Ansible: Register – store and display output of a command


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
        theName: shiju
        – name: Task to add a new user
                name: “{{ theName }}”
                groups: developers
                append: true

        – name: Tast to check information in user home folder
                cmd: “ls -lA /home/{{ theName }}”
            register: results

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

=== === ==

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

==== === =

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

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

TASK [Task to add a new user] **************************************************
ok: []

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

TASK [Display the listing of home directory] ***********************************
ok: [] => {
“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 ********************************************************************* : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

=== === ==