Conditional Expressions

The ternary condition ? true_value : false_value chooses a value based on a boolean.

Syntaxcondition ? true_value : false_value

A conditional expression picks one of two values based on a boolean condition, using the familiar ternary form condition ? a : b.

Typical uses

  • Bigger instances in prod, smaller in dev.
  • Enable a feature only in certain environments.
  • Provide a fallback default.

Combine conditionals with variables to make one configuration adapt to many environments.

Example

Example · hcl
variable "environment" {
  type = string
}

resource "aws_instance" "web" {
  ami = "ami-0c02fb55956c7d316"

  # Larger instance in production, small elsewhere
  instance_type = var.environment == "prod" ? "t3.large" : "t3.micro"

  monitoring = var.environment == "prod" ? true : false
}

When to use it

  • A configuration uses a conditional to set instance_type = var.env == 'production' ? 'm5.large' : 't3.micro', selecting the right size without two separate resource blocks.
  • A team enables multi_az on an RDS instance only when the environment variable equals 'production', keeping dev costs low with a single toggle.
  • A module uses a conditional to set min_size = var.high_availability ? 3 : 1 so the caller controls whether the ASG is HA or single-instance.

More examples

Conditional instance type

Selects the instance type using a ternary expression based on the environment variable value.

Example · hcl
variable "environment" { default = "dev" }

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.environment == "production" ? "m5.large" : "t3.micro"
}

Conditional RDS multi-AZ

Enables RDS Multi-AZ only for production by embedding a boolean conditional expression in the multi_az argument.

Example · hcl
variable "environment" { default = "staging" }

resource "aws_db_instance" "app" {
  engine            = "postgres"
  instance_class    = "db.t3.micro"
  allocated_storage = 20
  username          = "admin"
  password          = var.db_password
  multi_az          = var.environment == "production" ? true : false
}

Conditional resource count with count

Uses a conditional expression with count to optionally create a CloudWatch alarm based on a boolean feature flag variable.

Example · hcl
variable "enable_monitoring" {
  type    = bool
  default = false
}

resource "aws_cloudwatch_metric_alarm" "cpu" {
  count               = var.enable_monitoring ? 1 : 0
  alarm_name          = "high-cpu"
  comparison_operator = "GreaterThanThreshold"
  threshold           = 80
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  period              = 300
  evaluation_periods  = 2
  statistic           = "Average"
}

Discussion

  • Be the first to comment on this lesson.