Ansible logo

The other day I needed a way to get the main group of a user account in a playbook in Ansible. I figured there was a way to do this using native methods in Ansible, which proved correct. You can utilize the ansible.builtin.getent which can perform lookups to both the passwd and group databases.

As a result, I ended up with the following playbook.

---
- name: Print main group for user
  hosts: all
  connection: local
  gather_facts: true

  vars:
    group_username: tolecnal

  tasks:

    - name: Get user info
      ansible.builtin.getent:
        database: passwd
        key: "{{ group_username }}"
      register: user_info

    - name: Get group name
      ansible.builtin.getent:
        database: group
        key: "{{ ansible_facts.getent_passwd[group_username][2] }}"
      register: group_info

    - debug: msg="Main group for user {{ group_username }} is {{ ansible_facts.getent_group | first }}"

Example output of the playbook.

❯ ansible-playbook playbooks/group.yml -l localhost

PLAY [Print main group for user] *************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Get user info] *************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Get group name] ************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] *********************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "Main group for user tolecnal is tolecnal"
}

PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

By Jostein Elvaker Haande

"A free society is a society where it is safe to be unpopular" - Adlai Stevenson

Leave a Reply

Your email address will not be published. Required fields are marked *