如何从另一个资源中的计数资源访问属性? [英] How do I access an attribute from a counted resource within another resource?

查看:20
本文介绍了如何从另一个资源中的计数资源访问属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Terraform 编写 AWS 构建脚本.我正在跨多个可用区启动多个实例,在此示例中为 2:

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
}

我现在需要为这些实例分配一个弹性 IP,以便将来我可以在不更改 IP 地址的情况下重建这些实例.下面显示了我喜欢做什么:

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
}

但是这个错误:

应为}",但找到."

我也尝试过使用 lookup:

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

但失败并出现同样的错误.

but that fails with the same error.

如何将弹性 IP 附加到这些实例?

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

推荐答案

请通过terraform 插值 - 元素列表索引

element(list, index) - 从给定索引处的列表中返回单个元素.如果索引大于元素的数量,则此函数将使用标准 mod 算法进行换行.此功能仅适用于平面列表.例子:

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}"

这篇关于如何从另一个资源中的计数资源访问属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