Terraform - Conditionals
Updated at 2022-08-25 07:49
Conditional definitions can be quite unintuitive in Terraform.
variable "environment" {
description = "Deployment environment; dev, qa or production"
type = string
default = "dev"
}
variable "create_hosted_zone" {
type = bool
default = false
}
variable "domain" {
type = string
}
# creates a new hosted zone
resource "aws_route53_zone" "primary" {
count = var.create_hosted_zone ? 1 : 0
name = var.domain
}
# uses an existing hosted zone
data "aws_route53_zone" "primary" {
count = var.create_hosted_zone ? 0 : 1
name = var.domain
}
locals {
hosted_zone_id = var.create_hosted_zone ? aws_route53_zone.primary[0].zone_id : data.aws_route53_zone.primary[0].zone_id
subdomain = var.environment == "production" ? "" : "${var.environment}."
}
resource "aws_route53_record" "root" {
zone_id = local.hosted_zone_id
name = "${local.subdomain}${var.domain}"
type = "A"
alias {
name = aws_lb.primary.dns_name
zone_id = aws_lb.primary.zone_id
evaluate_target_health = true
}
}