Interview Prep/Real-World Interview/Write-Terraform tasks

Write a conditional resource that only exists in production.

BeginnerHands-onWrite-Terraform tasks
Answer
resource "aws_cloudwatch_metric_alarm" "high_cpu" {
  count               = var.env == "prod" ? 1 : 0
  alarm_name          = "high-cpu-${var.env}"
  namespace           = "AWS/EC2"
  metric_name         = "CPUUtilization"
  statistic           = "Average"
  period              = 300
  evaluation_periods  = 2
  threshold           = 80
  comparison_operator = "GreaterThanThreshold"
}

output "alarm_arn" {
  value = one(aws_cloudwatch_metric_alarm.high_cpu[*].arn)
}

Key trick → count = cond ? 1 : 0 toggles a resource. one(...[*].arn) returns null when it doesn't exist, instead of an index error.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks