【问题标题】:How to combine two loops into one in Ansible如何在 Ansible 中将两个循环合二为一
【发布时间】:2020-09-12 22:09:42
【问题描述】:

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

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

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

我添加了 loop: "{{ 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,但现在知道如何在这里实现它。

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

【问题讨论】:

  • mcve。编辑问题,降低复杂性,并最小化代码。添加预期结果。

标签: loops ansible


【解决方案1】:

为了解决这个问题,假设我们有以下列表

list_of_codes:
  - MX
  - GT

list_of_ids:
  - 1A
  - 1B

如果需要cartesian product,请参阅下面的剧本

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

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多