How to remove the line breaker character '\\n&

2019-02-06 07:11发布

问题:

I am using [file lookup] which reads the whole file and stores the content in a variable. My play looks something like this:

  - name: Store foo.xml contents in a variable
    set_fact:
     foo_content: "{{ lookup('file', 'foo.xml' ) | replace('\n', '')}}"

So the above code reads the foo.xml file and stores it in the variable, but the problem is when the foo.xml has line breaks in it, it also includes the line break in the variable.

My foo.xml is this file:

<?xml version="1.0" encoding="utf-8"?>
<initialize_param>
    <secrets>
        <my_secret id="99">3VMjII6Hw+pd1zHV5THSI712y421USUS8124487128745812sajfhsakjfasbfvcasvnjasjkvbhasdfasgfsfaj5G8A9+n8CkLxk7Dqu0G8Jclg0eb1A5xeFzR3rrJHrb2GBBa7PJNVx8tFJP3AtF6ek/F/WvlBIs2leX2fq+/bGryKlySuFmbcwBsThmPJC5Z5AwPJgGZx</my_secret>
    </secrets>
</initialize_param>

The output removes line break \n but also incudes the tabs \r & \t

I need to got rid of the \n , need to get rid of extra formatting too (\r & \t), Moreover after the replace filter I get the error while firing a DB Update query as

stderr: /bin/sh: 1: cannot open ?xml: No such file

回答1:

You can do that with the replace filter?

contents: "{{ lookup('file', '/etc/foo.txt') | replace('\n', '')}}"


回答2:

Use the Jinja trim filter:

"{{ lookup('file', 'foo.xml' ) | trim }}"