breezzz
breezzz

Reputation: 27

terraform take parameter name from variable

How i can do this right?

variable "vault_tag_name" {}
variable "vault_tag_value" {}


resource "aws_instance" "instance" {
  tags {
     Name  = "${var.name}"
     Group = "${var.group_tag}"
     "${var.vault_tag_name}" = "${var.vault_tag_value}"
  }
}

I have no errors from terraform, but result is wrong

tags.${var.vault_tag_name}:                ""
tags.%:                                    "3"
tags.Group:                                "test-dev"
tags.Name:                                 "test-dev"

Upvotes: 0

Views: 1128

Answers (1)

Edmund Dipple
Edmund Dipple

Reputation: 2434

According to this comment, dynamic variable names are not possible at this time in HCL.

You can use zipmap to emulate this, though it's a bit of a clunky workaround;

locals {
  ec2_tag_keys = ["Name", "Group", "${var.vault_tag_name}"]
  ec2_tag_vals = ["${var.name}", "${var.group_tag}", "${var.vault_tag_value}"]
}

resource "aws_instance", "instance" {
  ...
  tags = "${zipmap(local.ec2_tag_keys, local.ec2_tag_vals)}"
}

Result;

+ aws_instance.instance
      tags.%:                       "3"
      tags.Group:                   "MyGroup"
      tags.Name:                    "MyName"
      tags.MyTagName:               "MyTagValue"

Upvotes: 7

Related Questions