Ansible: User management – Add user – ssh key

Ansible_Logo

In this section we will try to understand few of the operations we can do using User module.

In the below example, we will create anew user named shiju in the managed node, and will try to see the users secondary group and lilst content of .ssh folder:

[root@centos9vm ~]# cat adduser_playbook.yml

==== ===

– – –
– name: Playbook to add a new user
    hosts: 192.168.48.129
    vars:
        theName: shiju
    tasks:
        – name: Task to add a new user
            ansible.builtin.user:
                name: “{{ theName }}”
                groups: developers
                append: true

        – name: Tast to check information in user home folder
            ansible.builtin.command:
                cmd: “ls -A /home/{{ theName }}”
                register: results

        – name: Display the listing of home directory
            ansible.builtin.debug:
                var: results.stdout

        – name: Create sn SSH key for user {{ theName }}
            ansible.builtin.user:
                name: “{{ theName }}”
                generate_ssh_key: yes
                ssh_key_bits: 2048
                ssh_key_file: .ssh/id_rsa

        – name: Tast again to check information in user home folder
            ansible.builtin.command:
                cmd: “ls -A /home/{{ theName }}”
                register: newResults

        – name: Display the listing of home directory to see if ssh folder was created
            ansible.builtin.debug:
                var: newResults.stdout

===== ====
[root@centos9vm ~]# ansible-navigator run -m stdout adduser_playbook.yml

===== ===

PLAY [Playbook to add a new user] **********************************************

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

TASK [Task to add a new user] **************************************************
changed: [192.168.48.129]

TASK [Tast to check information in user home folder] ***************************
changed: [192.168.48.129]

TASK [Display the listing of home directory] ***********************************
ok: [192.168.48.129] => {
“results.stdout”: “.bash_logout\n.bash_profile\n.bashrc”
}

TASK [Create sn SSH key for user shiju] ****************************************
changed: [192.168.48.129]

TASK [Tast again to check information in user home folder] *********************
changed: [192.168.48.129]

TASK [Display the listing of home directory to see if ssh folder was created] ***
ok: [192.168.48.129] => {
“newResults.stdout”: “.bash_logout\n.bash_profile\n.bashrc\n.ssh
}

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

===== ===