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 →
- Use
countwith a conditional. - Reference safely with
one()ortry().
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.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?AdvancedA security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?Intermediate