天天看點

08-script子產品Ansible常用子產品

一、概述

script 子產品可以幫助我們在遠端主機上執行 ansible 管理主機上的腳本,也就是說,腳本一直存在于 ansible 管理主機本地,不需要手動拷貝到遠端主機後再執行。

學習此子產品之前,請先學習 command 子產品。

二、常用參數

free_form參數 :必須參數,指定需要執行的腳本,腳本位于 ansible 管理主機本地,并沒有具體的一個參數名叫 free_form,具體解釋請參考 command 子產品。

chdir參數 : 此參數的作用就是指定一個遠端主機中的目錄,在執行對應的腳本之前,會先進入到 chdir 參數指定的目錄中。

creates參數 :使用此參數指定一個遠端主機中的檔案,當指定的檔案存在時,就不執行對應腳本,可參考 command 子產品中的解釋。

removes參數 :使用此參數指定一個遠端主機中的檔案,當指定的檔案不存在時,就不執行對應腳本,可參考 command 子產品中的解釋。

三、示例

[root@ansible-manager ~]# ansible ansible-demo3 -m script -a "chdir=/opt /testdir/testscript.sh"
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to ansible-demo3 closed.\r\n", 
    "stdout": "testscript\r\n", 
    "stdout_lines": [
        "testscript"
    ]
}
           

其中 testscript.sh 腳本為列印 ‘testscript’ 字元串。

[root@ansible-manager ~]# cat /testdir/testscript.sh
echo 'testscript'
           

上面指令表示 ansible 主機中的 /testdir/testscript.sh 腳本将在 ansible-demo3 主機中執行,執行此腳本之前,會先進入到 ansible-demo3 主機中的 /opt 目錄

[root@ansible-manager ~]# ansible ansible-demo3 -m script -a "creates=/testdir/testfile1 /testdir/testscript.sh"
ansible-demo3 | SKIPPED
           

上面指令表示,ansible-demo3 主機中的 /testdir/testfile1檔案已經存在,ansible 主機中的 /testdir/testscript.sh 腳本将不會在 ansible-demo3 主機中執行。

[root@ansible-demo3 ~]# ls /testdir/
test  testfile1  testfile2
           

由于 testfile1 已經存在,則 SKIPPED。

[root@ansible-manager ~]# ansible ansible-demo3 -m script -a "removes=/testdir/testfile1 /testdir/testscript.sh"
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to ansible-demo3 closed.\r\n", 
    "stdout": "testscript\r\n", 
    "stdout_lines": [
        "testscript"
    ]
}
           

上面指令表示,ansible-demo3 主機中的 /testdir/testfile1 檔案存在,ansible 主機中的 /testdir/testscript.sh 腳本則會在 ansible-demo3 主機中執行。

繼續閱讀