Ansible - Use default if a variable is not defined

Bernardo Vale picture Bernardo Vale · Jan 30, 2016 · Viewed 144.2k times · Source

I'm customizing linux users creation inside my role. I need to let users of my role customize home_directory, group_name, name, password.

I was wondering if there's a more flexible way to cope with default values.

I know that the code below is possible:

- name: Create default
  user:
    name: "default_name"
  when: my_variable is not defined

 - name: Create custom
  user:
    name: "{{my_variable}}"
  when: my_variable is defined

But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities.

Is there something like the code above?

user:
  name: "default_name", "{{my_variable}}"

The code should set name="default_name" when my_variable isn't defined.

I could set all variables on defaults/main.yml and create the user like that:

- name: Create user
  user:
    name: "{{my_variable}}"

But those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.

Answer

tedder42 picture tedder42 · Jan 30, 2016

You can use Jinja's default:

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"