即我有一本剧本,可以对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”语句中使用一些内容,我只是不确定是否有可能...
答案 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
以防万一有人对单线条件下的单任务解决方案感兴趣