terraform - 如何从另一个资源中的计数资源访问属性?

标签 terraform

我正在使用 Terraform 编写 AWS 构建脚本。我正在跨多个可用区启动多个实例,在本例中为 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 地址。下面显示了我想做的事情:
resource "aws_eip" "elastic_ips" {
    count    = 2
    instance = "${aws_instance.myinstance[count.index].id}"
    vpc      = true
}

但是这个错误:

expected "}" but found "."



我也试过使用 lookup :
instance = "${lookup(aws_instance.sbc, count.index).id}"

但这失败并出现相同的错误。

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

最佳答案

请通过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)

所以在你的情况下,代码将是:
instance = "${element(aws_instance.myinstance.*.id, count.index}"

关于terraform - 如何从另一个资源中的计数资源访问属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679456/

相关文章:

azure - Terraform 计划在 Azure 云中失败

terraform - for_each 是从 Terraform 集中检索值的唯一方法吗?

terraform - 如何在 Terraform 中为 AWS CodeBuild 项目设置 'Source version'

amazon-web-services - 如何使用 cdktf 在运行时获取所有可用区?

amazon-web-services - Terraform Fargate 任务定义请求执行角色

azure - 根据输入在 Terraform 中动态创建角色分配

kubernetes - 使用 terraform 在 k8s 集群中授予 RBAC 角色

amazon-web-services - Terraform 未上传新的 ZIP

terraform - 通过云教程使用变量的问题

terraform - 如何使用 terraform 输出作为另一个 terraform 模板的输入变量