首页 > 解决方案 > 如何在 Ansible 中将两个循环合二为一

问题描述

我有这部分代码负责为特定服务器向 Imperva 添加规则。

有很多嵌套变量,所以我不会解释它的所有部分,而是只关注一个问题。

问题是这个任务中不能有两个循环。

我添加了循环:“{{ list_of_codes }}”并且还有使用 with_items -> with_items 的旧代码部分:“{{ ic_dc_stat_list.json | default({}) | json_query('DCs[?name== Fontend_USA].id ') }}"

这是我正在谈论的任务:

    - name: "Add [USA] Rule"
      run_once: true
      delegate_to: 127.0.0.1
      uri:
        url: "{{ ic_api_url_sites_rules }}/add"
        method: POST
        validate_certs: false
        body: "{{ ic_auth }}&\
        site_id={{ _site_id }}&\
        dc_id={{ ic_dc_stat_id }}&\
        name=USA&\
        filter=CountryCode == {{ item }}&\
        {{ rules.action.frw_dc }}"
      loop: "{{ list_of_codes }}"
      vars:
        ic_dc_stat_id: "{{ item }}"
        _site_id: "{{ ic_site_stat.json.site_id | default(incapsula_brand_domain.site_id) | default(site_id)}}"
      with_items: "{{ ic_dc_stat_list.json | default({}) | json_query('DCs[?name==`Fontend_USA`].id') }}"
      when: ( not ic_rules.json.delivery_rules | json_query('Forward[?name==`USA`]') )
            and ( ic_abigail and not ic_cs )
      register: ic_rules_latam_stat
      changed_when: "'skipped' not in ic_rules_latam_stat"

循环list_of_codes应在此处添加国家代码filter=CountryCode == {{ item }}

这是提到的循环的详细信息:

list_of_codes:
 - "MX" # Mexico
 - "GT" # Guatemala
 - "HN" # Honduras
 - "NI" # Nicaragua
 - "CU" # Cuba
 - "DO" # Dominican Republic
 - "CR" # Costa Rica
 - "SV" # El Salvador
 - "PA" # Panama

我正在寻找实现list_of_codes的最佳方法,但是当任务中已经有一个循环时如何执行此操作 -> with_items: "{{ ic_dc_stat_list.json | default({}) | json_query('DCs[?name== Fontend_USA].id') }}"在这里使用:ic_dc_stat_id: "{{ item }}"

我虽然关于 jinja2,但现在确定如何在这里实现它。

请帮助我了解如何解决它。

标签: loopsansible

解决方案


为了专注于这个问题,让我们假设我们有下面的列表

list_of_codes:
  - MX
  - GT

list_of_ids:
  - 1A
  - 1B

如果需要笛卡尔积,请参考下面的剧本

shell> cat playbook.yml
- hosts: localhost
  vars:
    list_of_codes:
      - MX
      - GT
    list_of_ids:
      - 1A
      - 1B
  tasks:
    - debug:
        msg: "{{ item.0 }} - {{ item.1 }}"
      with_nested:
        - "{{ list_of_codes }}"
        - "{{ list_of_ids }}"

shell> ansible-playbook playbook.yml | grep msg:
  msg: MX - 1A
  msg: MX - 1B
  msg: GT - 1A
  msg: GT - 1B

推荐阅读