default value for dictionary in jinja2 (ansible)

你离开我真会死。 提交于 2020-01-01 04:19:08

问题


jinja2 has filter '|default()' to works with undefined variables. But it does not work with dictionary values.

if D may have or not have key foo (D[foo]), than:

{{ D[foo]|default ('no foo') }}

will prints 'no foo' if D is undefined, but will cause error ('dict object' has no attribute 'foo') if D is defined, but D[foo] is undefined.

Is any way to make default for dictionary item?


回答1:


This appears to be working properly for me using Ansible 1.7.2. Here's a test playbook I just wrote:

---
- hosts: localhost
  vars:
    D:
     1 : "one"
     2 : "two"
  tasks:
      - debug: var=D

      - debug: msg="D[1] is {{ D[1]|default ('undefined') }}"

      - debug: msg="D[3] is {{ D[3]|default ('undefined') }}"

And here is the output from running it:

TASK: [debug var=D] ***********************************************************
ok: [localhost] => {
    "D": {
        "1": "one",
        "2": "two"
    }
}

TASK: [debug msg="D[1] is one"] ***********************************************
ok: [localhost] => {
    "msg": "D[1] is one"
}

TASK: [debug msg="D[3] is undefined"] *****************************************
ok: [localhost] => {
    "msg": "D[3] is undefined"
}


来源:https://stackoverflow.com/questions/28885184/default-value-for-dictionary-in-jinja2-ansible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!