按空格分割字符串,然后在 ansible/jinja2 中再次加入 [英] splitting string by whitespace and then joining it again in ansible/jinja2

查看:33
本文介绍了按空格分割字符串,然后在 ansible/jinja2 中再次加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理" Ansible (ansible-2.1.1.0-1.fc24.noarch) 剧本中的变量中的空格,尽管我会首先 split() 它并且然后再次加入(' ').出于某种原因,这种方法给了我以下错误:-/

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"有一个无效值,它似乎包含一个未定义的变量.错误是:'list object' 没有属性 'join',但根据 有用的过滤器 文档,它应该可以工作.

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 方法.所以它有点hacky.
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