Terraform:来自yaml的嵌套for循环
Posted
技术标签:
【中文标题】Terraform:来自yaml的嵌套for循环【英文标题】:Terraform: nested for loop from yaml 【发布时间】:2021-12-29 12:00:09 【问题描述】:我正在尝试在 terraform 上运行嵌套的 for
循环。
我有以下 Yaml 文件:
Employees:
- Department:
- Dev:
- name: "danielf"
role: developer
details:
email : danielf@example.com
firstname : daniel
lastname : folsik
- name: "johnb"
role: developer
details:
email : johnb@example.com
firstname : john
lastname : belk
- Ops:
- name: "benol"
role: devops
details:
email : benol@example.com
firstname : ben
lastname : olkin
- name: "pauld"
role: devops
details:
email : pauld@example.com
firstname : paul
lastname : dempler
我正在使用locals
获取yaml数据:
locals
ou_config = yamldecode(file("employees.yaml"))
我想使用 for_each 进入“Dev”和“Ops”列表中的对象列表。 例如,我想在“Dev”列表上运行以在第一次迭代中获取以下对象列表:
[
key = "email"
value = "danielf@example.com"
,
key = "firstname"
value = "daniel"
,
key = "lastname"
value = "folskin"
]
for_each 的下一次运行将是:
[
key = "email"
value = "johnb@example.com"
,
key = "firstname"
value = "john"
,
key = "lastname"
value = "belk"
]
等如何在 terraform 上进行操作?
【问题讨论】:
【参考方案1】:如果我理解正确,您尝试提取的只是该 yaml 文件的 details
部分...
为了得到所有,我会这样做:
locals
ou_config = yamldecode(file("employees.yaml"))
expanded_names = flatten([
for e in local.ou_config.Employees : [
for d in e.Department : [
for key, person in d : [
for key, value in person : [
value.details
]
]
]
]
])
output "test"
value = local.expanded_names
如果我们想要过滤,我们添加一个if key == "Dev"
locals
ou_config = yamldecode(file("employees.yaml"))
expanded_names = flatten([
for e in local.ou_config.Employees : [
for d in e.Department : [
for key, person in d : [
for key, value in person : [
value.details
]
] if key == "Dev"
]
]
])
output "test"
value = local.expanded_names
一个 terraform 计划如下所示:
Changes to Outputs:
+ test = [
+
+ email = "danielf@example.com"
+ firstname = "daniel"
+ lastname = "folsik"
,
+
+ email = "johnb@example.com"
+ firstname = "john"
+ lastname = "belk"
,
]
该格式应该比您建议的键值更容易在最终资源中循环
【讨论】:
以上是关于Terraform:来自yaml的嵌套for循环的主要内容,如果未能解决你的问题,请参考以下文章