Use variables to retrieve the results of running commands
Learn to capture and reuse command output in Ansible playbooks using the register directive for improved automation and task management.
In this article, you’ll learn how to capture the output of tasks executed with Ansible using the register directive and reuse that data later in your playbook. Capturing command output can be invaluable—for instance, if you want to read the contents of a file and then use that information in subsequent tasks.
Capturing Command Output with a Registered Variable
Consider the following playbook that executes a shell command to display the contents of the /etc/hosts file on each host. Initially, the playbook might be written like this without capturing the output:
To capture the output, you can register the result of the shell command into a variable (for example, result). The revised playbook is shown below:
Copy
Ask AI
- name: Check /etc/hosts file hosts: all tasks: - shell: cat /etc/hosts register: result - debug: var: result
When executed, Ansible stores the result of the shell command into the result variable. Running the updated playbook produces debug output that looks like this:
The content stored in the result variable depends on the module that was executed. When using the shell module, the output is captured as a JSON object. For example, the result variable might contain data like the following:
rc: The return code of the command (0 indicates success).
stdout and stdout_lines: The standard output from the command, which in this example is the contents of /etc/hosts.
stderr and stderr_lines: Any error messages generated during command execution.
Timestamps and delta: Timing details that show when the command started, ended, and the duration of execution.
Registered variables in Ansible are host-scoped. This means the variable is only available for the specific host where the task was executed and can be accessed throughout the remainder of the playbook for that host.
Accessing Specific Elements from the Registered Variable
In many cases, you might only want to display specific parts of the command output. For instance, if you’re only interested in the standard output (the file contents of /etc/hosts), you can reference result.stdout in your debug task:
Copy
Ask AI
- name: Check /etc/hosts file hosts: all tasks: - shell: cat /etc/hosts register: result - debug: var: result.stdout
Similarly, if you want to check the command’s return code, you can reference result.rc:
Copy
Ask AI
- name: Check /etc/hosts file hosts: all tasks: - shell: cat /etc/hosts register: result - debug: var: result.rc
Another convenient way to view task output is to run your playbook with the -v option. This provides verbose output without the need to add explicit debug statements. For more details, refer to the Ansible Documentation.That’s it for now. Practice these techniques to further enhance your Ansible playbooks and streamline your automation processes.