'Ansible Loop Register

I have an ansible playbook to create new users and create a docker for each user. The information of the users is gathered from a yaml file there are more that 200 records. The yaml file consists of username and password. To create docker container I have to give PUID and PGID of the user to the docker run command. See below for example command

docker run --restart=always -it --init -td -p {port from ansible}:8443 -e PUID={PUID from ansible} -e PGID={PGID from Ansible} linuxserver/code-server:latest

I want to get PUID and PGID of a user and register it to a variable to use them to create docker container. I tried to use the following command but since it appends the output to a variable dictionary, I am not able to match the username with PUID/PGID.

  - name: GET PUID
    shell: id -u "{{ item.username }}"
    loop: "{{ user }}"
    register: puid
  - name: pgid Variable
    debug: msg="{{ pgid.stdout }}"

YAML for user

user:
  - username: john.doe
    password: password

The docker image that I want to use: https://hub.docker.com/r/linuxserver/code-server



Solution 1:[1]

For example, get the UID and GID of user admin at test_11

shell> ssh admin@test_11 id admin
uid=1001(admin) gid=1001(admin) groups=1001(admin)

Use the module getent. The playbook below

- hosts: test_11
  tasks:
    - getent:
        database: passwd
    - set_fact:
        admin_uid: "{{ ansible_facts.getent_passwd.admin.1 }}"
        admin_gid: "{{ ansible_facts.getent_passwd.admin.2 }}"
    - debug:
        msg: |
          admin_uid: {{ admin_uid }}
          admin_gid: {{ admin_gid }}

gives (abridged)

TASK [debug] ********************************************************
ok: [test_11] => 
  msg: |-
    admin_uid: 1001
    admin_gid: 1001

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladimir Botka