How to implement default value fallback in ansible with dictionaries?

时间:2017-04-06 17:18:05

标签: ansible

I want to improve the code below so it will always fallback to omit when it cannot find the value.

#!/usr/bin/env ansible-playbook
---
- hosts: localhost
  gather_facts: no
  vars:
      ansible_connection: local
      foo:
         bar:
           12: 'xxx'
  tasks:

    - debug:
        msg: "component_config={{ foo.bar[12] | default(omit) }}"

Current code works as expected only if foo.bar is a dictionary but fails if bar or even foo are not there.

1 个答案:

答案 0 :(得分:4)

AFAIK只能通过"嵌套" default

{{ ((foo|default({})).bar|default({}))[12] | default(omit) }}