Ansible 的 when 条件结合 run_once 会不小心跳过一些不应该跳过的任务 [英] Ansible's when condition combined with run_once will accidentally skip some tasks that should not be skipped
问题描述
我的inventory_hosts如下:
My inventory_hosts is as follows:
# inventory
[kafka]
192.168.1.1
192.168.1.2
[mysql]
192.168.1.3
我的 ansible-playbook 如下:
My ansible-playbook as follows:
site.yml:
- name: test
hosts: all
roles:
- kafka
kafka 角色任务:
kafka roles tasks:
# main.yml
- name: get kafka groups length
shell: echo "{{ groups['kafka']|length }}"
run_once: true
delegate_to: localhost
when: "'kafka' in group_names"
预期结果
获取kafka组长度
可以分别执行并委托给本地执行一次
get kafka groups length
can be executed and delegated to local execution respectively and only once
实际结果
TASK [Gathering Facts] ******************************************************************************************************************************************************
ok: [192.168.1.1]
ok: [192.168.1.2]
ok: [192.168.1.3]
TASK [kafka : get mongodb groups length] ************************************************************************************************************************************
skipping: [192.168.1.3]
很奇怪的设计,我觉得不应该跳过,但他确实跳过了,我该怎么办?我期待同样的结果
Very strange design, I think it should not be skipped, but he did skip it, what should I do? I expect the same result
推荐答案
来自 Ansible 文档:
From the Ansible documentation:
group_names
是当前主机所在的所有组的列表(数组)
group_names
is a list (array) of all the groups the current host is in
你的任务只运行一次,所以它只在第一台主机上运行,并且该主机只属于 kafka
组.这意味着您在该运行中的 group_names
变量仅包含 kafka
.
You are only running your task once, so it only runs on the first host, and that host only belongs to the kafka
group. This means that your group_names
variable on that run only includes kafka
.
试试这个:
- name: get kafka groups length
shell: echo "{{ groups['kafka']|length }}"
run_once: true
delegate_to: localhost
when: groups['kafka'] is defined
这篇关于Ansible 的 when 条件结合 run_once 会不小心跳过一些不应该跳过的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!