json_query on getent_group-data: resolving the group-name for a given group-id

Hello!

Is there an elegant way to deduce from given gid to group-name in the
dictionary that's provided by the getent-module of ansible?

I’m not a huge fan of json_query for most cases. I think using the native jinja2 filters are often more readable, although in this case, not 100% more readable.

getent_group|dictsort|selectattr('1.1', 'equalto', '100')|first|first

That turns getent_group into a list of tuples, selects where item[1][1] (the ID) is equal to 100, returns the first match, and the first element, which in my case is the groupname of “users”

Hello Matt,

thank you for having a look into this!

I’d love to use your suggestion - but apparently our setup is too old:

TASK [debug : debug] *********************************************************** fatal: [localhost]: FAILED! => {"failed": true, "msg": "template error while templating string: no filter named 'selectattr'. String: {{ getent_group | dictsort | selectattr('1.1', 'equalto', group_ID ) | first | first }}"}

It’s RHEL6:

$ rpm -qa | grep jinj python-jinja2-26-2.6-3.el6.noarch

May i ask for another try?

Thanks & best regards
Henning

One option is to use a loop

- debug:
    msg: '{% for k, v in getent_group.iteritems() %}{% if v.1 == "1000" %}{{ k }}{% endif %}{% endfor %}'

Hello Kai Stian,

thank you to have a look into this!

  • debug:
    msg: ‘{% for k, v in getent_group.iteritems() %}{% if v.1 == “1000” %}{{ k }}{% endif %}{% endfor %}’

Whow! This works!

  • debug:
    msg: “Primary group: {{ group_name | default( ‘not found’, true ) }}”
    vars:
    group_name: >-
    {% for k, v in getent_group.iteritems() %}{% if v.1 == group_id.str() %}{{ k }}{% endif %}{% endfor %}

While I had loved to learn some dark sides of json_query, this solves my current issue - thank you very much, both!

Have a nice weekend
best regards
Henning

PS: str() may seem redundant, but in one of my testcases, the comparison failed due to group_id being defined numerically.