Understanding the debug Module in Ansible: | vs. >

One of the key features in Ansible is the ability to output messages to help debug and understand your playbooks. This is often done using the debug module. However, how you format your debug messages can significantly impact readability and output. In this post, we’ll explore the difference between using the | and > operators in Ansible’s debug module.

The debug Module

The debug module is easy to use and lets you print messages during playbook execution, which is helpful for troubleshooting or displaying information.

Here’s a basic example:

- name: Debug message example
  hosts: localhost
  tasks:
    - name: Print a debug message
      debug:
        msg: "Hello, world!"

This will output:

TASK [Print a debug message] ***************************************************
ok: [localhost] => {
    "msg": "Hello, world!"
}

Using | for Literal Block Scalars

When you use the | operator, you indicate that the text should be treated as a literal block scalar. This means that newlines are preserved as they are.

Example:

- name: Debug message with literal block scalar
  hosts: localhost
  tasks:
    - name: Print a multi-line debug message
      debug:
        msg: |
          Hello, world!
          This is an example.

Output:

TASK [Print a multi-line debug message] ****************************************
ok: [localhost] => {
    "msg": "Hello, world!\nThis is an example.\n"
}

As you can see, the newlines are preserved in the output, maintaining the exact formatting you used in your playbook.

Using > for Folded Block Scalars

Conversely, the > operator is used for folded block scalars. This means that newlines are replaced with spaces, except for double newlines, which are converted to single newlines.

Example:

- name: Debug message with folded block scalar
  hosts: localhost
  tasks:
    - name: Print a folded multi-line debug message
      debug:
        msg: >
          Hello, world!
          This is an example.

Output:

TASK [Print a folded multi-line debug message] *********************************
ok: [localhost] => {
    "msg": "Hello, world! This is an example.\n"
}

In this case, the newlines within the text are replaced by spaces, resulting in a single line of output.

When to Use Each Operator

  • Use | when you want to maintain the exact formatting of your text, including newlines. This is useful for long messages or logs that need to be displayed in a specific format.
  • Use > when you want a more compact representation, where newlines are replaced by spaces. This can be handy for simpler messages or when you want to ensure the output is concise.
Compartir:

This article was written by RoberMB

💻OS, ☁️Cloud, 🛡️Cybersecurity, ✈️Traveling #Linux, #Ansible, #AWS, #VMware, #Docker 🏴‍☠️ CEH v10, CPHE 🏴‍☠️ ... Always learning, always enjoying.

Leave a Reply

Your email address will not be published. Required fields are marked *