Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - output instance ids from aws instance resource - one at a time

I have the following resource to create 2 was instances:

`resource "aws_instance" "prod_server" {
  count                  = "${var.instance_count}"
  instance_type          = "${var.instance_type}"
  ami                    = "${data.aws_ami.server_ami.id}"
  key_name               = "${aws_key_pair.prod_auth.id}"
  vpc_security_group_ids = ["${var.vpc_security_group}"]
  subnet_id              = "${element(var.subnets, count.index)}"
  user_data              = "${data.template_file.user-init.*.rendered[count.index]}"

  tags {
    Name = "prod_server-${count.index+1}"
  }
}`

where the value for count is 2.

I want to output the instance ids for each instance using a separate output resource as below:

`output "server_id1" {
  value = "${aws_instance.prod_server.0.id}"
}

output "server_id2" {
  value = "${aws_instance.prod_server.1.id}"
}`

However I keep getting the below error: Resource 'aws_instance.prod_server' not found for variable 'aws_instance.prod_server.1.id'

I realise that I can get the ids at once using: "${aws_instance.prod_server.*.id}"

But I do have a specific reason for wanting to get them one by one.

Could someone please advise/help me out on this?

like image 397
Hamza Avatar asked May 27 '18 06:05

Hamza


1 Answers

You can use element like this:

output "server_id1" {
  value = "${element(aws_instance.prod_server.*.id, 0)}"
}
like image 149
Brandon Miller Avatar answered Sep 20 '22 02:09

Brandon Miller