Here are three methods to get the UID and GID for the default ansible user.
With Ansible facts
If you don't disable fact gathering, then your ansible run will have a variable ansible_facts
. In this case, you can get the UID and GID directly from it:
- name: Get ansible user UID and GID
hosts: all
tasks:
- name: debug
debug:
msg: "{{ ansible_facts.user_id }}: {{ ansible_facts.user_uid }}:{{ ansible_facts.user_gid }}"
Via getent
and ansible_user
If for whatever reason you don't want to gather facts and you have defined ansible_user
for the hosts in inventory, then you can access it via:
- name: Get ansible user UID and GID
hosts: all
tasks:
- getent:
database: passwd
- name: debug
debug:
msg: "{{ ansible_user }}: {{ getent_passwd[ansible_user].1 }}:{{ getent_passwd[ansible_user].2 }}"
Execute the id command
Another alternative is to use the id
Unix command:
- name: Get Ansible user UID
hosts: all
tasks:
- name: Execute id command
command: id -u {{ ansible_user }}
register: ansible_user_uid
- name: Debug Ansible user UID
debug:
var: ansible_user_uid.stdout
Here, the uid
will be contained in ansible_user_uid.stdout
.
For the group retrieval, you can run id
with the -g
flag to get the primary group, or -G
to get a list of all groups an user belongs to. The easiest option would be:
- name: Get Ansible user primary GID
hosts: all
tasks:
- name: Execute id command
command: id -g {{ ansible_user }}
register: ansible_user_gid
- name: Debug Ansible user primary GID
debug:
var: ansible_user_gid.stdout
Conclusion
IMHO, the easiest way is the first one, as you don't need to employ the getent
module, or run a platform-dependent command.
Member discussion: