我正在创建一个以云形成形式编写的 AWS 堆栈集(在组织级别)。对于云的形成,它被写入 terraform 模板文件中,以便从 terraform 传递变量。然而,有一个部分我遇到了问题。
for
部分需要查看原理并在模板中创建Principal
块。然而,循环的最后一个索引包含一个逗号,这将使堆栈模板无效。
terraform 中是否有防止循环中最后一个逗号的方法?
main.tf:
variable "cross_account" {
type = list(object({
principals = list(string)
}))
default = [
{
principals = ["ACCOUNT_ID1","ACCOUNT_ID2","ACCOUNT_ID3"]
}
]
}
output "test" {
value = templatefile("./json.tpl", {
principals = var.cross_account[0].principals
})
}
模板文件(json.tpl):
"Principal": {
"AWS": [
%{ for princ in principals ~}
{
"Fn::Sub": "arn:aws:iam::${princ}:root"
}
, # <--------------- Need to prevent this line on the last loop index
%{ endfor ~}
]
我已将代码缩短为仅上面所需的位。谢谢
您可以使用jsonencode:
"Principal": {
"AWS": ${jsonencode([
for princ in principals:
{
"Fn::Sub": "arn:aws:iam::${princ}:root"
}
])}
或者您可以将其用于所有模板,如此处所示,具体取决于您的模板的定义方式。
在@Marcin 的帮助下玩了一段时间后,能够得到一个工作代码:
main.tf:
variable "cross_account" {
type = list(object({
principals = list(string)
}))
default = [
{
principals = ["ACCOUNT_ID1","ACCOUNT_ID2","ACCOUNT_ID3"]
}
]
}
output "test" {
value = templatefile("./json.tpl", {
principals = jsonencode([for i in var.cross_account[0].principals: tomap({"Fn::Sub" = "arn:aws:iam::${i}:root"})])
})
}
模板文件(json.tpl):
"Principal": {
"AWS": ${principals}
}
结果如下,没有额外的逗号:
test = <<-EOT
"Principal": {
"AWS": [{"Fn::Sub":"arn:aws:iam::ACCOUNT_ID1:root"},{"Fn::Sub":"arn:aws:iam::ACCOUNT_ID2:root"},{"Fn::Sub":"arn:aws:iam::ACCOUNT_ID3:root"}]
}
EOT
我今天遇到了这个问题,这是我的解决方案,以防它对任何人有帮助。
"Principal": {
"AWS": [
%{ for princ in principals ~}
{
"Fn::Sub": "arn:aws:iam::${princ}:root"
}
%{ if index(principals, princ) == length(principal)-1 }
#do nothing-here if we are on the last iteration
%{ else}
, #add the comma otherwise
%{ endif }
%{ endfor ~}
]