Interview Prep/Terraform/Resources Variables and Expressions

A monitoring stack should only exist in prod. How do you create a resource conditionally?

BeginnerScenarioResources Variables and Expressions
Answer

Situation read → On/off switch for a resource or module.

What I'd do →

  1. Use count with a conditional.
  2. Reference safely with one() or try().
resource "aws_cloudwatch_dashboard" "main" {
  count          = var.environment == "prod" ? 1 : 0
  dashboard_name = "app"
  dashboard_body = local.dashboard_json
}

output "dashboard_arn" {
  value = one(aws_cloudwatch_dashboard.main[*].dashboard_arn)
}

Why → one() returns null for an empty list and the element for a single item, which avoids [0] index errors when count is 0.

Interview tip → Prefer a boolean enable_x variable over environment-name checks inside modules.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions