我正在尝试“清理” Ansible (ansible-2.1.1.0-1.fc24.noarch) 剧本中变量中的空格,但我首先会split()它然后加入(' ')再次。由于某种原因,该方法给了我以下错误:-/
---
- 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”具有无效值,该值似乎包含未定义的变量。错误是:“列表对象”没有属性“加入”,但根据有用的过滤器 http://docs.ansible.com/ansible/playbooks_filters.html#other-useful-filters文档,它应该有效。
您应该使用管道来应用过滤器:
- debug:
msg: "{{ mytext.split() | join(' ') }}"
在这个例子中split()
是字符串对象的Python方法。所以这有点黑客行为。
And join(' ')
是一个 Jinja2 过滤器,它将列表连接成字符串。
通过致电mytext.split().join(' ')
你会得到错误,因为没有join
Python 中列表的方法。
有join
Python中字符串的方法,你可以调用' '.join(mytext.split())
,但这将是双重黑客。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)