Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an attribute from a counted resource within another resource?

Tags:

terraform

I'm using Terraform to script an AWS build. I'm spinning up a number of instances across multiple availability zones, in this example, 2:

resource "aws_instance" "myinstance" {
    count                   = 2
    ami                     = "${var.myamiid}"
    instance_type           = "${var.instancetype}"
    availability_zone       = "${data.aws_availability_zones.all.names[count.index]}"
    # other details omitted for brevity
}

I now need to assign an Elastic IP to these instances, so that I can rebuild the instances in the future without their IP address changing. The below shows what I'd like to do:

resource "aws_eip" "elastic_ips" {
    count    = 2
    instance = "${aws_instance.myinstance[count.index].id}"
    vpc      = true
}

But this errors with:

expected "}" but found "."

I've also tried using lookup:

instance = "${lookup(aws_instance.sbc, count.index).id}"

but that fails with the same error.

How can I go about attaching Elastic IPs to these instances?

like image 278
James Thorpe Avatar asked Jun 21 '17 14:06

James Thorpe


People also ask

How do you use count in terraform?

How to use Terraform Count. We use count to deploy multiple resources. The count meta-argument generates numerous resources of a module. You use the count argument within the block and assign a whole number (could by variable or expression), and Terraform generates the number of resources.

What is .ID terraform?

Terraform today treats the name id as a bit special for some historical reasons, but from a user perspective (as opposed to a provider developer perspective) it's just like any other attribute: it means whatever the provider decides that it means.

What are attributes in terraform?

Note: The Plugin Framework is in beta. Attributes are the fields in a resource, data source, or provider. They hold the values that end up in state. Every attribute has an attribute type, which describes the constraints on the data the attribute can hold.


1 Answers

This works for me,

instance = aws_instance.myinstance.*.id
like image 197
Vikk_King Avatar answered Oct 28 '22 06:10

Vikk_King