首页 > 解决方案 > 如何使用 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.nameitem.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

标签: ansible

解决方案


这比with_dict更接近with_itemswith_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 中的循环控制功能。


推荐阅读