Conditional Expressions
Sometimes you need to make decisions in your configuration – for example, create a resource only in production, or choose a different value based on a variable. Terraform provides conditional expressions for this.
Conditional Syntax
The ternary operator:
condition ? true_val : false_valvariable "environment" { default = "dev" }
locals {
instance_type = var.environment == "prod" ? "t3.large" : "t2.micro"
enable_backup = var.environment == "prod" ? true : false
}Conditional Resource Creation
Use
count with a conditional to decide whether to create a resource.resource "aws_instance" "bastion" {
count = var.create_bastion ? 1 : 0
ami = "ami-abc123"
instance_type = "t2.micro"
}
# Then refer to it with element(aws_instance.bastion.*.id, 0) or try()Using
for_each with ConditionalsYou can also conditionally add items to a map:
locals {
extra_tags = var.environment == "prod" ? { Backup = "daily" } : {}
}Conditional in Variable Default
You can use conditionals inside variable defaults, but they cannot reference other variables. Use locals instead.
Example: Conditional Data Source
data "aws_ami" "ubuntu" {
count = var.use_custom_ami ? 0 : 1
most_recent = true
owners = ["099720109477"]
}
locals {
ami_id = var.use_custom_ami ? var.custom_ami_id : data.aws_ami.ubuntu[0].id
}Two Minute Drill
- Conditional expression:
condition ? true_val : false_val. - Use
count = condition ? 1 : 0to conditionally create a resource. - Conditionals work with variables, locals, and resource attributes.
- Combine with
for_eachand maps for advanced logic.
Need more clarification?
Drop us an email at career@quipoinfotech.com
