1. 程式人生 > >自動化運維工具Ansible實戰---常用模組

自動化運維工具Ansible實戰---常用模組

Ansible預設提供了很多模組來供我們使用。在Linux中,我們可以通過 ansible-doc -l 命令檢視到當前Ansible支援哪些模組,通過 ansible-doc -s [模組名] 又可以檢視該模組有哪些引數可以使用。

ansible [主機或組] -m [模組名] -a ['模組引數'] [ansible引數]
ansible-doc -l          # 命令檢視到當前 ansible 都支援哪些模組
ansible-doc -s [模組名]  # 檢視該模組有哪些引數可以使用

自動化運維工具Ansible常用模組按功能可分為:
雲模組、叢集模組、 命令模組、資料庫模組、檔案模組、資產模組、訊息模組、監控模組、網路模組、通知模組、包管理模組、原始碼控制模組、系統模組、單元模組、web設施模組、windows模組。
具體模組可參考官網(

http://docs.ansible.com/ansible/latest/list_of_all_modules.html)。

這裡從官方分類的模組裡選擇最常用的一些模組進行介紹。

一、command模組

1、簡介

  • command模組用於在給的的節點上執行系統命令,比如echo hello
  • 該模組通過-a跟上要執行的命令可以直接執行,它不會通過shell進行處理,因此諸如$ HOME和諸如“<”,“>”,“|”,“;”和“&”之類的操作將不起作用,也就是在command模組中無法使用管道符(如果需要這些功能,請使用shell模組)
  • 對於Windows目標,請改用win_command模組

2、引數

chdir:執行command命令前先cd到這個目錄
creates:如果這個引數對應的檔案存在,就不執行command
removes:如果這個引數對應的檔案不存在,就不執行command,與creates引數的作用相反
free_form:需要執行的指令碼(沒有真正的引數為free_form)
stdin(2.4後新增):將命令的stdin設定為指定的值
warn(1.8後新增):如果command_warnings在ansible.cfg中開啟,如果設定為,則不要警告有關此特定行no

3、示例
(1)列出指定目錄下的檔案

# 在遠端主機上建立test.sh指令碼
[
[email protected]
~]# cat /root/test.sh #!/bin/bash i=0 echo $((i+1)) [[email protected] ~]# ansible web -m command -a 'ls /root' 192.168.8.66 | SUCCESS | rc=0 >> anaconda-ks.cfg test.sh # 執行遠端主機上的test.sh指令碼 [[email protected] ~]# ansible web -m command -a 'ls /root creates=test.sh' 192.168.8.66 | SUCCESS | rc=0 >> skipped, since test.sh exists [[email protected] ~]# ansible web -m command -a 'ls /root removes=test.sh' 192.168.8.66 | SUCCESS | rc=0 >> anaconda-ks.cfg test.sh

自動化運維工具Ansible實戰(四)常用模組

說明:首先切換目錄到/root 目錄中,然後檢視test.sh是否存在,如果存在,那麼命令不會執行;如果不存在,那麼執行命令。

在這裡也可以看到,命令是必須存在的,但是沒有引數名為free_form引數。

(2)切換目錄執行命令

# 檢視遠端主機上的test.sh指令碼
[[email protected] ~]# ansible web -m command -a 'cat test.sh chdir=/root'
192.168.8.66 | SUCCESS | rc=0 >>
#!/bin/bash
i=0
echo $((i+1))

[[email protected] ~]# ansible web -m command -a 'sh test.sh chdir=/root'
192.168.8.66 | SUCCESS | rc=0 >>
1

自動化運維工具Ansible實戰(四)常用模組

(3)無法使用管道符

[[email protected] ~]# ansible web -m command -a 'ls /root | grep test.sh'
192.168.8.66 | FAILED | rc=2 >>
test.sh

/root:
anaconda-ks.cfg
test.shls: 無法訪問|: 沒有那個檔案或目錄
ls: 無法訪問grep: 沒有那個檔案或目錄non-zero return code

自動化運維工具Ansible實戰(四)常用模組

4、注意事項

  • 若要通過shell執行一個命令,比如<, >, |等,實際上我們需要shell模組
  • command模組更安全,因為它不受使用者環境的影響
  • 從版本2.4開始,executable引數被刪除。如果你需要此引數,請改用shell模組

二、raw模組

1、簡介

  • raw模組執行一個原始的命令,而不是通過模組子系統。這對我們來說很有用,而且只能在兩種情況下完成。第一種情況是在較老的(Python 2.4和之前的版本)主機上安裝python-simplejson,因為幾乎所有核心模組都需要它,作為執行模組的依賴項。另一種是對任何沒有安裝任何Python的裝置(如路由器)進行對話。在任何其他情況下,使用shell或命令模組更合適。給raw的引數直接通過配置的遠端shell執行。在可用時返回標準輸出、錯誤輸出和返回程式碼。該模組沒有更改處理程式支援
  • 用法和shell 模組一樣 ,也可以執行任意命令,就像在本機執行一樣
  • raw和command模組類似,兩個模組都是呼叫遠端主機的指令,但是raw支援管道(|)命令
  • 該模組不需要遠端系統上的python,就像指令碼模組一樣。該模組也支援Windows目標

2、引數

executable:改變用來執行命令的shell,應該是可執行檔案的絕對路徑
free_form:需要執行的指令碼(沒有真正的引數為free_form)

3、示例

[[email protected] ~]# ansible web -m raw -a "hostname"
192.168.8.55 | SUCCESS | rc=0 >>
Ansible
Shared connection to 192.168.8.55 closed.

192.168.8.66 | SUCCESS | rc=0 >>
Client
Shared connection to 192.168.8.66 closed.

[[email protected] ~]# ansible web -m raw -a "ifconfig ens33|sed -n 2p|cut -d' ' -f10"
192.168.8.55 | SUCCESS | rc=0 >>
192.168.8.55
Shared connection to 192.168.8.55 closed.

192.168.8.66 | SUCCESS | rc=0 >>
192.168.8.66
Shared connection to 192.168.8.66 closed.

自動化運維工具Ansible實戰(四)常用模組

4、注意事項

  • 如果要安全可靠地執行命令,最好使用shell或command模組來代替
  • 如果從playbook中使用raw,則可能需要使用gather_facts: no禁用事實收集

三、shell模組

1、簡介

  • shell模組讓遠端主機在shell模組下執行任何命令,從而支援shell的特性,如管道等
  • 與command模組幾乎相同,就像在本機執行一樣,但通過遠端節點上的shel(/bin/sh)執行命令

2、引數

chdir:執行shell命令前先cd到這個目錄
creates:如果這個引數對應的檔案存在,就不執行shell
removes:如果這個引數對應的檔案不存在,就不執行shell,與creates引數的作用相反
executable:改變用來執行命令的shell,應該是可執行檔案的絕對路徑
free_form:需要執行的指令碼(沒有真正的引數為free_form)
stdin(2.4後新增):將命令的stdin設定為指定的值
warn(1.8後新增):如果command_warnings在ansible.cfg中開啟,如果設定為,則不要警告有關此特定行no

3、示例
切換目錄,執行命令並保持輸出

# 在遠端主機上建立test.sh指令碼
[[email protected] ~]# cat /root/test.sh
#!/bin/bash
i=0
echo $((i+1))

# 執行遠端主機上的test.sh指令碼
[[email protected] ~]# ansible web -m shell -a "sh test.sh > result chdir=/root"
192.168.8.66 | SUCCESS | rc=0 >>

[[email protected] ~]# ansible web -m shell -a "cat result chdir=/root"
192.168.8.66 | SUCCESS | rc=0 >>
1

自動化運維工具Ansible實戰(四)常用模組

4、注意事項

  • 如果你想安全可靠的執行命令,請使用command模組,這也是編寫playbook的最佳實踐

四、script模組

1、簡介

  • script模組的作用是將Ansible服務機上的script傳送到遠端主機之後再執行,原理類似於raw模組
  • 給定的指令碼將通過遠端節點上的shell環境進行處理
  • 該模組在遠端系統上不需要python的支援
  • 該模組也支援Windows目標

2、引數

chdir(2.4後新增):執行script命令前先cd到這個目錄
creates(1.5後新增):如果這個引數對應的檔案存在,就不執行script
removes(1.5後新增):如果這個引數對應的檔案不存在,就不執行script,與creates引數的作用相反
decrypt(2.4後新增):此選項控制使用保管庫對原始檔進行自動解密
free_form:需要執行指令碼的本地檔案路徑(沒有真正的引數為free_form)

3、示例

# 在Ansible伺服器上建立一個指令碼並賦予可執行許可權
[[email protected] ~]# cat script.sh
#!/bin/bash 
a='Hello World'
echo $a
echo "這是我的Ansible伺服器指令碼"
touch test.txt

[[email protected] ~]# chmod +x script.sh

[[email protected] ~]# ansible web -m script -a "script.sh chdir=/tmp"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.8.66 closed.\r\n",
    "stdout": "Hello World\r\n這是我的Ansible伺服器指令碼\r\n",
    "stdout_lines": [
        "Hello World",
        "這是我的Ansible伺服器指令碼"
    ]
}

