1. 程式人生 > >Ansible常用模組-command模組

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 檔案不存在,就不執行我們指定的命令,此引數並不會幫助我們刪除檔案。

三、示例
[[email protected]

~]# 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 使用者家目錄中的檔案列表。

[[email protected] ~]# ansible ansible-demo3 -m command -a "chdir=/testdir ls"
ansible-demo3 | SUCCESS | rc=0 >>
testfile1
testfile2
chdir 引數表示執行命令之前,會先進入到指定的目錄中,所以上面命令表示檢視 ansible-demo3 主機上 /testdir 目錄中的檔案列表,返回顯示有2個檔案。

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

[[email protected] ~]# ansible ansible-demo3 -m command -a "creates=/testdir/testfile3 echo test"
ansible-demo3 | SUCCESS | rc=0 >>
test
上面命令表示 /testdir/testfile1 檔案存在於遠端主機中,則不執行對應命令。/testdir/testfile3 不存在,才執行”echo test”命令。

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

[[email protected] ~]# 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”命令。

四、總結
本節介紹了 Ansible 常用模組之 command 模組,並舉例說明如何使用,下節我們介紹 shell 模組。
--------------------- 
作者:dylloveyou 
來源:CSDN 
原文:https://blog.csdn.net/dylloveyou/article/details/80412513 
版權宣告:本文為博主原創文章,轉載請附上博文連結!