gpt4 book ai didi

amazon-ec2 - 如何动态构建 terraform local_file

转载 作者:行者123 更新时间:2023-12-05 00:46:18 24 4
gpt4 key购买 nike

我想创建几个 EC2 实例并将它们的 private_ips 抓取到一个 ec2.ini 样式文件中,以便进一步与 Ansible 一起使用。

resource "local_file" "ec2_id" {
count = var.instance_count
content = "${aws_instance.instance[count.index].private_ip} ansible_ssh_user=ec2-user\n"
filename = "ec2.ini"
}

这总是打印最新创建的 EC2 实例的 private_ip。

知道如何解决这个问题。

更新:-

data "template_file" "hehe" {
count = var.instance_count
template = "${element(aws_instance.instance.*.private_ip, count.index)} ansible_ssh_user=ec2-user subnetmask=${element(split("/", data.aws_subnet.selected-subnet-id.cidr_block),1)}\n"
}


resource "local_file" "ec2_id" {
count = var.instance_count
content = "${element(data.template_file.hehe.*.rendered, count.index)}"
filename = "ec2.ini"
}

不起作用。给我最后创建的实例 private_ip。

最佳答案

当您使用 count 时在资源中,您要求 Terraform 创建该资源的多个实例。但是,在您的情况下,您没有包括 count.indexfilename参数,因此您的所有实例都在竞争覆盖相同的文件名 ec2.ini ,因此只有其中一个可以“获胜”。

听起来您的目标是只创建一个包含所有 IP 地址的文件。这与 Terraform String Templates 中的示例之一非常接近。我写这篇文章时的文档,我们可以像这样适应你的目标:

resource "local_file" "ec2_iini" {
filename = "ec2.ini"
content = <<-EOT
%{ for ip in aws_instance.instance.*.private_ip ~}
${ip} ansible_ssh_user=ec2-user
%{ endfor ~}
EOT
}

在上面的例子中,local_file资源本身count设置,因为我们的目标是只创建一个文件。相反,我们使用 Terraform 的 template for directive每个实例重复一次字符串模板,将结果收集为单个字符串,local_file然后可以用作它的content论据。

我使用了 string literal 的“heredoc”样式在这里,因为我认为它使 for通过将指令拆分为多行,指令更易于阅读。 -<<-EOT导致 Terraform 查看开口 <<-EOT 之间的所有线条和结束EOT并找到这些行共有的最少数量的前导空格,然后在渲染时将其剥离。这意味着您可以在配置中缩进模板,但避免出现在呈现的字符串中的缩进,这应该看起来像这样:

10.1.0.34 ansible_ssh_user=ec2-user
10.1.0.5 ansible_ssh_user=ec2-user
10.1.0.92 ansible_ssh_user=ec2-user

~两个 %{ ... } 末尾的标记指令指示 Terraform 的模板引擎忽略它们之后的换行符和空格,因此我们可以将模板包装在多行中,而无需在结果中引入额外的换行符。此处生成尾随换行符的唯一行是包含 IP 地址插值和 ansible_ssh_user 的中间行。部分,因此结果最终每个条目只有一个换行符,这似乎是这里的意图。

关于amazon-ec2 - 如何动态构建 terraform local_file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61404008/

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