# 在遠端主機上建立成功test.txt
[[email protected] ~]# ansible web -m command -a "ls /tmp"
192.168.8.66 | SUCCESS | rc=0 >>
ansible_G9sPom
test.txt

自動化運維工具Ansible實戰(四)常用模組

4、注意事項

  • 當指令碼執行時,ssh連線外掛將通過-tt強制偽tty分配。偽ttys沒有stderr通道,所有stderr被髮送到標準輸出。如果需要標準輸出和標準錯誤分離,我們需要使用到copy模組

五、copy模組

1、簡介

  • copy模組是將本地或遠端機器上的檔案拷貝到遠端主機上的某個位置
  • 對於Windows目標,請改用win_copy模組

2、引數

attributes(2.3後新增):檔案或目錄應具有的屬性,該字串應該包含與lsattr顯示的順序相同順序的屬性
backup:在覆蓋之前將原檔案備份,備份檔案包含時間資訊,有兩個選項:yes|no
checksum(2.5後新增):正在傳輸的檔案的SHA1校驗和。用於確定檔案的副本是否成功
如果沒有提供,那麼將使用src檔案的本地計算校驗和
content:當用content代替src引數的時候,可以把文件的內容直接設定指定檔案的值
decrypt(2.4後新增):此選項控制使用保管庫對原始檔進行自動解密
dest:必選項。要將原始檔複製到的遠端主機的絕對路徑,如果原始檔是一個目錄,那麼該路徑也必須是個目錄
directory_mode(1.5後新增):在進行遞迴複製時,請設定目錄的模式。如果沒有設定,我們將使用系統預設值。該模式僅在新建立的目錄中設定,不會影響已存在的目錄
follow(1.8後新增):表示是否遵循目標機器中的檔案系統連結(如果存在)
force:如果遠端主機包含該檔案,但內容不同,如果設定為yes,則強制覆蓋,如果為no,則只有當遠端主機的目標位置不存在該檔案時,才複製。預設為yes
group:設定檔案或目錄的所屬組
owner:設定檔案或目錄的所屬使用者
local_follow(2.4後新增):是否遵循本地機器中的檔案系統連結(如果存在)
mode:設定檔案許可權,模式實際上是八進位制數字(如0644),少了前面的零可能會有意想不到的結果。從版本1.8開始,可以將模式指定為符號模式(例如u+rwx或u=rw,g=r,o=r)
remote_src(2.0後新增):如果是no,它將在原始主機上搜索src;如果是yes,它會去src的目標機子上搜索src。預設是no
目前remote_src不支援遞迴複製
src:將本地路徑複製到遠端主機,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞迴複製。在這種情況下,如果路徑使用"/"來結尾,則只複製目錄裡的內容,如果沒有使用"/"來結尾,則包含目錄在內的整個內容全部複製,類似於rsync
unsafe_writes(2.2後新增):通常情況下,該模組使用原子操作來防止資料損壞或從目標檔案讀取不一致,有時系統會以防止這種情況的方式進行配置或破壞
validate:複製前是否檢驗需要複製目的地的路徑
others:所有的file模組裡的選項都可以在這裡使用

