2016-10-25 31 views
42

現在我使用ansible shell腳本,這將是更具有可讀性,如果它是多條線路上如何做多shell腳本在Ansible

- name: iterate user groups 
    shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do 
    with_items: "{{ users }}" 

只是不知道如何讓多腳本Ansible外殼模塊

+0

也可以考慮使用ansible「腳本」命令,並使用一個外部文件 – Jason

回答

83

Ansible使用YAML語法在其劇本。 YAML有多個塊運算符:

  • >是摺疊塊運算符。也就是說,它通過空格將多條線連接在一起。語法如下:

    key: > 
        This text 
        has multiple 
        lines 
    

    將此數值This text has multiple lines\n分配給key

  • |字符是一個字面塊運算符。這可能是你想要的多行shell腳本。語法如下:

    key: | 
        This text 
        has multiple 
        lines 
    

    將此數值This text\nhas multiple\nlines\n分配給key

你可以這樣用這個多shell腳本:

- name: iterate user groups 
    shell: | 
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here 
    and_some_other_stuff 
    with_items: "{{ users }}" 

有一點需要注意:Ansible做的論據一些janky操作的shell命令,因此,儘管上述一般上班預計,下面將不會:

- shell: | 
    cat <<EOF 
    This is a test. 
    EOF 

Ansible實際上將呈現與前導空格的文本,這意味着外殼永遠不會找到字符串EOF在一行的開頭。你能避免Ansible的無益的啓發使用cmd參數是這樣的:

- shell: 
    cmd: | 
     cat <<EOF 
     This is a test. 
     EOF 
+4

夢幻般的答案 –

8

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

提到YAML線延續。

作爲一個例子(試圖用ansible 2.0.0.2):

--- 
- hosts: all 
    tasks: 
    - name: multiline shell command 
     shell: > 
     ls --color 
     /home 
     register: stdout 

    - name: debug output 
     debug: msg={{ stdout }} 

外殼命令摺疊成一個單一的線,如在ls --color /home

+2

是的,但是在外殼'>'有一個非常特殊的意義。我試過這個,並沒有像預期的那樣工作。 –

+3

這就是爲什麼它只是在第一行,而不是在後面的行。對於我來說,它在我編寫的ansible 2.0中工作得很好,但它並沒有用完整的1.9.4打印出完整的ls輸出。你使用什麼版本的Ansible? –