首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ansible: 判断嵌套字典是否定义?

Ansible: 判断嵌套字典是否定义?

提问于 2020-03-16 23:58:08
回答 0关注 0查看 263

待修改脚本 test.yml

代码语言:yaml
复制
---
- 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 文件

代码语言:ini
复制
[a]
b=2

目的: 使用网络上的配置文件,覆盖默认嵌套字典中的变量

/etc/ansible/facts.d/local.fact 文件可能不存在

/etc/ansible/facts.d/local.fact文件中 a.b 可能不存在

我能想到的方法:

修改 test.yml

代码语言:yaml
复制
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 是否定义,有没有更优雅的方法?

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档