3、示例
(1)backup複製前備份
複製本地檔案到遠端主機並對原檔案進行備份(第一次複製之後,對本地檔案稍作修改,第二次複製時,就能進行遠端主機的備份)

[[email protected] ~]# ansible web -m copy -a "src=/root/test.sh backup=yes dest=/root"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "checksum": "e42a8fe379671479fbdad43a3b8737e3ada2f8be",
    "dest": "/root/test.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "5636a7c4398fc86b919631387fc712e5",
    "mode": "0644",
    "owner": "root",
    "size": 30,
    "src": "/root/.ansible/tmp/ansible-tmp-1524816562.347795-100129918473420/source",
    "state": "file",
    "uid": 0
}
[[email protected] ~]# echo "echo 'Hello world'" >> test.sh 
[[email protected] ~]# ansible web -m copy -a "src=/root/test.sh backup=yes dest=/root"
192.168.8.66 | SUCCESS => {
    "backup_file": "/root/[email protected]:10:37~",     # 複製前的備份檔案路徑
    "changed": true,
    "checksum": "4d8e92c604221322f38cc04d8d6e87e84799153e",
    "dest": "/root/test.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "0418be97c2fd733a9fb2aaec5977b559",
    "mode": "0644",
    "owner": "root",
    "size": 49,
    "src": "/root/.ansible/tmp/ansible-tmp-1524816636.447237-270228680719764/source",
    "state": "file",
    "uid": 0
}
[[email protected] ~]# ansible web -m command -a "ls -l /root"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 12
-rw-------. 1 root root 1382 4月   3 22:24 anaconda-ks.cfg
-rw-r--r--  1 root root   49 4月  27 16:10 test.sh
-rw-r--r--  1 root root   30 4月  27 16:09 [email protected]:10:37~     # 複製前的備份檔案

自動化運維工具Ansible實戰(四)常用模組

(2)src和dest都是檔案

[[email protected] ~]# mkdir -p /root/dest/test
[[email protected] ~]# touch /root/dest/test.sh
[[email protected] ~]# ansible web -m copy -a "src=test.sh dest=/root/dest/test"    # dest檔案的父目錄不存在將報錯
192.168.8.66 | FAILED! => {
    "changed": false,
    "checksum": "e42a8fe379671479fbdad43a3b8737e3ada2f8be",
    "msg": "Destination directory /root/dest does not exist"
}
[[email protected] ~]# ansible web -m copy -a "src=test.sh dest=/root/dest/"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "checksum": "e42a8fe379671479fbdad43a3b8737e3ada2f8be",
    "dest": "/root/dest/test.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "5636a7c4398fc86b919631387fc712e5",
    "mode": "0644",
    "owner": "root",
    "size": 30,
    "src": "/root/.ansible/tmp/ansible-tmp-1524812376.162108-152354561278684/source",
    "state": "file",
    "uid": 0
}

自動化運維工具Ansible實戰(四)常用模組

(3)src是目錄
A、源目錄以/結尾,只拷貝了目錄下的內容

[[email protected] ~]# ls /root/test/
123.txt  test.sh
[[email protected] ~]# ansible web -m copy -a "src=/root/test/ dest=/tmp/"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "dest": "/tmp/",
    "src": "/root/test/"
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 4
-rw-r--r-- 1 root root  0 4月  27 17:04 123.txt
drwx------ 2 root root 65 4月  27 17:05 ansible_ejRWFz
-rw-r--r-- 1 root root 49 4月  27 17:04 test.sh

自動化運維工具Ansible實戰(四)常用模組

B、源目錄未以/結尾,直接將src目錄本身拷貝到目標主機

[[email protected] ~]# ls /root/test/
123.txt  test.sh
[[email protected] ~]# ansible web -m copy -a "src=/root/test dest=/tmp/"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "dest": "/tmp/",
    "src": "/root/test"
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 4
-rw-r--r-- 1 root root  0 4月  27 17:04 123.txt
drwx------ 2 root root 65 4月  27 17:07 ansible_ownGJc
drwxr-xr-x 2 root root 36 4月  27 17:07 test     # 這是一個目錄
-rw-r--r-- 1 root root 49 4月  27 17:04 test.sh

自動化運維工具Ansible實戰(四)常用模組

(4)設定檔案許可權(owner/group/mode)

[[email protected] ~]# ansible web -m copy -a "src=/root/test.sh dest=/root dest=/tmp owner=test group=test mode=0644"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "checksum": "4d8e92c604221322f38cc04d8d6e87e84799153e",
    "dest": "/tmp/test.sh",
    "gid": 1001,
    "group": "test",
    "md5sum": "0418be97c2fd733a9fb2aaec5977b559",
    "mode": "0644",
    "owner": "test",
    "size": 49,
    "src": "/root/.ansible/tmp/ansible-tmp-1524817478.2402651-108214522667207/source",
    "state": "file",
    "uid": 1001
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 4
drwx------ 2 root root 65 4月  27 16:26 ansible_zczZtp
-rw-r--r-- 1 test test 49 4月  27 16:24 test.sh

自動化運維工具Ansible實戰(四)常用模組

(5)content引數
把目錄層次設定到特定的值,並輸出到指定檔案中。

[[email protected] ~]# ansible web -m copy -a "content='root \n dest \n' dest=/root/dest"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "checksum": "87984f77e2ad345c677b5191d78d5caeb7d41316",
    "dest": "/root/dest",
    "gid": 0,
    "group": "root",
    "md5sum": "dc18f79caca390e17c89e1c850f9f8a5",
    "mode": "0644",
    "owner": "root",
    "size": 13,
    "src": "/root/.ansible/tmp/ansible-tmp-1524818107.6488795-679046311890/source",
    "state": "file",
    "uid": 0
}
[[email protected] ~]# ansible web -m command -a "cat /root/dest"
192.168.8.66 | SUCCESS | rc=0 >>
root 
 dest

自動化運維工具Ansible實戰(四)常用模組

(6)force引數
如果遠端主機包含該檔案,但內容不同,如果設定為yes,則強制覆蓋,如果為no,則只有當遠端主機的目標位置不存在該檔案時,才複製。

[[email protected] ~]# ansible web -m copy -a "src=test.sh dest=/root/xztest force=no"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "checksum": "4d8e92c604221322f38cc04d8d6e87e84799153e",
    "dest": "/root/xztest",
    "gid": 0,
    "group": "root",
    "md5sum": "0418be97c2fd733a9fb2aaec5977b559",
    "mode": "0644",
    "owner": "root",
    "size": 49,
    "src": "/root/.ansible/tmp/ansible-tmp-1524818671.0156403-161213944315961/source",
    "state": "file",
    "uid": 0
}
[[email protected] ~]# ansible web -m copy -a "src=test.sh dest=/root/xztest force=no"
192.168.8.66 | SUCCESS => {
    "changed": false,
    "dest": "/root/xztest",
    "src": "/root/test.sh"
}
[[email protected] ~]# ansible web -m command -a "ls -l /root"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 8
-rw-------. 1 root root 1382 4月   3 22:24 anaconda-ks.cfg
-rw-r--r--  1 root root   49 4月  27 16:44 xztest

自動化運維工具Ansible實戰(四)常用模組

六、file模組

1、簡介

  • file模組,設定檔案、符號連結和目錄的屬性,或刪除檔案、符號連結、目錄
  • 許多其他模組支援與file模組相同的選項(包括複製、模板和彙編)
  • 對於Windows目標,請改用win_file模組

2、引數

