Ansible: Register – store and display output of a command

Ansible_Logo

At times we may want to run certain command in the managed nodes, and would like to see the output to verify if the command ran correctly. The module commonly used to run commands on managed nodes is “ansible.builtin.command”. However when we execute a command using this module the output wont be displayed as we run the playbook. The workaround is to capture the output using “register” parameter.

Below is an example where a user is created using “user” module, and a task is added to list the contents in the user’s home 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 -lA /home/{{ theName }}”
            register: results

        – name: Display the listing of home directory
            ansible.builtin.debug:
                var: results.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] **************************************************
ok: [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”: “total 12\n-rw-r–r–. 1 shiju shiju 18 Nov 24 2022 .bash_logout\n-rw-r–r–. 1 shiju shiju 141 Nov 24 2022 .bash_profile\n-rw-r–r–. 1 shiju shiju 492 Nov 24 2022 .bashrc\n-rw-r–r–. 1 root root 0 Apr 27 21:08 samkutty.txt”
}

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

=== === ==