terraform - 如何在 terraform 模板文件中附加索引号

标签 terraform terraform-template-file

我正在使用 terraform 模板从 terraform 准备 ansible 库存文件。我想创建一个如下所示的库存文件内容

slave-01 ansible_host=x.x.x.x
slave-02 ansible_host=x.x.x.x

所以在这里我无法根据该资源有多少个 IP 地址来附加数字 01,02...等

我正在尝试的模板文件如下

%{ for index,ip in test_slaves ~}
slave-[index] ansible_host=${ip}
%{ endfor ~}

我的资源文件是

resource "local_file" "hosts_cfg" {
  content = templatefile("${path.module}/templates/hosts.tpl",
    {
      test_slaves  = aws_instance.test-slaves.*.public_ip
    }
  )
  filename = "${path.module}/hosts.cfg"
}

请指导我如何处理这个问题?

最佳答案

正如您在 ip 值中所看到的,您可以使用模板插值将动态字符串插入到模板输出中。

但是,在您的情况下,您有一个数字,并且您希望它的格式与 Terraform 在将数字转换为字符串时默认采用的方式不同:您希望它用零填充以始终具有两位小数(我猜!)数字。

对于自定义数字格式 Terraform 有 the format function ,它允许您使用格式字符串向 Terraform 描述如何呈现您的号码。对于数字的十进制表示,我们可以使用 %d (“d”代表十进制),对于两位数的零填充,我们可以使用 02 前缀,其中0 表示零填充(而不是空格填充),2 表示两位数字。

将所有这些放在一起,我们可以通过将调用写入插值序列中来将对 format 的调用作为模板的一部分:

%{ for index, ip in test_slaves ~}
${format("slave-%02d", index + 1)} ansible_host=${ip}
%{ endfor ~}

我在此处包含了 slave- 前缀作为格式字符串的一部分,这说明 format 函数将仅传递任何不格式化“动词”的字符(以 % 开头)字面意思。您也可以将该前缀写入插值序列之外,具有相同的效果。

关于terraform - 如何在 terraform 模板文件中附加索引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67267803/

相关文章:

azure - 使用 terraform 从 azure signalr 检索primary_connection_string

amazon-sqs - 当 DLQ 尚不存在时,如何通过 Terraform 配置 SQS?

docker - 具有/Terraform Digitalocean负载平衡的Docker Swarm模式。如何自动缩放?

terraform - 在 terraform 中使用 count.index ?

terraform 将文件复制/上传到 aws ec2 实例

module - Terraform 模块依赖关系破坏了 template_file

json - 使用 Terraform 创建 Azure 策略

azure - 使用基于另一个本地创建的 for_each 本地变量时,Terraform 出现问题

azure - 运行 terraform init 后无法查看 Terraform 提供程序文件