But, suppose you want to print the command output of the command being executed on the remote target. How do you go about this? In this tutorial, you will learn how to print the command output in Ansible.
Prerequisites
Before getting started, ensure that you have Ansible installed on your Linux system. In this guide, we are running Ubuntu 20.04 in which Ansible installed. Check out our guide on how to install Ansible on Ubuntu 20.04.
Print command output in Ansible
Let take a simple playbook file that lists the home directory of the managed host or remote host.
- hosts: staging
name: List the contents of home directory
tasks:
- name: List files and folder in home directory
shell: 'ls -l'
The playbook will run just fine; however, the output will not be displayed on the terminal. All that is logged is the nature of the activity happening on the managed host.
When a playbook file is executed, every task saves its output in a variable. To capture the output, you need to specify your own variable into which the output will be saved. To achieve this, we use the ‘register’ parameter to record the output to a variable. Then use the ‘debug’ module to display the variable’s content to standard out.
To demonstrate this, let’s use a few examples.
Example 1: Print the command output of listing files in the home directory
Earlier, we provided an example of a playbook file that lists the contents of a managed host’s home directory. However, as we found out, the output is not printed to standard out.
We will use the ‘register’ parameter to record the results into a variable called command_output to resolve this issue. Then, we will print the output using the ‘debug’ module.
Here’s the complete playbook file.
- hosts: staging
name: List the contents of home directory
tasks:
- name: List files and folder in home directory
shell: 'ls -l'
register: command_output
- debug:
var: command_output.stdout_lines
When the playbook file is executed, the output of the home directory’s contents is printed to standard out.
Example 2: Print the command output of the uptime command
Let’s take another scenario where we are printing the output of ‘uptime’ command on the shell of the managed host. As you might know, the uptime command prints details such as how long the system has been running since it was powered on, logged in users, and load average.
We created a playbook file called check_uptime.yml, as shown.
- hosts: staging
name: Check uptime of the remote host
tasks:
- name: Check uptime of remote Ubuntu server
shell: uptime
register: command_output
- debug:
var: command_output.stdout_lines
When executed, the uptime details are printed to the terminal as shown.
Conclusion
This guide demonstrates how you can print the command’s output to standard out in Ansible. This was enlightening, and that you can now print the output of your command to std out.