Output Name tag of ALL EC2 instances of all types

Hello All,

I have several sets of resources of the aws_instance type, e.g. N nginx instances, M php instances etc. I would like to create an output which will print the names of all instances of all types.

It is easy to output all intances of one type:

output "ec2_instances" {
  description = "Names of EC2 instances"
  value       = aws_instance.nginx.*.tags.Name
}

but how can I output really all types in one output? A construction like aws_instance.*.*.tags.Name does not pass validation.

Does this match your purpose?


data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "nginx" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "ec2-nginx"
  }
}

resource "aws_instance" "php" {
  count = 2   // create multi instances
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "ec2-php-${count.index + 1}"
  }
}

output "ec2_instances" {
  description = "Names of EC2 instances"
  value       = concat(aws_instance.nginx.*.tags.Name, aws_instance.php.*.tags.Name)
}

applied:

Outputs:

ec2_instances = [
  "ec2-nginx",
  "ec2-php-1",
  "ec2-php-2",
]

Hello @JHashimoto0518 !

You are still enumerating instance types in concat(aws_instance.nginx.*.tags.Name, aws_instance.php.*.tags.Name) (i.e. you explicitly mention “nginx”, “php” etc) but I would like to avoid that. The whole purpose is to output all instances no matter of their type because enumerating does not scale well.

Hello @victor-sudakov,

I understood your situation. Unfortunately, I do not know how.

Neither do I. Somehow I need to iterate over aws_instance.* but don’t know how.

Terraform does not provide any way to do that, so you are required to reference each block explicitly.

Terraform does not provide any way to do that, so you are required to reference each block explicitly.

That’s unfortunate, but thank you @maxb for letting me know. At least I’ll stop looking for a solution which obviously does not exist.