Shu*_*roj 6 ansible devops ansible-facts
---
- hosts: "{{ run_on_node|default('mysql_cluster_sql[0]')}}"
connection: "{% if migrated is defined and migrated == 'yes' %}local{% else %}ssh{% endif %}" # This works as we are assigning non boolean value
gather_facts: "{% if migrated is defined and migrated == 'yes' %}false{% else %}true{% endif %}" #This doesnt work well
tasks:
- debug: var=ansible_all_ipv4_addresses
- debug: var=ansible_default_ipv4.address
Run Code Online (Sandbox Code Playgroud)
库存文件:
[mysql_cluster_sql]
10.200.1.191 migrated=yes
Run Code Online (Sandbox Code Playgroud)
该变量根据条件具有 true 和 false 值,但即使 Gather_facts 为 false,它也会收集事实。
简化并修复条件。使用默认值。这将涵盖这两个测试,例如
shell> cat pb.yml
- hosts: localhost
gather_facts: "{{ (migrated|default('no') == 'yes')|ternary(false, true) }}"
tasks:
- meta: noop
Run Code Online (Sandbox Code Playgroud)
将收集没有定义已迁移变量的事实
shell> ansible-playbook pb.yml
PLAY [localhost] ********************************************************
TASK [Gathering Facts] **************************************************
ok: [localhost]
Run Code Online (Sandbox Code Playgroud)
,或者当变量设置为“yes”以外的其他值时
shell> ansible-playbook pb.yml -e migrated=no
PLAY [localhost] ********************************************************
TASK [Gathering Facts] **************************************************
ok: [localhost]
Run Code Online (Sandbox Code Playgroud)
当变量设置为“yes”时,不会收集任何事实
shell> ansible-playbook pb.yml -e migrated=yes
PLAY [localhost] ********************************************************
PLAY RECAP **************************************************************
Run Code Online (Sandbox Code Playgroud)
金贾
如果您坚持使用Jinja,下面的剧本会给出相同的结果
shell> cat pb.yml
- hosts: localhost
gather_facts: "{% if migrated|default('no') == 'yes' %}
false
{% else %}
true
{% endif %}"
tasks:
- meta: noop
Run Code Online (Sandbox Code Playgroud)
布尔值
您可以通过显式转换为Boolean来进一步简化测试,例如
- hosts: localhost
gather_facts: "{{ (migrated|default('no')|bool)|ternary(false, true) }}"
tasks:
- meta: noop
Run Code Online (Sandbox Code Playgroud)
真实/虚假
确保您了解布尔转换和测试的工作原理。查看任务结果
- debug:
msg: "True"
loop: [yes, Yes, true, True, xxx]
when: item|bool
- debug:
msg: "False"
loop: [no, No, false, False, xxx]
when: not item|bool
- debug:
msg: "{{ item|bool|ternary(True, False) }}"
loop: [yes, Yes, true, True, xxx,
no, No, false, False, xxx]
- debug:
msg: "{{ item|ternary(True, False) }}"
loop: [yes, Yes, true, True, xxx,
no, No, false, False, xxx]
Run Code Online (Sandbox Code Playgroud)
问:“从库存中传递‘迁移’变量不起作用。 ”
答:你说得对。似乎库存变量在Gather_facts运行时不可用。使用设置作为解决方法。例如
- hosts: localhost
gather_facts: false
tasks:
- setup:
when: (migrated|default('no')|bool)|ternary(false, true)
Run Code Online (Sandbox Code Playgroud)