Search code examples
ansibleciscocisco-ios

Line breaks are removed in text output


I have a very long configuration file I am pulling from various pieces of equipment, and need it exactly as the command output gives me back. Ansible however, appears to be stripping the line breaks when I go to write the output to a file.

    - name: Pull the running-config...
      cisco.ios.ios_command:
        commands: show running-config brief
      register: running_output
...
...
    - name: Copy running_config data to file...
      ansible.builtin.copy:
        content: "{{  running_output.stdout_lines  }}"
        dest: "/etc/ansible/backups/{{  inventory_hostname  }}/running_config.txt"

When I debug the output, I do see the line breaks removed in stdout. But I also see a different output, (stdout_lines) as the configuration should be and not replaced with a ton of "\n"s.

Is there a way to ensure that line breaks exist in the output I send to file? Or ensure that the character that is replacing them is noted and formatted correctly?


Solution

  • Short answer: Use stdout instead of stdout_lines.

    Details: Given the below file for testing

    shell> cat /tmp/config.txt
    line1
    line2
    line3
    

    Read it and register the variable running_output

        - command: cat /tmp/config.txt
          register: running_output
    

    gives

      running_output:
        ansible_facts:
          discovered_interpreter_python: /usr/bin/python3
        changed: true
        cmd:
        - cat
        - /tmp/config.txt
        delta: '0:00:00.007317'
        end: '2023-11-02 02:15:50.172897'
        failed: false
        msg: ''
        rc: 0
        start: '2023-11-02 02:15:50.165580'
        stderr: ''
        stderr_lines: []
        stdout: |-
          line1
          line2
          line3
        stdout_lines:
        - line1
        - line2
        - line3
    

    If you use the list running_output.stdout_lines

        - copy:
            dest: /tmp/running_config.txt
            content: "{{ running_output.stdout_lines }}"
    

    You'll get the list

    shell> cat /tmp/running_config.txt 
    ["line1", "line2", "line"]
    

    Use running_output.stdout instead

        - copy:
            dest: /tmp/running_config.txt
            content: "{{ running_output.stdout }}"
    

    You'll get

    shell> cat /tmp/running_config.txt 
    line1
    line2
    line3