与when和run_once结合使用时,会意外跳过任务

时间:2019-08-12 16:41:10

标签: ansible

我的清单主机如下:

# inventory
[kafka]
192.168.1.1 
192.168.1.2 

[mysql]
192.168.1.3

我的ansible剧本如下:

site.yml:

- name: test
  hosts: all
  roles:
   - kafka

kafka角色任务:

# main.yml
- include: test.yml
  when:  "'kafka' in group_names"




# test.yml
---
- name: get kafka groups length
  shell: echo "{{ groups['kafka']|length }}"
  run_once: true
  delegate_to: localhost

- name: Get the main control machine ip
  shell: ip addr show `ip route |awk '$2=="via" {print $5}' |head -1` | awk '$1=="inet" {print $2}'| head -1 | cut -d '/' -f 1
  run_once: true
  delegate_to: localhost

预期结果

get kafka groups lengthGet the main control machine ip可以分别执行并委托给本地执行

实际结果

TASK [Gathering Facts] **********************************************************************************************************
ok: [192.168.1.1]
ok: [192.168.1.2]
ok: [192.168.1.3]
META: ran handlers

TASK [kafka : get kafka groups length] ***************************************************************************************
skipping: [192.168.1.3] => changed=false 
  skip_reason: Conditional result was False

TASK [kafka : Get the main control machine ip] ************************************************************************************
skipping: [192.168.1.3] => changed=false 
  skip_reason: Conditional result was False

还没有结束。取笑人的窍门是,当我对这组ip mysql进行评论时,我发现可以执行任务。

 # inventory
 [kafka]
 192.168.1.1 
 192.168.1.2 

 #[mysql]
 #192.168.1.3

新运行结果(是我想要的结果):

TASK [Gathering Facts] ******************************************************************************************************************************************************
ok: [192.168.1.1]
ok: [192.168.1.2]

TASK [kafka : get kafka groups length] ************************************************************************************************************************
changed: [192.168.1.1 -> localhost]

TASK [kafka : Get the main control machine ip] ******************************************************************************************************************************
changed: [192.168.1.1 -> localhost]

为什么会这样,我们如何避免这个不确定的问题?

1 个答案:

答案 0 :(得分:0)

  

问:“为什么这样,我们如何才能避免这个不确定的问题?”

- hosts: all
  tasks:
    - include: test.yml
      when: "'kafka' in group_names"

TASK ...
    skip_reason: Conditional result was False

A:使用include_tasks。继承应该可以正常工作。

    - include_tasks: test.yml
      when: "'kafka' in group_names"

(已通过ansible 2.7.9测试)


详细信息

引用Special Variables

  

group_names :当前主机所属的组的列表

有库存

 [kafka]
 192.168.1.1
 192.168.1.2

所有主持人的变量均为group_names: [ "kafka" ],剧本按预期进行。

有库存

 [kafka]
 192.168.1.1
 192.168.1.2

 [mysql]
 192.168.1.3

一个主机的变量为group_names: [ "mysql" ]。从您发现的情况来看,如果任何主机的条件失败,在include中似乎会跳过 run_once

skipping: [192.168.1.3] => changed=false 
  skip_reason: Conditional result was False