繁体   English   中英

当变量具有默认值时,Ansible playbook条件失败

[英]Ansible playbook condition fails when variable has a default value

给出以下playbook( deployment.yml ):

---
- name: Debug
  hosts: applicationservers
  tasks:
  - debug: msg="{{add_host_entries | default('false')}}"
  - debug: msg="{{add_host_entries | default('false') == 'true'}}"
  - debug: msg="Add host entries = {{add_host_entries | default('false') == 'true'}}"

- include: add_host_entries.yml
  when: add_host_entries | default('false') == 'true'

包含add_host_entries.yml的条件总是失败,即使所有上述调试消息都打印出某种类型的true (我知道在第一个调试消息中它是一个String,而另外两个导致布尔值)。

当我省略具有默认值的部分时,将执行add_host_entries.yml

  when: add_host_entries

我需要这个默认值行为,因为它是一个可选值,仅在某些阶段设置。

其他尝试(没有成功)

括号

  when: (add_host_entries | default('false')) == 'true'

转换为布尔值

  when: add_host_entries|default('false')|bool

其他来源和信息

以下是重现问题所需的所有资源。

add_host_entries.yml

---
- name: add_host_entries
  hosts: applicationservers
  gather_facts: false
  tasks:
    - debug: msg="Add Host Entries"

inventory

[applicationservers]
127.0.0.1

[all:vars]
add_host_entries=true

呼叫

markus@lubuntu:~/foobar$ ansible-playbook deployment.yml -i inventory

版本

markus@lubuntu:~/foobar$ ansible --version
ansible 2.1.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides

markus@lubuntu:~/foobar$ ansible-playbook --version
ansible-playbook 2.1.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides

你试图有条件地包括剧本 请参阅我关于不同包含类型的其他答案。

问题是,这仅 Ansible分析您的剧本之前定义变量时才有效。
但是您尝试将add_host_entries定义为主机级事实(组变量) - 这些变量在解析add_host_entries未定义。

如果您使用-e add_host_entries=true调用您的playbook,您的条件将按预期工作,因为在解析时已知额外值。

使用booladd_host_entries的字符串值转换为布尔值,然后条件将起作用。

---
- name: Debug
  hosts: applicationservers
  tasks:
  - debug: msg="{{add_host_entries | default('false')}}"
  - debug: msg="{{add_host_entries | default('false') == 'true'}}"
  - debug: msg="Add host entries = {{add_host_entries | default('false') == 'true'}}"

- include: add_host_entries.yml
  when: add_host_entries | default('false') | bool

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM