Ansible:当在任何 ansible_play_hosts_all 主机中未定义某些变量时,如何为这种情况定义 "when" 语句?

Ansible: how to define "when" statement for the case, when some variable is not defined in any of ansible_play_hosts_all hosts?

即我有一个剧本,可以对 ansible_play_hosts_all 列表中的某些主机应用一些操作,并且我需要在唯一的情况下执行一个任务,如果 ansible_play_hosts_all 列表中的 none 主机有某些变量定义。我尝试过使用这样的方法:

    - name: look-up if there are no junos changes in such deploy
      set_fact:
        no_junos_changes: >-
          {%- set ns = namespace(junos_changes_counter=0) -%}
          {%- for router in ansible_play_hosts_all -%}
          {%- if hostvars[router]['correct_sections'] is defined -%}
          {%- set ns.junos_changes_counter = ns.junos_changes_counter + 1 -%}
          {%- endif -%}
          {%- endfor -%}
          {{ ns.junos_changes_counter }}
      delegate_to: localhost
      run_once: true

    - name: sent final summary to ms teams in case when junos commit skipped
      import_tasks: ./tasks/post_commit_summary.yml
      when: no_junos_changes|int == 0
      delegate_to: localhost
      run_once: true

所以,第一个任务会给我一个数字,ansible_play_hosts_all 列表中有多少主机定义了 hostvars[router]correct_sections 变量。然后在第二个任务中,我将该数字与 0 进行比较。

它按预期工作,但我不确定它是否是实现此目的的最简单和优雅的方式。 我的意思是,理想情况下我想摆脱第一个任务并在第二个任务的 "when" 语句中使用一些单行,我只是不确定是否可能...

Q: "How much hosts within ansible_play_hosts_all list have they hostvars[router]correct_sections variable defined?"

答:试试这个

- set_fact:
    no_junos_changes: "{{ ansible_play_hosts_all|
                          map('extract', hostvars)|
                          selectattr('correct_sections', 'defined')|
                          list|length }}"
- name: sent final summary to ms teams in case when junos commit skipped
  import_tasks: ./tasks/post_commit_summary.yml
  when: ansible_play_hosts_all
    |map('extract', hostvars)
    |selectattr('correct_sections', 'defined')
    |list|length|int == 0
  delegate_to: localhost
  run_once: true

以防万一有人对单线条件下的单任务解决方案感兴趣