4

I'm trying to obtain the instance name from Terraform, data.aws_instance.foo.tags gives me a list of maps containing the name as one of the tags but I haven't been successful in getting the value for key Name from it.

Jakub Kania
  • 15,665
  • 2
  • 37
  • 47

2 Answers2

1

If have found a working solution using template rendering to by-pass the list of map's issue:

resource "aws_instance" "k8s_master" {
  count                       = "${var.master_count}"
  ami                         = "${var.ami}"
  instance_type               = "${var.instance_type}"
  vpc_security_group_ids      = ["${aws_security_group.k8s_sg.id}"]
  associate_public_ip_address = false
  subnet_id                   = "${element(var.subnet_ids,count.index % length(var.subnet_ids))}"
  user_data                   = "${file("${path.root}/files/user_data.sh")}"
  iam_instance_profile        = "${aws_iam_instance_profile.master_profile.name}"

  tags = "${merge(
    local.k8s_tags,
    map(
      "Name", "k8s-master-${count.index}",
      "Environment", "${var.environment}"
    )
  )}"
}

data "template_file" "k8s_master_names" {
  count    = "${var.master_count}"
  template = "${lookup(aws_instance.k8s_master.*.tags[count.index], "Name")}"
}

output "k8s_master_name" {
  value = [
    "${data.template_file.k8s_master_names.*.rendered}",
  ]
}

This will result in the following output:

k8s_master_name = [
    k8s-master-0,
    k8s-master-1,
    k8s-master-2
]
Boeboe
  • 2,070
  • 1
  • 17
  • 21
0

I found a somewhat similar solution for this on an aws_db_instance's by using just the lookup on this.

Here is a tag body:

tags = {
  TAG_KEY = "TAG_VALUE"
}

How to retrieve:

output "TAG_VALUE" {
  value = "${lookup(aws_db_instance.this.tags, "TAG_KEY", "default")}"
}

For

Outputs:

TAG_VALUE = TAG_KEY