"指令的"内的Terraform模板文件中未计算Format()函数 [英] format( ) function not not evaluating in Terraform template file within "for" directive

查看:0
本文介绍了"指令的"内的Terraform模板文件中未计算Format()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先了解一些问题的上下文,这样也许有人可以将我重定向到正确的答案/帖子。我学习Terraform已经有几天了,现在我想在部署我的TF文件时生成一个可行的清单。

经过大量的初学者搜索,我发现对于像我这样的初学者来说,数据和模板文件很重,但我可以这样-科学怪人-怪物我的方式:

resource "local_file" "inventory" {
  content = templatefile("${path.module}/templates/hosts.tpl",
    {
      master        = aws_instance.master.*.public_ip
      nodes_ubuntu  = aws_instance.node.*.public_ip
     }
  )
  filename = "./inventory"
}

使用如下格式的模板文件:

[master]
%{ for ip in master ~}
control ansible_host=${ip}
%{ endfor ~}

[nodes_ubuntu]

%{ for ip in nodes_ubuntu ~}

$${format{"withCurly-%02d",index + 1}} ansible_host=${ip}

$${format("WithRound-%02d",index + 1)} ansible_host=${ip}

format("PureFormat-%02s",index+1) ansible_host=${ip}

#These are possible combinations I used and failed for format()

%{ endfor ~}

这会导致混淆:

[master]
control ansible_host=ip.add.re.ss

[nodes_ubuntu]

${format{"withCurly-%02d",index + 1}} ansible_host=ip.add.re.ss

${format("WithRound-%02d",index + 1)} ansible_host=ip.add.re.ss

format("PureFormat-%02s",index+1) ansible_host=ip.add.re.ss

While,

${format("WithRound-%02d",index + 1)} ansible_host=${ip}
生成错误 Invalid value for "vars" parameter: vars map does not contain key "index"

我原以为是这样的:

[nodes_ubuntu]
ubuntu-01 ansible_host= ip.add.re.ss

我如何更正代码,或者是Terraform错误,因为我看到类似的代码工作,但忘记记下引用。

Terraform

您描述的第一个结果(函数调用保留在输出中)是因为您使用$${来转义正常的${模板内插序列,而是要求推荐答案插入文字${。如果您正在为另一种使用${表示某种含义的语言生成源代码,那么这将是一件合适的事情,但是由于您希望Terraform计算该内插值,因此您必须使用非转义的${形式,就像您在第二个例子中尝试的那样。

您在修复不正确的转义时看到的问题是,您没有在调用templatefile或在模板中本地声明任何符号index

如果您的目标是使用nodes_ubuntu的每个元素的索引,则可以通过在for指令中声明第二个符号来实现。如果给出两个符号,则第一个表示键/索引,第二个表示值:

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

这是使用count声明的资源对象列表的有效方法,但在采用此策略之前,请务必考虑这在将来维护时的行为:TerraForm通过它们在计数中的索引来跟踪这些对象,因此如果您稍后增加资源count,将在末尾添加一个新索引。如果减少count,则始终会从该列表的末尾删除条目。如果您替换任何一个主机,则相应的索引将在此模板结果中更改其IP地址。

如果这多个虚拟机更像牛而不是宠物,那么这些限制就很好了,也就是说,如果您需要销毁其中的一个,那么它们都同样可以销毁。如果它们中的任何一个具有独特的特征,可能会导致您想要专门销毁列表中间的一个,则不是一个好的设计。

在您的案例中,这看起来是合适的,因为您已经在不同的资源中区分了";master";和";node";角色,因此希望这些节点都是可替换的。我之所以提到它,只是因为编写Terraform配置是一个相对常见的陷阱,这意味着实例在实际不可替换时是可替换的,这可能会导致以后的维护问题。

(有关详细信息,请参阅When to Use for_each Instead of count。)

这篇关于"指令的"内的Terraform模板文件中未计算Format()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