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

how to append a index number in terraform template file

我正在使用 terraform template.In 从 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 表示零-padding(而不是 space-padding)并且 2 表示两位数。

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

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

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