terraform

Concatenate a string with a variable


I'm trying to do a rather simple task in Terraform and it's not working:

tfvars:

hosted_zone       = "example.com"
domain            = "my.${var.hosted_zone}"

route_53_record:

resource "aws_route53_record" "regional" {
  zone_id = "${data.aws_route53_zone.selected.zone_id}"
  name    = "${var.domain}"
  type    = "A"
  ttl     = "300"
  records = ["4.4.4.4"]
}

When I run terraform plan I'm getting this:

+ aws_route53_record.regional
      id:                 <computed>
      allow_overwrite:    "true"
      fqdn:               <computed>
      name:               "my.${var.hosted_zone}"
      records.#:          "1"
      records.3178571330: "4.4.4.4"
      ttl:                "300"
      type:               "A"
      zone_id:            "REDACTED"

domain should be my.example.com. How do I join the variable hosted_zoned and a string to form domain?


Solution

  • You can't use interpolation in a tfvars file.

    Instead you could either join it directly in your Terraform like this:

    terraform.tfvars

    hosted_zone = "example.com"
    domain      = "my"
    

    main.tf

    resource "aws_route53_record" "regional" {
      zone_id = data.aws_route53_zone.selected.zone_id
      name    = "${var.domain}.${var.hosted_zone}"
      type    = "A"
      ttl     = "300"
      records = ["4.4.4.4"]
    }
    

    Or, if you always need to compose these things together you could use a local:

    locals {
      domain = "${var.domain}.${var.hosted_zone}"
    }
    
    resource "aws_route53_record" "regional" {
      zone_id = data.aws_route53_zone.selected.zone_id
      name    = local.domain
      type    = "A"
      ttl     = "300"
      records = ["4.4.4.4"]
    }