0
0
Terraformcloud~5 mins

Conditional expressions (ternary) in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to choose between two values based on a condition in your infrastructure code. Conditional expressions let you do this simply and clearly in Terraform.
When you want to set a resource property differently depending on an environment variable.
When you need to choose between two instance types based on a cost-saving flag.
When you want to enable or disable a feature based on a boolean input.
When you want to assign a tag value conditionally depending on a deployment stage.
When you want to select a subnet ID based on whether the deployment is in production or testing.
Config File - main.tf
main.tf
variable "is_production" {
  type    = bool
  default = false
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.is_production ? "t3.large" : "t3.micro"

  tags = {
    Name = var.is_production ? "prod-server" : "dev-server"
  }
}

This Terraform file defines a boolean variable is_production to indicate the environment.

The aws_instance resource uses conditional expressions to set the instance_type and Name tag based on whether is_production is true or false.

If is_production is true, it uses a larger instance and a production tag; otherwise, it uses a smaller instance and a development tag.

Commands
This command initializes the Terraform working directory, downloading necessary provider plugins and preparing the environment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
This command shows what Terraform will do based on the current configuration and variables. It helps verify the conditional expressions are working as expected.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t3.micro" + tags = { + "Name" = "dev-server" } } Plan: 1 to add, 0 to change, 0 to destroy. ───────────────────────────────────────────────────────────────────────────── Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.
This command applies the planned changes to create or update infrastructure. The -auto-approve flag skips manual confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Still creating... [10s elapsed] aws_instance.example: Creation complete after 15s [id=i-0abcd1234efgh5678] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
-auto-approve - Automatically approve the apply without prompting
This command shows any output values defined in the configuration. Here, it confirms the infrastructure state after applying.
Terminal
terraform output
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: a conditional expression lets you pick one of two values based on a true or false condition in your Terraform code.

Common Mistakes
Using an assignment (=) instead of a question mark (?) and colon (:) for the conditional expression
Terraform syntax requires the ternary operator format: condition ? true_value : false_value. Using = causes a syntax error.
Write the condition as var.is_production ? "t3.large" : "t3.micro" without any equals sign.
Using a non-boolean variable directly as a condition without comparison
Terraform requires the condition to be a boolean expression. Using a string or number directly causes an error.
Ensure the variable is boolean or compare it explicitly, e.g., var.env == "prod" ? value1 : value2.
Forgetting to wrap string values in quotes in the conditional expression
Terraform expects string literals to be quoted. Missing quotes cause parsing errors.
Always put string values in double quotes, like "prod-server".
Summary
Initialize Terraform with 'terraform init' to prepare the environment.
Use 'terraform plan' to preview changes and verify conditional expressions.
Apply changes with 'terraform apply -auto-approve' to create resources based on conditions.