Bird
Raised Fist0
Terraformcloud~5 mins

Conditional expressions (ternary) in Terraform - Commands & Configuration

Choose your learning style10 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.

Practice

(1/5)
1. What does this Terraform conditional expression do?
var.is_production ? "prod" : "dev"
easy
A. Returns true or false
B. Always returns "prod"
C. Returns "prod" if var.is_production is true, otherwise "dev"
D. Causes a syntax error

Solution

  1. Step 1: Understand the condition

    The expression checks if var.is_production is true or false.
  2. Step 2: Evaluate the ternary expression

    If true, it returns "prod"; if false, it returns "dev".
  3. Final Answer:

    Returns "prod" if var.is_production is true, otherwise "dev" -> Option C
  4. Quick Check:

    Condition ? true_value : false_value = C [OK]
Hint: Remember: condition ? value_if_true : value_if_false [OK]
Common Mistakes:
  • Thinking it returns a boolean
  • Confusing true and false branches
  • Assuming it always returns the first value
2. Which of these is the correct syntax for a Terraform conditional expression?
easy
A. condition : true_val ? false_val
B. condition ? true_val : false_val
C. condition ? (true_val, false_val)
D. if (condition) then true_val else false_val

Solution

  1. Step 1: Recall Terraform conditional syntax

    Terraform uses the format: condition ? true_val : false_val.
  2. Step 2: Compare options

    Only condition ? true_val : false_val matches this syntax exactly.
  3. Final Answer:

    condition ? true_val : false_val -> Option B
  4. Quick Check:

    Correct ternary syntax = D [OK]
Hint: Look for question mark and colon in correct order [OK]
Common Mistakes:
  • Using if-then-else syntax from other languages
  • Swapping question mark and colon
  • Using commas inside the expression
3. Given this Terraform code:
variable "env" { default = "test" }
output "message" {
  value = var.env == "prod" ? "Deploy to production" : "Deploy to staging"
}

What will be the output value?
medium
A. Error: unknown variable
B. "Deploy to production"
C. "test"
D. "Deploy to staging"

Solution

  1. Step 1: Check variable value

    var.env is set to "test" by default.
  2. Step 2: Evaluate condition

    var.env == "prod" is false, so the false branch "Deploy to staging" is chosen.
  3. Final Answer:

    "Deploy to staging" -> Option D
  4. Quick Check:

    Condition false -> false branch output = A [OK]
Hint: Check variable value before condition evaluation [OK]
Common Mistakes:
  • Assuming default is "prod"
  • Confusing true and false branches
  • Expecting variable value as output
4. Identify the error in this Terraform conditional expression:
output "result" {
  value = var.enabled ? "yes" "no"
}
medium
A. Missing colon ':' between true and false values
B. Variable var.enabled is undefined
C. Quotes around values are incorrect
D. Ternary operator not supported in outputs

Solution

  1. Step 1: Review ternary syntax

    The correct syntax requires a colon ':' between true and false values.
  2. Step 2: Identify missing colon

    The expression has "? \"yes\" \"no\"" missing the ':' separator.
  3. Final Answer:

    Missing colon ':' between true and false values -> Option A
  4. Quick Check:

    Syntax error due to missing ':' = A [OK]
Hint: Check for '?' and ':' pair in ternary expressions [OK]
Common Mistakes:
  • Omitting the colon ':'
  • Misplacing quotes
  • Assuming ternary not allowed in outputs
5. You want to assign a resource name based on environment, but if the environment variable is empty or null, use "default" instead. Which expression correctly does this in Terraform?
var.env == "" || var.env == null ? "default" : var.env
hard
A. var.env == "" || var.env == null ? "default" : var.env
B. var.env == "" && var.env == null ? "default" : var.env
C. var.env ? "default" : var.env
D. var.env == null ? var.env : "default"

Solution

  1. Step 1: Understand the requirement

    If var.env is empty string or null, use "default"; else use var.env.
  2. Step 2: Analyze each option

    var.env == "" || var.env == null ? "default" : var.env checks if var.env is empty or null, then returns "default", else var.env, matching the requirement exactly.
  3. Final Answer:

    var.env == "" || var.env == null ? "default" : var.env -> Option A
  4. Quick Check:

    Check empty or null -> default else env = B [OK]
Hint: Check both empty string and null explicitly in condition [OK]
Common Mistakes:
  • Using && instead of || causing wrong logic
  • Assuming var.env alone checks for empty or null
  • Swapping true and false branches
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard