tl;dr - sample solutions to the problem with getent
module (tricky) or user
module (easier but more limited info)
You can get the most info by using the getent
module, but it's tricky to pick out the items you want (use debug
to show you the whole structure so you can work out how to specify the fields that you want).
To fetch some common fields with getent
for example,
- ansible.builtin.set_fact:
username: ntp
- ansible.builtin.getent:
database: passwd
key: "{{ username }}"
- ansible.builtin.set_fact:
uid: "{{ getent_passwd[username][1] }}"
gid: "{{ getent_passwd[username][2] }}"
home: "{{ getent_passwd[username][4] }}"
shell: "{{ getent_passwd[username][5] }}"
- ansible.builtin.debug:
msg: "UID: {{ uid }}, GID: {{ gid }}, home: {{ home }}, shell: {{ shell }}"
To reiterate Zoredache's comment, the getent
module will create host facts of the form getent_
databasename where databasename will correspond with the database:
specified to getent
, thus getent_passwd
above.
If it's only those particular fields you want, you could instead use the easier to understand user
module with check_mode
(without check_mode: true
the user concerned will be created or modified so take care!). The corresponding lines would be,
- ansible.builtin.user:
name: ntp
check_mode: true
register: res
- ansible.builtin.set_fact:
uid: "{{ res.uid }}"
gid: "{{ res.group }}"
home: "{{ res.home }}"
shell: "{{ res.shell }}"
- ansible.builtin.debug:
msg: "UID: {{ uid }}, GID: {{ gid }}, home: {{ home }}, shell: {{ shell }}"