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:
result). The revised playbook is shown below:
result variable. Running the updated playbook produces debug output that looks like this:
Understanding the Registered Variable Content
The content stored in theresult 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:
result.rc:
Using Registered Variables Across Multiple Plays
Since registered variables are host-scoped, you can also access them in subsequent plays within the same playbook. For example:Verifying Command Output with Verbose Mode
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.