Capturing Script Output in Ansible Playbooks
Capturing the output of a script executed by Ansible is a fundamental task that allows you to gather information, troubleshoot issues, and automate complex processes. In this section, we will explore the different ways to capture script output in Ansible playbooks.
Using the register
Keyword
The most common method for capturing script output in Ansible is to use the register
keyword. This allows you to store the output of a task in a variable, which can then be used in subsequent tasks or output to the console.
- name: Execute a script and capture the output
command: /path/to/script.sh
register: script_output
- name: Print the script output
debug:
var: script_output.stdout
In the above example, the output of the /path/to/script.sh
command is stored in the script_output
variable. The stdout
field of the script_output
variable can then be used to access the standard output of the script.
Handling Different Output Types
Ansible can capture different types of output, including standard output (stdout), standard error (stderr), and return codes. You can access these different output types using the appropriate fields of the registered variable.
- name: Execute a script and capture the output
command: /path/to/script.sh
register: script_output
- name: Print the standard output
debug:
var: script_output.stdout
- name: Print the standard error
debug:
var: script_output.stderr
- name: Print the return code
debug:
var: script_output.rc
In this example, we access the stdout
, stderr
, and rc
(return code) fields of the script_output
variable to handle the different types of output.
Conditional Execution Based on Output
You can also use the captured output to conditionally execute tasks based on the script's behavior. This can be particularly useful for error handling and decision-making in your Ansible playbooks.
- name: Execute a script and capture the output
command: /path/to/script.sh
register: script_output
- name: Print the script output
debug:
var: script_output.stdout
- name: Handle script failure
debug:
msg: "The script failed with return code {{ script_output.rc }}"
when: script_output.rc != 0
In this example, we check the return code of the script (script_output.rc
) and only execute the "Handle script failure" task if the return code is not 0 (i.e., the script failed).