Prvaak
Prvaak

Reputation: 885

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 %}"

Upvotes: 52

Views: 124306

Answers (5)

miller the gorilla
miller the gorilla

Reputation: 930

How about :

shellvar = "{{ some_var | default(omit) }}"
``
from [this article][1]


  [1]: https://stackoverflow.com/a/55826235/1021535

Upvotes: 0

Henrik Pingel
Henrik Pingel

Reputation: 3203

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) }}

Upvotes: 67

panticz
panticz

Reputation: 2315

Additional, in case you using lookup to define default variable (read from environment) you have also set the second parameter of default to true:

- set_facts:
    ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"

You can also concatenate multiple default definitions together:

- set_facts:
    ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"

Upvotes: 6

Noam Manos
Noam Manos

Reputation: 17000

In case you need to set your variable by priority order, likewise:

  1. Set variable as var_priority_1.
    But if it is not defined, then:
  2. Set variable as var_priority_2.
    But if it is not defined either, then:
  3. Set variable to a default value.

I had to use such condition while trying to get value from inventory hosts variables, that sometimes need to be overridden by role vars:

shell: |
    ...
    shell_var={{ role_var if role_var is defined else hostvars[item].host_var | default('defalut_value') }}
    ...
  with_items: "{{ groups[hosts_group_iterator] }}"

Upvotes: 5

helloV
helloV

Reputation: 52433

- set_fact: namespace="default_namespace"
  when: namespace is undefined

Upvotes: 38

Related Questions