gpt4 book ai didi

amazon-ec2 - 如何遍历 terraform 中的所有 aws_instances?

转载 作者:行者123 更新时间:2023-12-03 09:57:24 24 4
gpt4 key购买 nike

我是 terraform 的新手,我正在尝试遍历所有 aws_instances 以应用 null_resource。您能否使用多个 splat 来访问所有实例,而不管它们的名称?

EC2 实例分为三种类型:

aws_instance.web.* (3 instances)
aws_instance.app.* (3 instances)
aws_instance.db.* (2 instances)

这是我对所有八个 aws_instances 应用 null_resource 的尝试:

resource "null_resource" "install_security_package" {

#count = "${length(aws_instance)}" #terraform error: resource count can't reference variable: aws_instance
#count = "${length(aws_instance.*)}" #terraform error: resource variables must be three parts: TYPE.NAME.ATTR
count = "${length(aws_instance.*.*)}" #terraform error: unknown resource 'aws_instance.*'

connection {
type = "ssh"
host = "${element(aws_instance.*.private_ip, count.index)}"
user = "${lookup(var.user, var.platform)}"
private_key = "${file("${var.private_key_path}")}"
timeout = "2m"
}

provisioner "remote-exec" {
inline = [
"sudo rpm -Uvh http://www.example.com/security/repo/security_baseline.rpm",
]
}
}

最佳答案

目前无法匹配给定类型的所有资源。如您所见,“splat”语法仅允许选择从特定资源 block 创建的所有实例。

今天使用 Terraform 最接近的方法是将不同的资源连接在一起:

concat(aws_instance.web.*.private_ip, aws_instance.app.*.private_ip, aws_instance.db.*.private_ip)

在这个答案的当前版本的 Terraform 中,有必要使用 github issue #4084 中共享的一些解决方法为了避免在多个地方重复那个复杂的表达式。即将推出的功能称为 Local Values将在不久的将来使这更简单,允许为列表命名以在多个地方重复使用:

# Won't work until Terraform PR#15449 is merged and released
locals {
aws_instance_addrs = "${concat(aws_instance.web.*.private_ip, aws_instance.app.*.private_ip, aws_instance.db.*.private_ip)}"
}

resource "null_resource" "install_security_package" {

count = "${length(local.aws_instance_addrs)}"

connection {
type = "ssh"
host = "${local.aws_instance_addrs[count.index]}"
user = "${lookup(var.user, var.platform)}"
private_key = "${file("${var.private_key_path}")}"
timeout = "2m"
}

provisioner "remote-exec" {
inline = [
"sudo rpm -Uvh http://www.example.com/security/repo/security_baseline.rpm",
]
}
}

关于amazon-ec2 - 如何遍历 terraform 中的所有 aws_instances?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com