How to display script output in Ansible playbook?

AnsibleAnsibleBeginner
Practice Now

Introduction

Ansible, the popular infrastructure automation tool, provides a powerful way to execute scripts and commands on remote hosts. However, effectively displaying the output of these scripts within your Ansible playbooks can be a crucial aspect of monitoring and troubleshooting your automation workflows. This tutorial will guide you through the process of displaying script output in Ansible playbooks, covering both basic and advanced techniques.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ansible(("`Ansible`")) -.-> ansible/ModuleOperationsGroup(["`Module Operations`"]) ansible(("`Ansible`")) -.-> ansible/PlaybookEssentialsGroup(["`Playbook Essentials`"]) ansible/ModuleOperationsGroup -.-> ansible/shell("`Execute Shell Commands`") ansible/ModuleOperationsGroup -.-> ansible/template("`Generate Files from Templates`") ansible/ModuleOperationsGroup -.-> ansible/debug("`Test Output`") ansible/PlaybookEssentialsGroup -.-> ansible/playbook("`Execute Playbook`") ansible/PlaybookEssentialsGroup -.-> ansible/roles("`Assign Roles`") subgraph Lab Skills ansible/shell -.-> lab-415724{{"`How to display script output in Ansible playbook?`"}} ansible/template -.-> lab-415724{{"`How to display script output in Ansible playbook?`"}} ansible/debug -.-> lab-415724{{"`How to display script output in Ansible playbook?`"}} ansible/playbook -.-> lab-415724{{"`How to display script output in Ansible playbook?`"}} ansible/roles -.-> lab-415724{{"`How to display script output in Ansible playbook?`"}} end

Understanding Ansible Playbook Output

Ansible is a powerful automation tool that allows you to manage and configure your infrastructure through the use of playbooks. When executing an Ansible playbook, it's essential to understand the output generated by the playbook, as it provides valuable information about the execution process and the results of the tasks.

Ansible Playbook Output Structure

Ansible playbook output typically consists of the following elements:

  1. Task Execution: Ansible displays the tasks being executed, including the module name, the task name, and any parameters passed to the module.
  2. Task Result: Ansible displays the result of each task, including any output, changes made, and the status of the task (success, failure, or skipped).
  3. Host Summaries: At the end of the playbook execution, Ansible provides a summary of the tasks performed on each host, including the number of tasks that were changed, failed, or skipped.
  4. Playbook Execution Summary: Ansible provides an overall summary of the playbook execution, including the total number of tasks, the number of tasks that were changed, failed, or skipped, and the total execution time.

Understanding Task Execution and Results

When a task is executed, Ansible displays the task name and the module being used. The output also includes any parameters passed to the module, as well as the result of the task execution.

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

In this example, the task "Gathering Facts" is executed on the "localhost" host, and the task result is "ok", indicating that the task was successful.

Handling Task Failures

If a task fails during the playbook execution, Ansible will display the error message and the task result will be "failed".

TASK [Install Apache] *****************************************************
failed: [localhost] => {"changed": false, "msg": "No package matching 'apache2' is available", "rc": 1, "results": []}

In this example, the "Install Apache" task failed because the package "apache2" is not available on the system.

Skipping Tasks

Ansible may skip certain tasks based on the conditions defined in the playbook or the state of the target system.

TASK [Install Python] *****************************************************
skipped: [localhost]

In this example, the "Install Python" task was skipped because Python is already installed on the "localhost" host.

By understanding the structure and content of the Ansible playbook output, you can effectively troubleshoot issues, monitor the execution progress, and ensure that your playbooks are performing as expected.

Displaying Script Output in Playbooks

In addition to the default output generated by Ansible, you may want to display the output of scripts or commands executed within your playbooks. Ansible provides several ways to handle and display script output, allowing you to gain more visibility into the execution process.

Using the command or shell Modules

The command and shell modules in Ansible allow you to execute scripts or commands on the target hosts. By default, Ansible will display the output of these tasks in the playbook output.

- name: Run a script
  command: /path/to/script.sh
  register: script_output

In this example, the output of the script /path/to/script.sh will be captured in the script_output variable, which can be used later in the playbook.

Displaying the Output

To display the output of a script, you can use the debug module and reference the registered variable.

- name: Display script output
  debug:
    var: script_output.stdout

This will print the standard output (stdout) of the script to the playbook output.

Handling Errors and Exit Codes

If a script or command executed using the command or shell modules fails, Ansible will automatically mark the task as failed. You can inspect the exit code and error messages using the registered variable.

- name: Run a script
  command: /path/to/script.sh
  register: script_output
  failed_when: script_output.rc != 0

- name: Display script output
  debug:
    var: script_output.stdout
    verbosity: 2

In this example, the failed_when condition checks the exit code (script_output.rc) and marks the task as failed if the exit code is not 0 (indicating a successful execution). The script output is then displayed using the debug module, but only when the verbosity level is set to 2 or higher.

By leveraging the capabilities of the command and shell modules, along with the registered variables, you can effectively display and handle the output of scripts executed within your Ansible playbooks.

Advanced Output Handling Techniques

While the basic techniques for displaying script output in Ansible playbooks are useful, there are more advanced methods that can provide greater flexibility and control over the output handling.

Filtering and Transforming Output

Ansible provides the json_query filter, which allows you to extract specific data from the output using a JSON query language. This can be particularly helpful when dealing with complex or structured output.

- name: Run a script
  command: /path/to/script.sh
  register: script_output

- name: Display filtered output
  debug:
    var: script_output.stdout | json_query('[*].name')

In this example, the json_query filter is used to extract the "name" field from the script output, which is assumed to be in a JSON format.

Handling Multiline Output

If a script generates multiline output, you can use the splitlines() filter to split the output into a list of lines, making it easier to process.

- name: Run a script
  command: /path/to/script.sh
  register: script_output

- name: Display multiline output
  debug:
    var: script_output.stdout.splitlines()

Conditional Debugging

In some cases, you may want to display the script output only when certain conditions are met, such as when a task fails or when the verbosity level is set to a specific value.

- name: Run a script
  command: /path/to/script.sh
  register: script_output
  failed_when: script_output.rc != 0

- name: Display script output on failure
  debug:
    var: script_output.stdout
  when: script_output.failed

In this example, the script output is only displayed when the task fails (i.e., the exit code is not 0).

Integrating with LabEx

LabEx is a powerful tool that can enhance your Ansible playbook output. By integrating LabEx into your playbooks, you can take advantage of its advanced output formatting and visualization capabilities.

- name: Run a script
  command: /path/to/script.sh
  register: script_output
  failed_when: script_output.rc != 0

- name: Display script output with LabEx
  labex:
    data: "{{ script_output.stdout }}"
    title: "Script Output"
    type: "text"
  when: script_output.failed

In this example, the script output is displayed using the LabEx module, which provides a more visually appealing and structured output format.

By exploring these advanced output handling techniques, you can gain greater control and flexibility over the presentation of your Ansible playbook output, making it easier to troubleshoot, analyze, and share with your team.

Summary

In this Ansible tutorial, you will learn how to display script output within your playbooks, enabling you to better understand and troubleshoot your automation processes. By mastering the techniques covered, you will be able to enhance the visibility and transparency of your Ansible-powered infrastructure, leading to more efficient and reliable deployments.

Other Ansible Tutorials you may like