通过空格分割字符串,然后再次将其加入ansible/jinja2 [英] splitting string by whitespace and then joining it again in ansible/jinja2
问题描述
我正在尝试清理" Ansible(ansible-2.1.1.0-1.fc24.noarch)剧本中的变量中的空格,尽管我首先会对其进行 split()然后再次 join('').由于某种原因,这种方法在下面给了我错误:-/
I'm trying to "cleanup" whitespaces in a variable in Ansible (ansible-2.1.1.0-1.fc24.noarch) playbook and I though I'll first split() it and then join(' ') again. For some reason that approach is giving me error below :-/
---
- hosts: all
remote_user: root
vars:
mytext: |
hello
there how are
you?
tasks:
- debug:
msg: "{{ mytext }}"
- debug:
msg: "{{ mytext.split() }}"
- debug:
msg: "{{ mytext.split().join(' ') }}"
...
给我:
TASK [debug] *******************************************************************
ok: [192.168.122.193] => {
"msg": "hello\nthere how are\nyou?\n"
}
TASK [debug] *******************************************************************
ok: [192.168.122.193] => {
"msg": [
"hello",
"there",
"how",
"are",
"you?"
]
}
TASK [debug] *******************************************************************
fatal: [192.168.122.193]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'join'\n\nThe error appears to have been in '.../tests.yaml': line 15, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n msg: \"{{ mytext.split() }}\"\n - debug:\n ^ here\n"}
关于我在做什么错的任何想法吗?它说字段"args"具有无效值,该值似乎包含未定义的变量.错误是:列表对象"没有属性连接" ,但是根据有用的过滤器文档,它应该可以工作.
Any idea on what I'm doing wrong? It says the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'join', but according to useful filters docs, it should work.
推荐答案
您应使用管道应用过滤器:
You should use pipe to apply a filter:
- debug:
msg: "{{ mytext.split() | join(' ') }}"
在此示例中,split()
是字符串对象的Python方法.所以有点黑客.
join(' ')
是Jinja2过滤器,它将列表连接成字符串.
In this example split()
is a Python method of string object. So it's a bit hackery.
And join(' ')
is a Jinja2 filter that concatenates a list into string.
通过调用mytext.split().join(' ')
会出错,因为Python中没有用于列表的join
方法.
Python中有用于字符串的join
方法,您可以调用' '.join(mytext.split())
,但这将是双重攻击.
By calling mytext.split().join(' ')
you get error, because there is no join
method for lists in Python.
There is join
method for string in Python and you can call ' '.join(mytext.split())
, but it will be a double hack.
这篇关于通过空格分割字符串,然后再次将其加入ansible/jinja2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!