Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform Combine Variable and String

Tags:

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?

like image 432
user3063045 Avatar asked Feb 18 '19 16:02

user3063045


People also ask

How do you concatenate strings in Terraform?

so to add a simple answer to a simple question: enclose all strings you want to concatenate into one pair of "" reference variables inside the quotes with ${var.name}

What is ${} in Terraform?

Embedded within strings in Terraform, whether you're using the Terraform syntax or JSON syntax, you can interpolate other values. These interpolations are wrapped in ${} , such as ${var. foo} . The interpolation syntax is powerful and allows you to reference variables, attributes of resources, call functions, etc.

How do you concatenate a string and variable in Terraform?

For Terraform 0.12 and later, you can use the join() function, to allow you to join or concatenate strings in your Terraform plans. The terraform join function has two inputs, the separator character and a list of strings we wish to join together.


1 Answers

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"]
}
like image 74
ydaetskcoR Avatar answered Sep 17 '22 12:09

ydaetskcoR