在之前的文章中,我們已經(jīng)對 Ansible 以及 Ansible Adhoc 做了講解,下面會對 Ansible 的常用模塊進(jìn)行講解,主要包括 命令模塊、文件處理模塊、包管理模塊、服務(wù)管理模塊等。
今天就帶大家熟悉一下 Ansible 的幾個命令模塊,包括:
-
command- 在遠(yuǎn)程節(jié)點上執(zhí)行命令 -
shell- 讓遠(yuǎn)程主機(jī)在 shell 進(jìn)程下執(zhí)行命令 -
raw- 在沒有 Python 環(huán)境的主機(jī)上執(zhí)行命令
command 模塊
-
command模塊用于在給的的節(jié)點上運行系統(tǒng)命令,比如 echo hello。 - 不是調(diào)用的 shell 的指令,所以沒有 bash 的環(huán)境變量,也不能使用 shell 的一些操作方式,因此不支持像
$HOME這樣的變量,以及<、>、|、;和&等都是無效的。也就是在command模塊中 無法使用管道符。
模塊參數(shù)
| 名稱 | 必選 | 備注 |
|---|---|---|
| chdir | no | 運行 command 命令前先 cd 到這個目錄 |
| creates | no | 如果這個參數(shù)對應(yīng)的文件存在,就不運行 command |
| removes | no | 如果這個參數(shù)對應(yīng)的文件不存在,就不運行 command,與 creates 參數(shù)的作用相反 |
示例
- 列出指定目錄下的文件
# ansible test -m command -a "ls /root"
172.20.21.120 | SUCCESS | rc=0 >>
anaconda-ks.cfg
test.sh
whoami.rst
- 根據(jù)指定文件是否存在判斷是否執(zhí)行
# ansible test -m command -a "ls /root creates=test.sh"
172.20.21.120 | SUCCESS | rc=0 >>
skipped, since test.sh exists
# ansible test -m command -a "ls /root removes=test.sh1"
172.20.21.120 | SUCCESS | rc=0 >>
skipped, since test.sh1 does not exist
- 切換目錄執(zhí)行命令
# ansible test -m command -a "cat test.sh chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
#!/bin/bash
i=0
echo $((i+1))
# ansible test -m command -a "sh test.sh chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
1
- 無法使用管道符
# ansible test -m command -a "ls /root | grep test"
172.20.21.120 | FAILED | rc=2 >>
/root:
anaconda-ks.cfg
test.sh
whoami.rstls: 無法訪問|: 沒有那個文件或目錄
ls: 無法訪問grep: 沒有那個文件或目錄
ls: 無法訪問test: 沒有那個文件或目錄non-zero return code
shell模塊
讓遠(yuǎn)程主機(jī)在 shell 進(jìn)程下執(zhí)行命令,從而支持 shell 的特性,如管道等。與 command 模塊幾乎相同,但在執(zhí)行命令的時候調(diào)用的是 /bin/sh。
模塊參數(shù)與 command 模塊相同。
示例
- 切換目錄,執(zhí)行命令并保持輸出
# ansible test -m shell -a "sh test.sh > result chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
# ansible test -m shell -a "cat result chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
1
raw模塊
簡介
raw 模塊不需要遠(yuǎn)程系統(tǒng)上的 Python。
raw 模塊只適用于下列兩種場景,第一種情況是在較老的(Python 2.4和之前的版本)主機(jī)上,另一種情況是對任何沒有安裝 Python 的設(shè)備(如路由器)。 在其他情況下,使用 shell 或 command 模塊更為合適。
示例
# ansible test -m raw -a "pwd"
172.20.21.120 | SUCCESS | rc=0 >>
/root
Shared connection to 172.20.21.120 closed.
區(qū)別
command,shell,raw 模塊都是 ansible 遠(yuǎn)程執(zhí)行命令的一種指令模式,但是它們的適用還是有一定的區(qū)別。
-
command模塊不是調(diào)用的 shell 的指令,所以不能使用 bash 的環(huán)境變量,也不能使用 shell 的一些操作方式,其他和 shell 沒有區(qū)別;另外,command 模塊更安全,因為它不受用戶環(huán)境變量的影響。 -
shell與 command 模塊幾乎相同,但在執(zhí)行命令的時候使用的是 /bin/sh。從而支持 shell 的特性,如管道等。 -
raw很多地方和 shell 類似,更多的地方建議使用 shell 和 command 模塊。但是如果是使用老版本 python,需要用到 raw,又或者是沒有安裝 python 模塊的客戶端,如路由器。
如果覺得有用,歡迎關(guān)注我的微信,有問題可以直接交流:

你的關(guān)注是對我最大的鼓勵!