"IF" Conditional Resource Creation in Terraform
In Terraform, you can conditionally create resources based on certain conditions. This is often done using the count
parameter along with a conditional expression. Here's how you can implement an "if" statement-like behavior:
Using count
for Conditional Creation
The count
parameter can be set to either 0 or 1 based on a condition:
resource "aws_instance" "example" {
count = var.environment == "production" ? 1 : 0
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
In this example, the EC2 instance will only be created if the environment
variable is set to "production".
Checking Environment Variables
You can also use environment variables in your conditions:
variable "create_resource" {
type = bool
default = tobool(coalesce(trimspace(get(jsondecode(nonsensitive(data.aws_ssm_parameter.my_vars.value)), "CREATE_RESOURCE", null)), "false"))
}
resource "aws_s3_bucket" "conditional_bucket" {
count = var.create_resource ? 1 : 0
bucket = "my-conditional-bucket"
}
Here, we're using a more complex setup to read an environment variable from AWS Systems Manager Parameter Store, but you could also use Terraform's built-in terraform.workspace
or other environment-specific variables.
Using Maps for Environment-Specific Conditions
You can use maps to store environment-specific conditions:
variable "env_resource_count" {
type = map(number)
default = {
dev = 0
test = 1
prod = 1
}
}
resource "aws_instance" "example" {
count = lookup(var.env_resource_count, terraform.workspace, 0)
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
This approach allows you to specify different counts for different environments.
Remember, when using count
, you'll need to refer to your resources using the index syntax, e.g., aws_instance.example[0]
.