how to achieve a conditional block in terraform
You can use the count meta-argument to create conditional blocks in Terraform. The count meta-argument allows you to create multiple instances of a resource or module based on a condition. Here's an example:
Copy
resource "aws_instance" "example" {
count = var.create_instance ? 1 : 0
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
In this example, we are using the count meta-argument to conditionally create an EC2 instance based on the value of the create_instance variable. If the create_instance variable is true, then one instance will be created. If it is false, then no instances will be created.
You can also use the if expression to conditionally include or exclude a block of configuration. Here's an example:
Copy
locals {
environment = "production"
}
resource "aws_s3_bucket" "example" {
bucket = "my-bucket"
# Only enable versioning in production
dynamic "versioning" {
for_each = local.environment == "production" ? [1] : []
content {
enabled = true
}
}
}