首页 > 解决方案 > Ansible:当任何 ansible_play_hosts_all 主机中未定义某些变量时,如何为案例定义“何时”语句?

问题描述

即我有一本剧本,可以对列表中的某些主机应用一些操作,如果列表中的主机都没有定义某些变量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”语句中使用一些单行,我只是不确定是否可能......

标签: ansiblejinja2ansible-2.xansible-template

解决方案


问:“ansible_play_hosts_all 列表中有多少主机定义了它们的 hostvars[router]correct_sections 变量?”

答:试试这个

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

推荐阅读