attributes(2.3後新增):檔案或目錄應具有的屬性。要獲得支援的標誌,請檢視目標系統上chattr的手冊頁。該字串應該包含與lsattr顯示的順序相同順序的屬性
follow(1.8後新增):是否遵循目的機器中的檔案系統連結,(如果存在)。在Ansible 2.5之前,預設是no
force:強制建立軟連結
group:設定檔案或目錄的所屬組
owner:設定檔案或目錄的所屬使用者
mode:設定檔案許可權,模式實際上是八進位制數字(如0644),少了前面的零可能會有意想不到的結果。從版本1.8開始,可以將模式指定為符號模式(例如u+rwx或u=rw,g=r,o=r)
path:定義目標檔案/目錄的路徑,也可以用dest、name代替
recurse:是否遞迴設定檔案的屬性,只對目錄有效(僅適用於state=directory)
selevel:要被連結的原始檔的路徑(僅適用於state=link)
dest:被連結到的路徑(僅適用於state=link)
src:要連結到的檔案路徑(僅適用於state=link)
state:若果是directory,所有的子目錄將被建立(如果它們不存在);若是file,檔案將不會被建立(如果檔案不存在);link表示符號連結;若是absent,目錄、檔案或連結會被遞迴刪除;touch代表生成一個空檔案;hard代表硬連結
touch:如果檔案不存在,則會建立一個新的檔案,如果檔案或目錄已存在,則更新其最後修改時間
unsafe_writes(2.2後新增):是否以不安全的方式進行,可能導致資料損壞

3、示例
(1)設定檔案許可權(owner/group/mode)

[[email protected]le ~]# ansible web -m command -a "ls -l /root/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
-rwxr-xr-x 1 root root 31 4月  28 10:41 /root/test.sh

[[email protected] ~]# ansible web -m file -a "path=/root/test.sh owner=test group=test mode=0777" 
192.168.8.66 | SUCCESS => {
    "changed": true,
    "gid": 1001,
    "group": "test",
    "mode": "0777",
    "owner": "test",
    "path": "/root/test.sh",
    "size": 31,
    "state": "file",
    "uid": 1001
}
[[email protected] ~]# ansible web -m command -a "ls -l /root/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
-rwxrwxrwx 1 test test 31 4月  28 10:41 /root/test.sh

自動化運維工具Ansible實戰(四)常用模組

(2)建立空檔案(state=touch)

[[email protected] ~]# ansible web -m file -a "path=/tmp/xz_test state=touch mode=0644"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "dest": "/tmp/xz_test",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp/xz_test"
192.168.8.66 | SUCCESS | rc=0 >>
-rw-r--r-- 1 root root 0 4月  28 10:49 /tmp/xz_test

自動化運維工具Ansible實戰(四)常用模組

(3)建立目錄(state=directory)
A、目錄是遞迴建立的

[[email protected] ~]# ansible web -m file -a "path=/tmp/test/xzxs/ state=directory mode=0755"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/tmp/test/xzxs/",
    "size": 6,
    "state": "directory",
    "uid": 0
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp/"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 0
drwx------ 2 root root 65 4月  28 10:56 ansible_iy9v52
drwxr-xr-x 3 root root 18 4月  28 10:56 test
-rw-r--r-- 1 root root  0 4月  28 10:49 xz_test

[[email protected] ~]# ansible web -m command -a "ls -l /tmp/test/"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 6 4月  28 10:56 xzxs

自動化運維工具Ansible實戰(四)常用模組

B、目標檔案不存在
state=file時會報錯,但是state=absent不會報錯,執行狀態也不會變化

[[email protected] ~]# ansible web -m file -a "path=/tmp/test/xzxs/1.txt state=file mode=0644"
192.168.8.66 | FAILED! => {
    "changed": false,
    "msg": "file (/tmp/test/xzxs/1.txt) is absent, cannot continue",
    "path": "/tmp/test/xzxs/1.txt",
    "state": "absent"
}
[[email protected] ~]# ansible web -m file -a "path=/tmp/test/xzxs/1.txt state=absent mode=0644"
192.168.8.66 | SUCCESS => {
    "changed": false,
    "path": "/tmp/test/xzxs/1.txt",
    "state": "absent"
}

自動化運維工具Ansible實戰(四)常用模組

(4)建立軟連結(state=link)

[[email protected] ~]# ansible web -m file -a "src=/etc/fstab dest=/tmp/123.txt state=link"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "dest": "/tmp/123.txt",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 10,
    "src": "/etc/fstab",
    "state": "link",
    "uid": 0
}
[[email protected] ~]# ansible web -m command -a "ls -l /tmp/"
192.168.8.66 | SUCCESS | rc=0 >>
總用量 0
lrwxrwxrwx 1 root root 10 4月  28 11:06 123.txt -> /etc/fstab   # 建立軟連結
drwx------ 2 root root 65 4月  28 11:06 ansible_pfisoW
drwxr-xr-x 3 root root 18 4月  28 10:56 test
-rw-r--r-- 1 root root  0 4月  28 10:49 xz_test

自動化運維工具Ansible實戰(四)常用模組

(5)刪除檔案、目錄或者軟連結(state=absent)

[[email protected] ~]# ansible web -m file -a "path=/tmp/test/ state=absent"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "path": "/tmp/test/",
    "state": "absent"
}
[[email protected] ~]# ansible web -m file -a "path=/tmp/xz_test state=absent"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "path": "/tmp/xz_test",
    "state": "absent"
}
[[email protected] ~]# ansible web -m file -a "path=/tmp/123.txt state=absent"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "path": "/tmp/123.txt",
    "state": "absent"
}

自動化運維工具Ansible實戰(四)常用模組

七、ping模組

