Ansible: Set variable only if undefined -


i set ansible variable default value if variable undefined. otherwise keep unchanged.

i tried these 2 approaches , both of them produce recursive loop:

namespace: "{{namespace|default(default_namespace)}}" namespace: "{% if namespace defined %}{{namespace}}{% else %}{{default_namespace}}{% endif %}" 

it seems taking wrong approach.

take @ ansible documentation concerning variable precedence. built-in feature of ansible use default variable if variable not defined.

in ansible 2.x variable precedence starts this:

role defaults

inventory vars

so if want define default value variable should set in role/defaults/main.yml. ansible use value if variable not defined somewhere else.

another option use jinja2 filter. jinja filter can set default value variable this:

{{ some_variable | default(5) }} 

Comments