Calling a variable within a variable within a jinja pipe filter

I am trying to do two things:

  1. Call a variable while trying to set_fact within a jinja pipe filter
  2. Prevent fails when the user isn’t found

`

  • name: “Find the user_id for {{ user }}”
    set_fact:
    uid: “{{ (userinfo.json.users|selectattr(‘username’,‘match’,‘MYVAR’)|list|first).user_id }}”

`

If this is possible, what is the proper syntax for the variable MYVAR? Everything I am trying fails.

In addition, I can’t use “failed_when: false” with the above and get it to work (ie passing in a non-existent user into MYVAR)–it seems to get ignored and ansible exits with a failure. What would be the proper way to prevent this from failing Ansible when the user isn’t found?

Figured it out. I just call the variable with nothing else:

`

`

  • name: “Find the user_id for {{ user }}”
    set_fact:
    uid: “{{ (userinfo.json.users|selectattr(‘username’,‘match’,MYVAR)|list|first).user_id }}”

`

`

Still trying to figure out how to keep the set_fact from failing when passing in a non-existent user. If you have ideas for that, please let me know.

ignore_errors: yes works with set_fact

Figured it out. I just call the variable with nothing else:

    - name: "Find the user_id for {{ user }}"
      set_fact:
        uid: "{{
(userinfo.json.users|selectattr('username','match',MYVAR)|list|first).user_id
}}"

Using ignore_errors is a bad practice IMHO.

If you get no hits you "|list" will be empty and you "|first" filter will fail so you need to run it through default filter.

{{ (userinfo.json.users|selectattr('username','match',MYVAR)|list|first|default()).user_id }}"

But this will also fail since user_id doesn't exist in a empty list do you need to run that through the default filter as well.

So this should work without ignore_errors

{{ (userinfo.json.users|selectattr('username','match',MYVAR)|list|first|default()).user_id