1、簡介

  • ping模組用於確認和物件機器之間是否能夠ping通,正常情況會返回pong
  • ping模組在劇本中沒有任何意義,但從/usr/bin/ansible或者/ansible-2.5.0/bin/ansible可以驗證主機是否可以登入
  • 這不是ICMP ping,這只是一個簡單的測試模組,需要遠端節點上的Python
  • 對於Windows目標,請改用win_ping模組
  • 對於網路目標,請改用net_ping模組

2、引數

data:要返回的資料為ping返回值。如果此引數設定為crash,模組將導致異常

3、示例

# 預設返回是pong
[[email protected] ~]# ansible web -m ping
192.168.8.66 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

# 設定返回值是hello
[[email protected] ~]# ansible web -m ping -a "data=hello"
192.168.8.66 | SUCCESS => {
    "changed": false,
    "ping": "hello"
}

# 設定返回值是crash,模組導致異常
[[email protected] ~]# ansible web -m ping -a "data=crash"
192.168.8.66 | FAILED! => {
    "changed": false,
    "module_stderr": "Shared connection to 192.168.8.66 closed.\r\n",
    "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_oNemnu/ansible_module_ping.py\", line 84, in <module>\r\n    main()\r\n  File \"/tmp/ansible_oNemnu/ansible_module_ping.py\", line 74, in main\r\n    raise Exception(\"boom\")\r\nException: boom\r\n",
    "msg": "MODULE FAILURE",
    "rc": 1
}

自動化運維工具Ansible實戰(四)常用模組

八、service模組

1、簡介

  • service模組用於控制遠端主機的服務,說白了,就是Linux下的service命令
  • 支援的init系統包括BSD init,OpenRC,SysV,Solaris SMF,systemd,upstart
  • 對於Windows目標,請改用win_service模組

2、引數

arguments:如果開啟這個標記,backrefs會改變模組的一些操作:insertbefore和insertafter引數會被忽略。當regexp不匹配檔案中的任何行時,檔案不會做任何修改,否則 使用擴充套件的line引數 替換 最後一個匹配正則表示式的行
enabled:服務是否開機自動啟動yes|no。enabled和state至少要有一個被定義
name:必選項,服務名稱
pattern:如果通過status指令來檢視服務的狀態時,沒有響應,就會通過ps指令在程序中根據該模式進行查詢,如果匹配到,則認為該服務依然在運
runlevel:執行級別
sleep(1.3後新增):如果服務被重新啟動,則睡眠多少秒再執行停止和啟動命令
state:對當前服務執行啟動,停止、重啟、重新載入等操作(started,stopped,restarted,reloaded)
use(2.2後新增):以哪個使用者的身份執行

3、示例
(1)啟動、停止、重啟或過載服務

# 啟動(started)
[[email protected] ~]# ansible web -m service -a "name=httpd state=started"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        ……
    }
}
# 停止(stopped)
[[email protected] ~]# ansible web -m service -a "name=httpd state=stopped"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "stopped",
    "status": {
        ……
    }
}
# 重啟(restarted)
[[email protected] ~]# ansible web -m service -a "name=httpd state=restarted"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
"status": {
        ……
    }
}
# 過載(reloaded)
[[email protected] ~]# ansible web -m service -a "name=httpd state=reloaded"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
"status": {
        ……
    }
}

**(2)設定服務開機自啟動**
[[email protected] ~]# ansible web -m service -a "name=httpd enabled=yes"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "enabled": true,
    "name": "httpd",
    "status": {
        ……
    }
}

九、systemd模組

1、簡介

  • systemd模組用於控制遠端主機的systemd服務,說白了,就是Linux下的systemd命令。需要遠端主機支援systemd
  • 用法和service模組基本相同

2、引數

daemon_reload:在執行任何其他操作之前執行守護程序重新載入,以確保systemd已經讀取其他更改
enabled:服務是否開機自動啟動yes|no。enabled和state至少要有一個被定義
masked:是否將服務設定為masked狀態,被mask的服務是無法啟動的
name:必選項,服務名稱
no_block(2.3後新增):不要同步等待操作請求完成
state:對當前服務執行啟動,停止、重啟、重新載入等操作(started,stopped,restarted,reloaded)
user:使用服務的呼叫者執行systemctl,而不是系統的服務管理者

3、示例
(1)啟動、停止、重啟或過載服務

# 啟動(started)
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=started"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        ……
    }
}
# 停止(stopped)
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=stopped"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "stopped",
    "status": {
        ……
    }
}
# 重啟(restarted)
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=restarted"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        ……
    }
}
# 過載(reloaded)
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=reloaded"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        ……
    }
}

(2)設定服務masked狀態

# 先將服務停止
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=stopped"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "stopped",
    "status": {
        ……
    }
}

[[email protected] ~]# ansible web -m systemd -a "name=httpd masked=yes"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "status": {
        ……
    }
}
# 服務已無法啟動
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=started"
192.168.8.66 | FAILED! => {
    "changed": false,
    "msg": "Unable to start service httpd: Failed to start httpd.service: Unit is masked.\n"
}
# 撤銷mask
[[email protected] ~]# ansible web -m systemd -a "name=httpd masked=no"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "status": {
        ……
    }
}
# 可以啟動成功
[[email protected] ~]# ansible web -m systemd -a "name=httpd state=started"
192.168.8.66 | SUCCESS => {
    "changed": true,
    "name": "httpd",
    "state": "started",
"status": {
        ……
    }
}

