sorin
sorin

Reputation: 170778

How to implement default value fallback in ansible with dictionaries?

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.

Upvotes: 1

Views: 2133

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68329

AFAIK only via "nested" default:

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

Upvotes: 6

Related Questions