Terraform 创建具有特定键的动态映射。

huangapple go评论56阅读模式
英文:

Terraform create map with certain keys dynamic

问题

我想定义一个像这样的映射

MyMap = {
"abc" = {
}
"pqr" = {
}
"key-1" = {
}
"key-2" = {
}
"key-3" = {
}
"key-4" = {
}
}


这只是一个示例,但我可以有许多"key-n"键。我想知道是否可以使用一些for循环魔法来动态生成"key-n"键,而其余的键保持静态。我找不到任何这样的示例。我的目标是找到一种类似于以下的方法(下面的代码不起作用)

MyMap = {
"abc" = {
}
"pqr" = {
}
for i in range(1, n) :
"key-${i}" => {
}
}

英文:

I want to define a map like this

MyMap = {
  "abc" = {
  }
  "pqr" = {
  }
  "key-1" = {
  }
  "key-2" = {
  }
  "key-3" = {
  }
  "key-4" = {
  }
}

This is just an illustration but I can have many "key-n" keys. I was wondering if I could do some for loop magic to generate "key-n" keys dynamically while rest of the keys static. I am not finding any such examples. My goal is to find a way to do something like (below does not work)

MyMap = {
  "abc" = {
  }
  "pqr" = {
  }
  for i in range(1, n) :
  "key-${i}" => {
  }
}

答案1

得分: 1

这并没有直接的语法,但你可以通过合并两个地图来实现相同的结果,其中一个地图是直接编写的,另一个是使用表达式动态生成的。

example = merge(
  tomap({
    "abc" = {
    }
    "pqr" = {
    }
  }),
  tomap({
    for i in range(1, n) : "key-${i}" => {
    }
  }),
}

参考资料:

英文:

There is not any direct syntax for this but you can achieve the same result by merging two maps together, where one of them is written out literally and the other one is generated dynamically using an expression.

example = merge(
  tomap({
    "abc" = {
    }
    "pqr" = {
    }
  }),
  tomap({
    for i in range(1, n) : "key-${i}" => {
    }
  }),
}

References:

huangapple
  • 本文由 发表于 2023年6月22日 01:56:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定