十、lineinfile模組

1、簡介

  • lineinfile模組用於確保一個特定的行在一個檔案中,或使用一個正則表示式替換現有的行
  • 如果想要改變檔案中相似的多行,可以使用replace模組。如果想要插入、更新、刪除一個行塊,可以使用blockinfile模組

2、引數

attributes(2.3後增加):檔案或目錄應具有的屬性。要獲得支援的標誌,請檢視目標系統上chattr的手冊頁。該字串應該包含與lsattr顯示的順序相同順序的屬性
backrefs:如果開啟這個標記,backrefs會改變模組的一些操作:insertbefore和insertafter引數會被忽略。當regexp不匹配檔案中的任何行時,檔案不會做任何修改,否則 使用擴充套件的line引數 替換 最後一個匹配正則表示式的行
backup:用於建立一個包含時間戳資訊的備份檔案。以便在錯誤的修改了檔案的時候,能夠找回原始的檔案
create:與state=present一起使用。如果指定了這個引數,當要修改的檔案不存在的時候,會建立它。否則會報錯
firstmatch(2.5後增加):用於insertafter或insertbefore。如果設定,insertafter並inserbefore找到第一行有正則表示式匹配
group:設定檔案/目錄的所屬組
insertafter:當regexp不匹配檔案中的任何行的時候,會將新行插入到其所指定的正則表示式匹配的行中的最後一行的後面。insertafter也支援一個特殊的值:EOF(代表檔案的末尾)。若沒有匹配的行,那麼就會插入EOF
insertbefore:當regexp不匹配檔案中的任何行的時候,會將line引數所指定的行,插入到insertbefore所指定的正則表示式匹配的行中的最後一行的前面,當insertbefore所指定的正則表示式不匹配任何行時,會插入到檔案的末尾,同時insertbefore還可以是一個特殊的值:BOF(代表檔案的開始);否則,會使用line引數所指定的行替換regexp所匹配的行中的最後一行
line:要插入或者替換的行。如果設定了backrefs引數,那麼line中可以包含位置分組或命名分組,lineinfile模組會使用regexp捕獲的分組填充它們
mode:設定檔案許可權,模式實際上是八進位制數字(如0644),少了前面的零可能會有意想不到的結果。從版本1.8開始,可以將模式指定為符號模式(例如u+rwx或u=rw,g=r,o=r)
others:file模組的其他引數可以在這裡使用
owner:設定檔案或目錄的所屬使用者
path:要修改的檔案,也可以使用dest、destfile、name
regexp(1.7後增加):用於搜尋檔案中的每一行的正則表示式。對於state=present,這個正則表示式所匹配的行中的最後一行會被替換;對於state=present,會刪除所有匹配的行
state:用於設定 新增或替換一行,還是刪除行(present、absent)
unsafe_writes(2.2後增加):是否以不安全的方式進行,可能導致資料損壞
validate:複製前是否檢驗需要複製目的地的路徑

3、示例
(1)文字替換
將/etc/selinux/config檔案中所有匹配^SELINUX=正則表示式的行中的最後一行使用SELINUX=disabled替換
如果regexp不匹配檔案中的任何一行,則將line所指定的行插入到檔案的末尾

[[email protected] ~]# ansible web -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
# 檢視結果
[[email protected] ~]# ansible web -m command -a "cat /etc/selinux/config"
192.168.8.66 | SUCCESS | rc=0 >>

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled                                   # 修改成功
# SELINUXTYPE= can take one of three two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

自動化運維工具Ansible實戰(四)常用模組

(2)刪除行
將/tmp/test.sh檔案中所有匹配^pwd的行刪除

# 刪除前內容
[[email protected] ~]# ansible web -m command -a "cat /tmp/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
#!/bin/bash
echo "Hello world"
pwd
pwd1=123456789
pwd2=test
# 刪除行
[[email protected] ~]# ansible web -m lineinfile -a "path=/tmp/test.sh regexp='^pwd' state=absent"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "found": 3,
    "msg": "3 line(s) removed"
}
# 再次執行,沒有匹配
[[email protected] ~]# ansible web -m lineinfile -a "path=/tmp/test.sh regexp='^pwd' state=absent"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": false,
    "found": 0,
    "msg": ""
}
# 刪除後
[[email protected] ~]# ansible web -m command -a "cat /tmp/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
#!/bin/bash
echo "Hello world"

自動化運維工具Ansible實戰(四)常用模組

(3)替換行並設定檔案許可權

# 執行前
[[email protected] ~]# ansible web -m command -a "cat /etc/hosts"
192.168.8.66 | SUCCESS | rc=0 >>
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.8.55 Ansible
192.168.8.66 Client
# 執行中
[[email protected] ~]# ansible web -m lineinfile -a "path=/etc/hosts regexp='^127.0.0.1' line='127.0.0.1 localhost' owner=root group=root mode=0644"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
# 執行後
[[email protected] ~]# ansible web -m command -a "cat /etc/hosts"
192.168.8.66 | SUCCESS | rc=0 >>
127.0.0.1 localhost
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.8.55 Ansible
192.168.8.66 Client

