待修改脚本 test.yml
---
- hosts: localhost
user: root
gather_facts: false
vars:
- a:
b: 1
tasks:
- file:
path: /etc/ansible/facts.d/
state: directory
- name: empty local.fact
file:
path: /etc/ansible/facts.d/local.fact
state: absent
- get_url: # get a['b'] from apache server
url: "{{ apache_url }}/local.ini"
dest: /etc/ansible/facts.d/local.fact
force: yes
ignore_errors: true # 先忽略吧,可能404
- name: Refresh local facts
setup:
filter: ansible_local
gather_subset: "!all"
- debug:
var: a
local.ini 文件
[a]
b=2
目的: 使用网络上的配置文件,覆盖默认嵌套字典中的变量
/etc/ansible/facts.d/local.fact 文件可能不存在;
/etc/ansible/facts.d/local.fact文件中 a.b 可能不存在。
我能想到的方法:
修改 test.yml
vars:
- a:
b: "{% if ansible_local.local is defined and ansible_local.local.a is defined and ansible_local.local.a.b is defined %}{{ ansible_local.local.a.b }}{% else %}1{% endif %}"
除了逐级判断 ansible_local.local.a.b 是否定义,有没有更优雅的方法?