How can I set a default that includes information from a variable?

I’ve tried the following code:

`

  • name: ensure users exist.
    when: item.value.state is defined
    user:
    state: “{{ item.value.state }}”
    name: “{{ item.value.username }}”
    comment: “{{ item.value.fullname }}”
    password: “{{ item.value.crypted_pass }}”
    createhome: “yes”
    home: “{{ item.value.home|default(/home/{{ item.value.username }}) }}”
    shell: “{{ item.value.shell }}”
    uid: “{{ item.value.uid }}”
    with_dict: “{{ aspects_local_users }}”
    tags:
  • aspects_local_users
    `

Basically, if aspects_local_users.user.home is set, I want to use that value. Otherwise I want to use /home/.

As I expected, you can’t nest {{ }} to get the value out of item.value.username. I, obviously, can get the value if I just do this:

home: "{{ blah|default(item.value.username) }}"

But that leaves off the /home.

Note, I can just create a second task and run one when item.value.home is defined and the other when it isn’t. But I would like to just use one task. :slight_smile:

Thanks for any ideas or suggestions!

I’m on Ansible 2.3.2.0 installed from Pip. Ubuntu 16.04 64bit. Testing against vagrant vms.

David -

I haven’t tried doing exactly what you’re trying to do, but I did something similar. I’ve changed the variable names to protect the innocent):

  • name: remember variables
    set_fact:
    myvar: “{{var1}}{{item.path|basename| regex_replace(‘^’ + version_regex + ‘$’, ‘\1’) }}” #regex parses version from jar file name

with_items: “{{output.files}}”

Maybe that’ll give you something to go off?

-Adam

I probably should have explained that “version_regex” is a variable defined in roles/role/vars/main.yml.

-Adam

Correct syntax should be:

home: "{{ item.value.home | default('/home/' + item.value.username) }}"

Thank you! That worked perfect. :slight_smile: