一、概述
shell 子產品可以幫助我們在遠端主機上執行指令。與 command 子產品不同的是,shell 子產品在遠端主機中執行指令時,會經過遠端主機上的 /bin/sh 程式處理。
學習此子產品之前,請先參考 command 子產品的介紹。
二、常用參數
free_form參數 :必須參數,指定需要遠端執行的指令,但是并沒有具體的一個參數名叫free_form,具體解釋參考 command 子產品。
chdir參數 : 此參數的作用就是指定一個目錄,在執行對應的指令之前,會先進入到 chdir 參數指定的目錄中。
creates參數 :使用此參數指定一個檔案,當指定的檔案存在時,就不執行對應指令,可參考command 子產品中的解釋。
removes參數 :使用此參數指定一個檔案,當指定的檔案不存在時,就不執行對應指令,可參考 command 子產品中的解釋。
executable參數:預設情況下,shell 子產品會調用遠端主機中的 /bin/sh 去執行對應的指令,通常情況下,遠端主機中的預設 shell 都是 bash。如果你想要使用其他類型的 shell 執行指令,則可以使用此參數指定某種類型的 shell 去執行對應的指令。指定 shell 檔案時,需要使用絕對路徑。
三、示例
shell 子產品中 chdir、creates、removes 參數的作用與 command 子產品中的作用都是相同的,此處不再舉例。
[root@ansible-manager ~]# ansible ansible-demo3 -m shell -a "chdir=/testdir echo mytest > test"
ansible-demo3 | SUCCESS | rc=0 >>
使用 shell 子產品可以在遠端伺服器上執行指令,它支援管道與重定向等符号。上面指令列印出mytest并寫入test檔案。
[root@ansible-manager ~]# ansible ansible-demo3 -m shell -a "chdir=/testdir ls"
ansible-demo3 | SUCCESS | rc=0 >>
test
testfile1
testfile2
上面指令列出了 /testdir 下面的檔案,多了個 test 檔案。
[root@ansible-manager ~]# ansible ansible-demo3 -m shell -a "chdir=/testdir cat test"
ansible-demo3 | SUCCESS | rc=0 >>
mytest
上面指令列出了 test 檔案的内容。
由于 command 比較安全有可預知性,是以我們平時用的時候,最好用 command。需要用到 shell 特性的時候,再用 shell。