自動化運維工具Ansible實戰(四)常用模組

(4)insertafter和insertbefore
當檔案中沒有匹配正則表示式^Listen80的行時,會將Listen 80插入到^#Listen所匹配的最後一行的後面

[[email protected] ~]# ansible web -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen80' insertafter='^#Listen' line='Listen 80'"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line added"
}
# insertbefore的使用方法類似
[[email protected] ~]# ansible web -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^#Listen80' insertbefore='^Listen 80' line='#Listen 80'"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line added"
}

自動化運維工具Ansible實戰(四)常用模組

(5)為檔案新增一行
直接在檔案中新增一行(如果line不存在則會插入),而不通過正則表示式進行匹配

[[email protected] ~]# ansible web -m lineinfile -a "path=/root/test.sh line='xiaozuo test'"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line added"
}
# 再次執行
[[email protected] ~]# ansible web -m lineinfile -a "path=/root/test.sh line='xiaozuo test'"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": false,
    "msg": ""
}
# 執行後的檔案
[[email protected] ~]# ansible web -m command -a "cat /root/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
#!/bin/bash
echo 'Hello world'
xiaozuo test          # 新增的行

自動化運維工具Ansible實戰(四)常用模組

(6)backrefs用法
backrefs為no時,如果沒有匹配,則新增一行line。如果匹配了,則把匹配內容替被換為line內容。
backrefs為yes時,如果沒有匹配,則檔案保持不變。如果匹配了,把匹配內容替被換為line內容。

# backrefs為yes時,匹配到了,並把匹配內容替被換為line內容
[[email protected] ~]# ansible web -m lineinfile -a "path=/root/test.sh line='xiaozuo xiansen' regexp='^xiaozuo' backrefs=yes"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
# backrefs為yes時,沒有匹配到,則檔案保持不變
[[email protected] ~]# ansible web -m lineinfile -a "path=/root/test.sh line='xiaozuo xiansen' regexp='^xiaozuo1' backrefs=yes"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": false,
    "msg": ""
}
# backrefs為no時,沒有匹配到,則新增一行line
[[email protected] ~]# ansible web -m lineinfile -a "path=/root/test.sh line='xiaozuo xiansen' regexp='^xiaozuo1' backrefs=no"
192.168.8.66 | SUCCESS => {
    "backup": "",
    "changed": true,
    "msg": "line added"
}
# 執行後的檔案
[[email protected] ~]# ansible web -m command -a "cat /root/test.sh"
192.168.8.66 | SUCCESS | rc=0 >>
#!/bin/bash
echo 'Hello world'
xiaozuo xiansen
xiaozuo xiansen
  • 自動化運維工具Ansible實戰(四)常用模組

十一、setup模組

1、簡介
setup模組被劇本自動呼叫,以收集有關可用於劇本的遠端主機的有用變數
****也可以直接通過/usr/bin/ansible或者/ansible-2.5.0/bin/ansible來檢查主機可用的變數
該模組也支援Windows目標

2、引數

fact_path(1.3後增加):用於本地(.fact)的路徑, 如果檔案不可執行,則會讀取該目錄中的檔案;(如果可執行)並將其結果新增到ansible_local的資訊中
filter:過濾串
gather_subset(2.1後增加):將收集的其他資訊限制在給定的子集中。可能的值:all,min,hardware,network,virtual,ohai和facter可以指定一個值列表來指定一個更大的子集。值也可以與初始值一起使用,!以指定不應收集該特定子集(如:!hardware, !network, !virtual, !ohai, !facter. if !all)。為避免收集最小子集,請指定!all和!min子集。要僅收集特定資訊,請使用!all、!min,並指定特定的資訊子集
gather_timeout(2.2後增加):設定單個資訊收集的預設超時值,以秒為單位

3、示例
(1)收集fact並進行儲存

# 將所有主機的資訊輸入到/tmp/facts目錄下
[[email protected] ~]# ansible web -m setup --tree /tmp/facts
192.168.8.66 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.8.66"
            ……
        ]
        "module_setup": true
    },
    "changed": false
}
[[email protected] ~]# ls /tmp/facts/
192.168.8.66

(2)收集記憶體資訊

[[email protected] ~]# ansible web -m setup -a "filter=ansible_*_mb"
192.168.8.66 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 119,
        "ansible_memory_mb": {
            "nocache": {
                "free": 484,
                "used": 2524
            },
            "real": {
                "free": 119,
                "total": 3008,
                "used": 2889
            },
            "swap": {
                "cached": 43,
                "free": 1980,
                "total": 2047,
                "used": 67
            }
        },
        "ansible_memtotal_mb": 3008,
        "ansible_swapfree_mb": 1980,
        "ansible_swaptotal_mb": 2047
    },
    "changed": false
}

自動化運維工具Ansible實戰(四)常用模組

(3)收集主機網絡卡資訊

[[email protected] ~]# ansible web -m setup -a "filter=ansible_ens33"
192.168.8.66 | SUCCESS => {