Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Set variable only if undefined

I would like to set an ansible variable to some default value but only if the variable is undefined. Otherwise I would like to keep it unchanged.

I tried these two approaches and both of them produce recursive loop:

namespace: "{{namespace|default(default_namespace)}}" namespace: "{% if namespace is defined %}{{namespace}}{% else %}{{default_namespace}}{% endif %}" 
like image 864
Prvaak Avatar asked Jan 29 '16 11:01

Prvaak


People also ask

How is it possible to check if a variable is defined in Ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. Show activity on this post.

When variable is defined?

1.1 Defined / not defined variable A variable is defined when it has been declared in the current scope using a declaration statement. The usual way to declarate variables is const , let and var statements, plus the function and class declaration statements.


Video Answer


2 Answers

It seems like you are taking a wrong approach.

Take a look at the Ansible documentation concerning variable precedence. It is a built-in feature of Ansible to use the default variable if the variable is not defined.

In Ansible 2.x the variable precedence starts like this:

role defaults

inventory vars

So if you want to define a default value for a variable you should set it in role/defaults/main.yml. Ansible will use that value only if the variable is not defined somewhere else.

Another option is to use a Jinja2 filter. With a Jinja filter you can set a default value for a variable like this:

{{ some_variable | default(5) }} 
like image 138
Henrik Pingel Avatar answered Sep 19 '22 17:09

Henrik Pingel


- set_fact: namespace="default_namespace"   when: namespace is undefined 
like image 34
helloV Avatar answered Sep 18 '22 17:09

helloV