Ansible:如何定义;什么时候;语句,当某个变量未在任何ansible\u play\u hosts\u all hosts中定义时?

Ansible:如何定义;什么时候;语句,当某个变量未在任何ansible\u play\u hosts\u all hosts中定义时?,ansible,jinja2,ansible-2.x,ansible-template,Ansible,Jinja2,Ansible 2.x,Ansible Template,i、 e.我有一个剧本,可以对ansible\u play\u hosts\u all列表中的一些主机应用一些操作,如果ansible\u play\u hosts\u all列表中没有任何主机定义了某个变量,我只需要执行一个任务。我曾尝试使用这种方法: - name: look-up if there are no junos changes in such deploy set_fact: no_junos_changes: >-

i、 e.我有一个剧本,可以对
ansible\u play\u hosts\u all
列表中的一些主机应用一些操作,如果
ansible\u play\u hosts\u all
列表中没有任何主机定义了某个变量,我只需要执行一个任务。我曾尝试使用这种方法:

    - 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\u play\u hosts\u all
列表中有多少主机定义了
hostvars[router]正确的\u部分
变量。然后在第二个任务中,我将把这个数字与0进行比较

这是预期的工作,但我不确定这是否是最简单和优雅的方式为这样的目的。 我的意思是,理想情况下,我想摆脱第一个任务,在第二个任务的“when”语句中使用一行,我只是不确定这是否可能

问:“ansible\u play\u hosts\u all列表中有多少主机定义了hostvars[路由器]正确的\u节变量?”

A:试试这个

- set_fact:
    no_junos_changes: "{{ ansible_play_hosts_all|
                          map('extract', hostvars)|
                          selectattr('correct_sections', 'defined')|
                          list|length }}"

以防万一,如果有人对单任务解决方案感兴趣,只需一行条件

非常感谢!我怀疑,是不是可以用selectattr完成,我只是不知道map('extract')可以用于将嵌套dict的所需部分切片到列表中。
- 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