Terraform for managing #MultiEnvironment infrastructure while keeping your code #DRY and organized.
Scenario:
You’re tasked with deploying infrastructure for three environments: dev, test, and prod. The resources (e.g., EC2 instances, S3 buckets , RDS ) are the same, but configuration values like instance type, AMI, or bucket names differ by environment.
Challenge:
How can you efficiently reuse the same Terraform configuration across multiple environments (dev, test, prod) without duplicating code?
Solution:
A solution is to use Terraform modules combined with environment-specific variable files to maintain DRY and modular infrastructure-as-code. Here’s how:
Define Terraform Modules: The module will contain the core resource definitions (e.g., EC2 instances, S3 buckets and RDS) and use variables for configurable values.
Create Environment-Specific .tfvars Files: Each environment (dev, test, prod) has its own .tfvars file to specify unique values, such as instance type, number of instances, etc.
Call the Module in the Root Configuration: The root configuration references the module and passes in variables from the .tfvars files.
Apply Configuration: Run the following to specify the environment file:
bash
terraform apply -var-file="dev.tfvars"
This approach allows you to reuse the module for all environments while keeping configurations separate and clean.
Example Script:
Here’s a quick example:
- Module Definition (modules/ec2/main.tf)
variable "instance_type" {}
variable "ami" {}
resource "aws_instance" "example" {
ami = var.ami
instance_type = var.instance_type
}
- Root Configuration (main.tf)
module "ec2" {
source = "./modules/ec2"
instance_type = var.instance_type
ami = var.ami
}
- Environment-Specific Variables (e.g., dev.tfvars)
instance_type = "t2.micro"
ami = "ami-123456"
Run terraform apply -var-file="dev.tfvars" to apply the configuration for the dev environment.