Keywords: Ansible | Debug Module | Multi-line Output
Abstract: This paper comprehensively examines common challenges in outputting multi-line messages using the debug module in Ansible automation tools. By analyzing real-world issues encountered during Jenkins slave deployment where variable content failed to display with proper line breaks, the article systematically compares four distinct solutions. It focuses on the best practice approach using with_items loops, which achieves clear multi-line output through structured data while maintaining code maintainability. The paper also provides detailed explanations of YAML array syntax, string splitting techniques, and pause module alternatives, offering Ansible users a complete guide to multi-line message output.
Problem Context and Challenges
In Ansible configuration management, using the debug module for outputting diagnostic information is a common development practice. However, when needing to output messages containing multiple lines, users frequently encounter formatting display issues. As shown in the user case, during Jenkins slave deployment configuration tasks, attempts to use \n escape characters for line breaks resulted in variable content being displayed as a single-line string rather than the expected formatted output.
Core Solution: with_items Loop Method
Based on the best answer (Answer 4), the most effective solution utilizes Ansible's with_items loop structure. This approach achieves clear, maintainable multi-line output by decomposing multi-line messages into structured data items.
The following code example demonstrates how to refactor the original debugging task:
- debug: msg="Installing swarm slave = {{ slave_name }} at {{ slaves_dir }}/{{ slave_name }}"
- debug: msg="Slave properties = {{ item.prop }} [ {{ item.value }} ]"
with_items:
- { prop: 'fsroot', value: "{{ slave_fsroot }}" }
- { prop: 'master', value: "{{ slave_master }}" }
- { prop: 'connectingToMasterAs', value: "{{ slave_user }}" }
- { prop: 'description', value: "{{ slave_desc }}" }
- { prop: 'No.Of.Executors', value: "{{ slave_execs }}" }
- { prop: 'LABELs', value: "{{ slave_labels }}" }
- { prop: 'mode', value: "{{ slave_mode }}" }
tags:
- koba
The advantages of this method include:
- Clear Structure: Each property is processed as an independent item, automatically displaying with line breaks
- Easy Maintenance: Property lists can be easily added, removed, or modified
- Variable Safety: All variables are referenced through standard Jinja2 template syntax
- Tag Support: Task tags can be conveniently added for selective execution
Alternative Solutions Comparison
YAML Array Syntax (Answer 1)
Ansible's debug module natively supports message arrays, making this one of the most straightforward solutions:
debug:
msg:
- "First line"
- "Second line with variable {{ var1 }}"
The output format is a JSON array with each line as an independent string element. This method is simple and intuitive but requires manually splitting long messages into array elements.
String Splitting Technique (Answer 2)
Define multi-line text through variables, then convert to arrays using the split() method:
- name: Print several lines of text
vars:
msg: |
This is the first line.
This is the second line with a variable like {{ inventory_hostname }}.
And here could be more...
debug:
msg: "{{ msg.split('\n') }}"
This approach leverages YAML's multi-line string syntax (|), maintaining the natural format of message content, but requires attention to potential trailing empty lines.
Pause Module Alternative (Answer 3)
For scenarios requiring complex formatting, the pause module can substitute for debug:
- pause:
seconds: 1
prompt: |
======================
line_1
line_2 with {{ variable }}
======================
This method supports arbitrary text formatting including tabs, borders, etc., but note that the pause module executes only on the first host and may disrupt automation flow continuity.
Technical Principle Analysis
The fundamental cause of message display issues in Ansible lies in the output processing mechanism. The debug module's msg parameter expects strings or string arrays. When strings containing \n are passed, these escape characters are processed during YAML parsing but may be re-encoded or displayed as literals in final output.
YAML's multi-line string syntax offers three main approaches:
- Literal Block Scalar (|): Preserves line breaks and trailing empty lines
- Folded Block Scalar (>): Folds line breaks into spaces
- Block Scalar with Indicators: Controls indentation and line break handling
In the Ansible context, Jinja2 template engine variable interpolation occurs after YAML parsing, which can create sequencing issues in line break processing.
Best Practice Recommendations
- Use Array Syntax for Simple Messages: For messages with few fixed lines, YAML arrays are most concise
- Use with_items for Structured Data: When output content has clear structural properties, adopt the best answer method
- Consider Pause Module for Complex Formatting: Use only when special formatting is needed and interactive interruption is acceptable
- Maintain Consistency: Adopt a unified multi-line output strategy within projects
- Test Validation: Test format effectiveness across different Ansible versions and output targets (console, log files)
Conclusion
The key to achieving multi-line message output in Ansible lies in understanding the interaction between YAML parsing, Jinja2 template processing, and output rendering. The with_items-based approach provides the optimal balance: maintaining structured code clarity while ensuring output readability and maintainability. By selecting appropriate solutions for specific scenarios, developers can effectively enhance debugging experience and operational efficiency in Ansible playbooks.