How to Display File Contents Without Debug Module in Ansible Playbooks


1 views

When working with Ansible playbooks, we often need to display file contents during execution. While the debug module works, it shows output in JSON format which isn't always ideal for end-users or clean logging.

Here are three effective methods to display file contents properly:


# Method 1: Using command module with echo
- name: Display Google Authenticator config
  command: "cat {{ google_authenticator_secret_file_location }}"
  register: ga_config
  changed_when: false

- name: Show config
  debug:
    var: ga_config.stdout

For better formatting of multi-line files:


# Method 2: Using lineinfile to display with proper formatting
- name: Read and display file
  shell: |
    echo "----- Google Authenticator Config -----"
    cat {{ google_authenticator_secret_file_location }}
    echo "--------------------------------------"
  register: formatted_output
  changed_when: false

- name: Show formatted output
  debug:
    var: formatted_output.stdout

For frequent use, create a custom filter plugin:


# In filter_plugins/file_filters.py
def file_display(content):
    return "File Contents:\n" + content

class FilterModule(object):
    def filters(self):
        return {'file_display': file_display}

Then in your playbook:


- name: Display using custom filter
  debug:
    msg: "{{ ga_config.stdout | file_display }}"

The original error occurs because of YAML parsing. This is the correct syntax:


- debug:
    msg: "{{ details.stdout_lines | join('\n') }}"

The | join('\n') filter converts the list to properly formatted multi-line output.


When working with Ansible, we often need to display file contents during playbook execution. The debug module works but produces output wrapped in JSON format with variable names and metadata, which isn't ideal for clean user-facing output.

Here are three effective methods to display file contents cleanly:


# Method 1: Using command module with echo
- name: Display file contents
  command: "cat {{ google_authenticator_secret_file_location }}"
  register: file_output
  changed_when: false
  
- name: Show output cleanly
  debug:
    msg: "{{ file_output.stdout }}"

The original error occurs because of improper YAML formatting. Here's the corrected version:


- name: Print file contents
  debug:
    var: details.stdout

Or alternatively:


- name: Print file contents
  debug:
    msg: |
      {{ details.stdout_lines | join('\n') }}

Another approach is using the copy module with content filtering:


- name: Display file contents
  copy:
    content: "{{ lookup('file', google_authenticator_secret_file_location) }}"
    dest: /dev/stdout

For multi-line files with special formatting needs:


- name: Display formatted output
  debug:
    msg: |
      Google Authenticator Configuration:
      ==================================
      {{ details.stdout }}
      ==================================