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

跟風遠走 提交于 2020-07-18 11:43:44

问题


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?


回答1:


Please go through terraform interpolation - element list index

element(list, index) - Returns a single element from a list at the given index. If the index is greater than the number of elements, this function will wrap using a standard mod algorithm. This function only works on flat lists. Examples:

element(aws_subnet.foo.*.id, count.index)

So in your case, the code will be:

instance = "${element(aws_instance.myinstance.*.id, count.index}"



回答2:


A bit more playing around and I've found the answer - you can index into the "splat" syntax:

instance = "${aws_instance.myinstance.*.id[count.index]}"



回答3:


Other answers already pointed out that counted elements must be accessed via indexes. I like to add that I encountered the error

Because aws_instance.some-resource has "count" set, its attributes must be accessed on specific instances.

although I had already fixed that particular line. The error kept showing up, mentioning a line with some code segment that was not even present any longer in my code.

I was able to resolve this by fixing all places where I had not accessed a specific instance (which were also mentioned in other errors). In my case, an output section was not adapted previously. Only then all errors disappeared all of a sudden.




回答4:


try using aws_instance.jserver[count.index].id

e.g. of ec2 instance and volume attachment is

  resource "aws_instance" "jserver"{
    count=3
  }
  
  resource "aws_volume_attachment" "j_ebs_att" {
    count = 3
    ...
    instance_id = aws_instance.jserver[count.index].id
  }


来源:https://stackoverflow.com/questions/44679456/how-do-i-access-an-attribute-from-a-counted-resource-within-another-resource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!