Calling a variable within a variable within a jinja pipe filter

25 views
Skip to first unread message

John Harmon

unread,
Jan 29, 2019, 5:34:13 PM1/29/19
to Ansible Project
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?

John Harmon

unread,
Jan 29, 2019, 5:44:50 PM1/29/19
to Ansible Project
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 }}"


John Harmon

unread,
Jan 29, 2019, 5:51:07 PM1/29/19
to Ansible Project
 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.

John Harmon

unread,
Jan 29, 2019, 5:52:25 PM1/29/19
to Ansible Project


On Tuesday, January 29, 2019 at 3:51:07 PM UTC-7, John Harmon wrote:
 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 

Kai Stian Olstad

unread,
Feb 2, 2019, 7:23:08 AM2/2/19
to ansible...@googlegroups.com
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
| default('') }}"

--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages