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.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner