ansible - 如何使用 Ansible 遍历字典?
问题描述
我有一个从 yaml 即子网 [0] (在 group_vars 的 all.yml 中)读取字典变量的任务。如果我想遍历整个字典怎么办?
- name: Create and/or update the subnet
azure_rm_subnet:
name: "{{ subnets[0].name }}"
address_prefix_cidr: "{{ subnets[0].prefix }}"
route_table: "{{ subnets[0].udr }}"
我尝试使用with_dict: "{{ subnets }}"然后即item.value.name 或item.name但剧本失败并出现错误。此外,如果不是所有对象都具有所有属性,即缺少子网[1].udr,是否可以检查任务中是否存在属性?我的 all.yml 文件如下所示:
subnets:
-
name: subnet1
prefix: 10.2.1.0/24
udr: rt1
nsg: sg1
-
name: subnet2
prefix: 10.2.1.0/24
nsg: sg1
解决方案
这比with_dict更接近with_items或with_subelements
你会像这样使用它:
- name: Create and/or update the subnet
azure_rm_subnet:
name: "{{ item.name }}"
address_prefix_cidr: "{{ item.prefix }}"
route_table: "{{ item.udr }}"
with_items:
- "{{ subnets }}"
子元素是在您曾经拥有此类项目的子元素的情况下。检查文档以进一步使用 ansbile 中的循环控制功能。
推荐阅读
- python - 在 for 循环的每次迭代中更改线图的颜色
- javascript - TypeError:无法在“HTMLSelectElement”上执行“添加”:提供的值不是“(HTMLOptionElement 或 HTMLOptGroupElement)”类型
- kubernetes - 从 kubernetes 访问 azure databricks 数据
- c - 如何实现数据输入验证
- git - 如何自动化一系列复杂的 git 历史重写?
- javascript - Jquery脚本不在脚本中工作但在控制台中工作
- amazon-web-services - AWS 爬虫卡在 STOPPING 状态
- xslt - 从 XML 创建 CSV 时 XSL 的性能
- php - 无法安装“全局”作曲家要求,因为“composer.json 不可写”
- excel - 双“根据列中的值选择行”