天天看點

06-Ansible常用子產品-command子產品

一、概述

command 子產品可以幫助我們在遠端主機上執行指令。

注意:使用 command 子產品在遠端主機中執行指令時,不會經過遠端主機的 shell 處理,在使用 command 子產品時,如果需要執行的指令中含有重定向、管道符等操作時,這些符号也會失效,比如”<”, “>”, “|”, “;” 和 “&” 這些符号,如果你需要這些功能,可以參考後面介紹的 shell 子產品。還有一點需要注意,如果遠端節點是 windows 作業系統,則需要使用 win_command 子產品。

執行 ansible 時,不加 -m 預設使用 command ,可以在 /etc/ansible/ansible.cfg 中修改。

# default module name for /usr/bin/ansible
#module_name = command
           

二、常用參數

free_form參數 :必須參數,指定需要遠端執行的指令。需要說明一點,free_form 參數與其他參數(如果想要使用一個參數,那麼則需要為這個參數指派,也就是name=value模式)并不相同。比如,當我們想要在遠端主機上執行 ls 指令時,我們并不需要寫成”free_form=ls” ,這樣寫反而是錯誤的,因為并沒有任何參數的名字是 free_form,當我們想要在遠端主機中執行 ls 指令時,直接寫成 ls 即可。因為 command 子產品的作用是執行指令,是以,任何一個可以在遠端主機上執行的指令都可以被稱為 free_form。

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

creates參數 :看到 creates,你可能會從字面上了解這個參數,但是使用這個參數并不會幫助我們建立檔案,它的作用是當指定的檔案存在時,就不執行對應指令,比如,如果 /testdir/test檔案存在,就不執行我們指定的指令。

removes參數 :與 creates 參數的作用正好相反,它的作用是當指定的檔案不存在時,就不執行對應指令,比如,如果 /testdir/tests 檔案不存在,就不執行我們指定的指令,此參數并不會幫助我們删除檔案。

三、示例

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "ls"
ansible-demo3 | SUCCESS | rc=0 >>
anaconda-ks.cfg
CentOS7-Base-163.repo
Centos-7.repo
           

上面指令表示在 ansible-demo3 主機上執行 ls 指令,因為使用的是 root 使用者,是以預設情況下,ls 出的結果是 ansible-demo3 主機中 root 使用者家目錄中的檔案清單。

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "chdir=/testdir ls"
ansible-demo3 | SUCCESS | rc=0 >>
testfile1
testfile2
           

chdir 參數表示執行指令之前,會先進入到指定的目錄中,是以上面指令表示檢視 ansible-demo3 主機上 /testdir 目錄中的檔案清單,傳回顯示有2個檔案。

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "creates=/testdir/testfile1 echo test"
ansible-demo3 | SUCCESS | rc=0 >>
skipped, since /testdir/testfile1 exists

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "creates=/testdir/testfile3 echo test"
ansible-demo3 | SUCCESS | rc=0 >>
test
           

上面指令表示 /testdir/testfile1 檔案存在于遠端主機中,則不執行對應指令。/testdir/testfile3 不存在,才執行”echo test”指令。

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "removes=/testdir/testfile1 echo test"
ansible-demo3 | SUCCESS | rc=0 >>
test

[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "removes=/testdir/testfile3 echo test"
ansible-demo3 | SUCCESS | rc=0 >>
skipped, since /testdir/testfile3 does not exist
           

上面指令表示 /testdir/testfile3 檔案不存在于遠端主機中,則不執行對應指令。/testdir/testfile1 存在,才執行”echo test”指令。

繼續閱讀