用空格分割字符串,然后在ansible / jinja2中再次连接它

时间:2016-09-30 14:38:04

标签: ansible jinja2

我正在尝试"清理" Ansible(ansible-2.1.1.0-1.fc24.noarch)剧本中的变量中的空格,虽然我先是 split()然后加入(&#39) ;')。出于某种原因,这种方法给我的错误如下: - /

---
- 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'具有无效值,似乎包含未定义的变量。错误是:'列出对象'没有属性'加入' ,但根据useful filters文档,它应该有效。

1 个答案:

答案 0 :(得分:11)

您应该使用管道来应用过滤器:

- debug:
    msg: "{{ mytext.split() | join(' ') }}"

在此示例中,split()是字符串对象的Python方法。所以这有点hackery join(' ')是一个Jinja2过滤器,它将列表连接成字符串。

通过调用mytext.split().join(' ')会出现错误,因为Python中的列表没有join方法。
Python中有join字符串方法,您可以调用' '.join(mytext.split()),但这将是双重攻击。