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

时间:2020-02-10 14:53:49

标签: ansible jinja2 ansible-2.x ansible-template

即我有一本剧本,可以对ansible_play_hosts_all列表中的某些主机执行某些操作,并且只有在ansible_play_hosts_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_play_hosts_all变量中的hostvars[router]correct_sections列表中的主机数。然后在第二项任务中,我将比较该数字与0。

它正在按预期工作,但是我不确定这是否是最简单,最优雅的方法。 我的意思是,理想情况下,我想摆脱第一项任务,而在第二项任务的“ when”语句中使用一些内容,我只是不确定是否有可能...

2 个答案:

答案 0 :(得分:1)

Q:“在ansible_play_hosts_all列表中有多少台主机定义了hostvars [router] correct_sections变量?”

A:试试看

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

答案 1 :(得分:0)

- 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

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