string 如何从 Ansible 的 lookup() 模块的结果中删除换行符 '\n'?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32016123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:26:28  来源:igfitidea点击:

How to remove the line breaker character '\n' from the result of lookup() module in Ansible?

stringreplaceansible

提问by Nishant Singh

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

我正在使用 [file lookup] 读取整个文件并将内容存储在变量中。我的游戏看起来像这样:

  - 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.xmlfile and stores it in the variable, but the problem is when the foo.xmlhas line breaks in it, it also includes the line break in the variable.

所以上面的代码读取foo.xml文件并将其存储在变量中,但问题是当其中foo.xml有换行符时,它还包括变量中的换行符。

My foo.xmlis this file:

我的foo.xml是这个文件:

<?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

输出删除换行符 \n 但也包括制表符 \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

我需要摆脱\n, 也需要摆脱额外的格式 (\r & \t),而且在替换过滤器之后,我在触发数据库更新查询时出现错误

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

回答by Andreas Maier

Use the Jinja trimfilter:

使用 Jinja修剪过滤器:

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

回答by udondan

You can do that with the replacefilter?

你可以replace用过滤器做到这一点吗?

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