ansiblejinja2

Ansible (Jinja2) Case Insensitive selectattr


I am looking to perform a case insensitive comparison in Ansible with selectattr.

The below works, but does not guarantee a case insensitive comparison.

__app_pools_info.app_pools | selectattr('attributes.processModel.userName', 'equalto', username_var | lower) | map(attribute='name') | list

The below fails with an error stating processModel is undefined.

__app_pools_info.app_pools | selectattr('attributes.processModel.userName' | lower, 'equalto', username_var | lower) | map(attribute='name') | list

Another attempt fails due to too many arguments being passed to to_lower. I expect I'm not understanding the use of this option.

__app_pools_info.app_pools | selectattr('attributes.processModel.userName', 'lower,' 'equalto', username_var | lower) | map(attribute='name') | list

The below would work, but the username has a forward slash in the name which causes escape issues The error was: re.error: bad escape.

__app_pools_info.app_pools | selectattr('attributes.processModel.userName', 'search', username_var | lower, ignorecase=true) | map(attribute='name') | list

Solution

  • You can use match with regex flags:

    __app_pools_info.app_pools | selectattr('attributes.processModel.userName', 'match', '^' + (username_var | regex_escape) + '$', ignorecase=true) | map(attribute='name') | list
    

    The regex_escape filter handles the forward slash issue you encountered, and ignorecase=true provides case-insensitive matching.