ansible - 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”语句中使用一些单行,我只是不确定是否可能......
解决方案
问:“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 }}"
推荐阅读
- java - 与主分支同步时,Sonarcloud 中不显示分支覆盖率
- node.js - 如何使用 puppeteer 按名称或文本单击按钮?
- c++ - 围栏-codechef 2019 年 4 月长期挑战
- laravel - 我想在 laravel 中使用相同形式的两个文件输入上传两个文件
- selenium - 在 IE11 浏览器上通过 Jenkins(远程)执行 selenium 脚本时遇到缓慢
- angular - 如何在 nativescript-datetimepicker 插件上设置 5 分钟的间隔?
- keras - ValueError:检查目标时出错:预期 lstm_27 有 2 个维度,但得到了形状为 (1, 11, 1) 的数组
- android - 派凌空连接
- python - 如何将 save_screenshot 添加到 If 语句?
- java - Java中自定义文件的自定义图标