2016-09-30 31 views
0

我試圖「清理」在Ansible變量中的空格(ansible-2.1.1.0-1.fc24.noarch)playbook和我雖然我會首先split()它然後再次加入('')。出於某種原因,這種做法是給我的錯誤如下: -/由空格分割字符串,然後在ansible/jinja2中再次加入它

--- 
- 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文檔,它應該工作。

回答

5

應使用管道應用過濾器:

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

在這個例子中split()是String對象的Python的方法。所以這有點嘮叨。
join(' ')是一個Jinja2過濾器,它將一個列表連接成一個字符串。

通過調用mytext.split().join(' '),您會收到錯誤消息,因爲Python中沒有用於列表的join方法。
在Python中有用於字符串的join方法,你可以調用' '.join(mytext.split()),但它會是一個雙重黑客。

+1

該死的,我很確定我已經試過了。爲什麼是mytext.split()|從mytext.split()加入('')'deffierent?join('')'反正?謝謝! – jhutar

+1

我已經用解釋更新了我的答案。 –