This example uses a terraform.tfvars file and workspaces to manage different environments (dev, staging, prod) for a simple web application using AWS.
File Structure:
text
project/
├── main.tf
├── variables.tf
├── terraform.tfvars
└── dev.tfvars # (Optional, alternative to workspaces)
This file defines the input variables, allowing you to customize each environment.
hcl
variable "environment" {
description = "The deployment environment (dev, staging, prod)"
type = string
default = "dev"
}
variable "instance_type" {
description = "The EC2 instance type"
type = string
# No default here, it will be set in terraform.tfvars
}
variable "instance_count" {
description = "Number of EC2 instances to create"
type = number
}
variable "enable_monitoring" {
description = "Whether to enable detailed monitoring"
type = bool
default = false
}
This file sets the common variables. You can override these per environment using -var-file or workspaces.
hcl
# Common settings (can be overridden)
instance_type = "t3.micro"
instance_count = 1
enable_monitoring = false
This is the main configuration that uses the variables to create resources. The local.env prefix is a best practice to avoid naming conflicts.
hcl
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
}
# Create a local value to simplify naming conventions
locals {
env_prefix = "${var.environment}-myapp"
}
# Create a VPC (simplified)
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "${local.env_prefix}-vpc"
Env = var.environment
}
}
# Create an EC2 instance
resource "aws_instance" "web" {
# The count meta-argument allows us to scale per environment
count = var.instance_count
ami = "ami-0cff7528ff583bf9a" # Amazon Linux 2 AMI
instance_type = var.instance_type
monitoring = var.environment == "prod" ? true : var.enable_monitoring # Enable monitoring automatically if prod
tags = {
Name = "${local.env_prefix}-web-${count.index + 1}"
Env = var.environment
}
}
# Output the public IPs of the created instances
output "instance_public_ips" {
description = "Public IP addresses of the EC2 instances"
value = aws_instance.web[*].public_ip
}
Step 1: Initialize and Deploy to Dev
bash
# Initialize Terraform
terraform init
# Deploy to the default environment (dev, as per variables.tf)
terraform apply -var-file="terraform.tfvars"
Step 2: Create a Workspace for Staging & Deploy
Workspaces allow you to manage distinct state files for each environment.
bash
# Create a new workspace for staging
terraform workspace new staging
# Deploy the staging environment, overriding any variables
terraform apply -var="environment=staging" -var="instance_count=2"
Step 3: Create a Workspace for Production & Deploy
bash
# Create a new workspace for production
terraform workspace new prod
# Deploy to production with more powerful instances and monitoring
terraform apply -var="environment=prod" -var="instance_type=t3.medium" -var="instance_count=3" -var="enable_monitoring=true"
To switch between environments to make changes:
bash
# See current workspace
terraform workspace show
# Switch to staging workspace
terraform workspace select staging
# Make changes only to staging
terraform apply -var="environment=staging" -var="instance_count=2"
This is a simple, cost-effective setup for a static website hosted on AWS S3 and CloudFront.
hcl
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# Create a unique S3 bucket name
resource "random_id" "bucket_suffix" {
byte_length = 4
}
locals {
bucket_name = "my-portfolio-${random_id.bucket_suffix.hex}"
domain_name = "myportfolio.com" # CHANGE THIS TO YOUR DOMAIN
}
# S3 Bucket for hosting the static site
resource "aws_s3_bucket" "portfolio_bucket" {
bucket = local.bucket_name
}
resource "aws_s3_bucket_website_configuration" "portfolio_config" {
bucket = aws_s3_bucket.portfolio_bucket.bucket
index_document {
suffix = "index.html"
}
error_document {
key = "error.html"
}
}
# Make bucket contents public
resource "aws_s3_bucket_public_access_block" "portfolio_public_access" {
bucket = aws_s3_bucket.portfolio_bucket.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
resource "aws_s3_bucket_policy" "allow_public_read" {
bucket = aws_s3_bucket.portfolio_bucket.id
policy = data.aws_iam_policy_document.allow_public_read.json
}
data "aws_iam_policy_document" "allow_public_read" {
statement {
principals {
type = "*"
identifiers = ["*"]
}
actions = [
"s3:GetObject"
]
resources = [
"${aws_s3_bucket.portfolio_bucket.arn}/*",
]
}
}
# Upload a simple index.html file
resource "aws_s3_object" "index" {
bucket = aws_s3_bucket.portfolio_bucket.bucket
key = "index.html"
source = "./index.html" # You need to create this HTML file
content_type = "text/html"
etag = filemd5("./index.html")
}
# Output the website URL
output "website_url" {
description = "URL of the portfolio website"
value = aws_s3_bucket_website_configuration.portfolio_config.website_endpoint
}
html
<!DOCTYPE html>
<html>
<head>
<title>My Portfolio</title>
</head>
<body>
<h1>Welcome to My Work Portfolio</h1>
<p>This site is hosted on AWS S3, deployed with Terraform!</p>
</body>
</html>
bash
# Save the main.tf and index.html files
terraform init
terraform apply
# Type 'yes' when prompted. Terraform will output the website URL.
Important Note: Always run terraform plan before apply to review what will be created. Remember to terraform destroy when you are finished to avoid unnecessary cloud costs.
At Avalogs.com, we offer IT consulting services in terraform iaas focused on supporting your business servers and the infrastructure ti provision strategy. Our consultants analyze your current systems and processes and offer solutions that increase your efficiency. Together, we ensure your technology aligns with your business goals.
Copyright © 2025 Avalogs.com - All rights reserved
We gebruiken cookies om websiteverkeer te analyseren en de ervaring op je website te optimaliseren. Als je het gebruik van cookies accepteert, worden je gegevens gecombineerd met de gegevens van alle andere gebruikers.