ansible環境部署及經常使用模塊總結 - 運維筆記

 

一.  Ansible 介紹
Ansible是一個配置管理系統configuration management system, python 語言是運維人員必須會的語言, ansible 是一個基於python 開發的自動化運維工具, 其功能實現基於ssh遠程鏈接服務, ansible 能夠實現批量系統配置,批量軟件部署,批量文件拷貝,批量運行命令等功能, 除了ansible以外,還有saltstack 等批量管理軟件.html

Ansible能作什麼? 
ansible能夠幫助運維人員完成一些批量任務,或者完成一些須要常常重複的工做。
好比:同時在100臺服務器上安裝nginx服務,並在安裝後啓動服務。
好比:將某個文件一次性拷貝到100臺服務器上。
好比:每當有新服務器加入工做環境時,運維人員都要爲新服務器部署某個服務,也就是說運維人員須要常常重複的完成相同的工做。
這些場景中運維人員均可以使用到ansible。node

Ansible軟件特色?
ansible不須要單獨安裝客戶端,SSH至關於ansible客戶端。
ansible不須要啓動任何服務,僅需安裝對應工具便可。
ansible依賴大量的python模塊來實現批量管理。
ansible配置文件/etc/ansible/ansible.cfgpython

Ansible是一種agentless(基於ssh),可實現批量配置、命令執行和控制,基於Python實現的自動化運維工具。Ansible的兩個特性:
- 模塊化經過調用相關模塊,完成指定任務,且支持任何語言編寫的自定義模塊;
- playbook劇本,可根據須要一次執行完劇本中的全部任務或某些任務;linux

Ansible 架構nginx

- 鏈接插件(connectior plugins) 用於鏈接主機 用來鏈接被管理端。
- 核心模塊(core modules) 鏈接主機實現操做, 它依賴於具體的模塊來作具體的事情。
- 自定義模塊(custom modules) 根據本身的需求編寫具體的模塊。
- 插件(plugins) 完成模塊功能的補充。
- 劇本(playbooks)ansible的配置文件,將多個任務定義在劇本中,由ansible自動執行。
- 主機清單(host inventory)定義ansible須要操做主機的範圍。git

最重要的一點: ansible是模塊化的, 它全部的操做都依賴於模塊, 不須要單獨安裝客戶端(no agents),基於系統自帶的sshd服務,sshd就至關於ansible的客戶端, 不須要服務端(no sever),須要依靠大量的模塊實現批量管理, 配置文件 /etc/ansible/ansible.cfg (前期不用配置)。github

二.  Ansible命令使用
語法格式:
ansible <pattern_goes_here> -m <module_name> -a <arguments>
也就是:
ansible  匹配模式   -m  模塊  -a  '須要執行的內容'web

解釋說明:
匹配模式:即哪些機器生效 (能夠是某一臺, 或某一組, 或all) , 默認模塊爲command , 執行常規的shell命令. 正則表達式

-m name, --module-name=name:  指定執行使用的模塊。
-u username, --user=username:  指定遠程主機以username運行命令。
-s, --sudo:  至關於linux系統下的sudo命令。
-usudo_username, --sudo-user=sudo_username:  使用sudo, 至關於linux系統下的sudo命令。
-C, --check:  只檢查不實際執行。
-e, 即extra_vars:  引用外部參數。
-i, 即inventory:  指定倉庫列表, 默認/etc/ansible/hosts
--list-host:  列出執行主機列。 docker

三. Ansible經常使用模塊
ping 模塊: 檢查指定節點機器是否還能連通,用法很簡單,不涉及參數,主機若是在線,則回覆pong 。
raw 模塊: 執行原始的命令,而不是經過模塊子系統。
yum 模塊: RedHat和CentOS的軟件包安裝和管理工具。
apt 模塊: Ubuntu/Debian的軟件包安裝和管理工具。
pip 模塊 : 用於管理Python庫依賴項,爲了使用pip模塊,必須提供參數name或者requirements。
synchronize 模塊: 使用rsync同步文件,將主控方目錄推送到指定節點的目錄下。
template 模塊: 基於模板方式生成一個文件複製到遠程主機(template使用Jinjia2格式做爲文件模版,進行文檔內變量的替換的模塊。
copy 模塊: 在遠程主機執行復制操做文件。
user 模塊 與 group 模塊: user模塊是請求的是useradd, userdel, usermod三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令。
service 模塊: 用於管理遠程主機的服務。
get_url 模塊: 該模塊主要用於從http、ftp、https服務器上下載文件(相似於wget)。
fetch 模塊: 它用於從遠程機器獲取文件,並將其本地存儲在由主機名組織的文件樹中。
file 模塊: 主要用於遠程主機上的文件操做。
lineinfile 模塊: 遠程主機上的文件編輯模塊
unarchive模塊: 用於解壓文件。
command模塊 和 shell模塊: 用於在各被管理節點運行指定的命令. shell和command的區別:shell模塊能夠特殊字符,而command是不支持
hostname模塊: 修改遠程主機名的模塊。
script模塊: 在遠程主機上執行主控端的腳本,至關於scp+shell組合。
stat模塊: 獲取遠程文件的狀態信息,包括atime,ctime,mtime,md5,uid,gid等信息。
cron模塊: 遠程主機crontab配置。
mount模塊: 掛載文件系統。
find模塊: 幫助在被管理主機中查找符合條件的文件,就像 find 命令同樣。
selinux模塊:遠程管理受控節點的selinux的模塊

四.  Ansible 自動化運維操做記錄

1) 實驗環境準備

ip地址               主機名                 角色           系統版本 
172.16.60.211       ansible-server        主控節點        centos7.5
172.16.60.212       ansible-node01        受控節點1       centos7.5
172.16.60.213       ansible-node02        受控節點2       centos7.5
172.16.60.214       ansible-node03        受控節點3       centos7.5

四個節點各自設置主機名
[root@ansible-server ~]# hostnamectl set-hostname ansible-server
[root@ansible-node01 ~]# hostnamectl set-hostname ansible-node01
[root@ansible-node02 ~]# hostnamectl set-hostname ansible-node02
[root@ansible-node03 ~]# hostnamectl set-hostname ansible-node03

設置主控節點到受控節點的ssh無密碼信任關係 (ansible應用環境下, 主控節點必需要設置ssh無密碼跳轉到受控節點的信任關係)

添加主控節點到受控節點的認證! 首先主控節點必需要生成公私密鑰對, 不然不能進行免密信任關係設置!!   
[root@ansible-server ~]# ssh-keygen -t rsa                                 #一直回車便可
[root@ansible-server ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub -p22 root@172.16.60.212      #回車, 輸入遠程登陸的密碼便可
[root@ansible-server ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub -p22 root@172.16.60.213
[root@ansible-server ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub -p22 root@172.16.60.214

若是受控節點數量比較多的話, 可使用expect進行遠程ssh鏈接的免密信任關係, 具體可參考: https://www.cnblogs.com/kevingrace/p/5900303.html

2) Ansible安裝部署

Ansible有兩種安裝方式: yum 和 pip 安裝方式
 
Ansible在epel的yum中有提供,因此配置好epel源,直接使用yum命令安裝便可.
CentOS系統, 可使用默認的yum源直接安裝ansible
 
[root@ansible-server ~]# yum install -y ansible
 
配置文件目錄:/etc/ansible/
執行文件目錄:/usr/bin/
Lib庫依賴目錄:/usr/lib/pythonX.X/site-packages/ansible/
Help文檔目錄:/usr/share/doc/ansible-X.X.X/
Man文檔目錄:/usr/share/man/man1/
 
================================================
pip安裝方式
# yum -y install python-pip python-devel
# pip install ansible
================================================
 
ansible程序文件
/usr/bin/ansible:  命令行工具
ansible命令通用格式: ansible <host-pattern> [options] [-m module_name] [-a args]
/usr/bin/ansible-doc: 幫助文檔
/usr/bin/ansible-playbook: 劇本執行工具
/etc/ansible/ansible.cfg: 主配置文件
/etc/ansible/hosts: 管理的主機清單
/etc/ansible/roles: 角色存放處
 
查看ansible命令幫助
[root@ansible-server ~]# ansible -h
 
查看支持的模塊
[root@ansible-server ~]# ansible-doc -l
[root@ansible-server ~]# ansible-doc -l|grep copy    #查看copy模塊
 
查看ansible的支持的模塊個數
[root@ansible-server ~]# ansible-doc -l |wc -l
2080
 
查看ansible版本
[root@ansible-server ~]# ansible --version
ansible 2.7.8
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

3) Ansible清單管理
inventory文件一般用於定義要管理主機的認證信息, 例如ssh登陸用戶名、密碼以及key相關信息。默認inventory文件爲/etc/hostsweb-nodes, ansible模塊操做命令中能夠省去默認inventory (便可以省去"-i /etc/hostsweb-nodes"), 若是inventory文件定義了其餘路徑,則在ansible模塊操做命令中不能省去, 要加上"-i inventory路徑".

如何配置Inventory文件?
主控節點:
-  支持主機名通配以及正則表達式,例如web[1:3].oldboy.com;
-  支持基於非標準的ssh端口,例如web1.oldboy.com:6666;
-  支持指定變量,可對個別主機的特殊配置,如登錄用戶,密碼等;

受控節點
-  支持嵌套組,例如[game:children],那麼在game模塊下面的組都會被game所包含;
-  支持指定變量,例如[game:vars]在下面指定變量;

ansible的inventory清單文件(/etc/ansible/hosts)中配置說明:
[ ] 中的名字表明組名
主機(hosts)部分可使用域名、主機名、IP地址表示, 通常此類配置中多使用IP地址;
組名下的主機地址就是ansible能夠管理的地址;

下面是/etc/ansible/hosts 文件中清單的配置示例:

[root@ansible-server ~]# cd /etc/ansible/
[root@ansible-server ansible]# cp hosts hosts.bak
[root@ansible-server ansible]# vim hosts                      #以下, 這裏設置了兩組管理清單
...........
#可使用受控節點的ip, 下面表示test-hosts組包括172.16.60.212, 172,16,60,213, 172.16.60.214 (若是ssh端口不是22, 好比是22222, 能夠配置爲"172.16.60.212:22222")
[test-hosts]
172.16.60.2[12:14]
  
#也可使用受控節點的主機名, 前提是主控節點要能跟受控節點的主機名正常通訊
[web-nodes]
172.16.60.21[2:3]
#ansible-node03                #前提是要能ping通這個主機名, 即作好/etc/hosts主機名映射
  
簡單測試,可設置是否生效
查看ansible清單裏全部節點的uptime狀況
[root@ansible-server ansible]# ansible all -m command -a "uptime"
172.16.60.213 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 22:19,  3 users,  load average: 0.00, 0.01, 0.05
  
172.16.60.214 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 22:19,  3 users,  load average: 0.01, 0.03, 0.05
  
172.16.60.212 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 23:30,  3 users,  load average: 0.00, 0.01, 0.05
  
查看ansible清單裏test-hosts組的節點的主機名
[root@ansible-server ansible]# ansible test-hosts -m command -a "hostname"  
172.16.60.213 | CHANGED | rc=0 >>
ansible-node02
  
172.16.60.214 | CHANGED | rc=0 >>
ansible-node03
  
172.16.60.212 | CHANGED | rc=0 >>
ansible-node01
  
查看ansible清單裏web-nodes組的節點的系統時間
[root@ansible-server ansible]# ansible web-nodes -m command -a "date"        
172.16.60.213 | CHANGED | rc=0 >>
Sun Mar 17 01:51:02 CST 2019
  
172.16.60.212 | CHANGED | rc=0 >>
Sun Mar 17 01:51:02 CST 2019
 
[root@ansible-server ansible]# ansible test-hosts --list-hosts
  hosts (3):
    172.16.60.212
    172.16.60.213
    172.16.60.214
[root@ansible-server ansible]# ansible web-nodes --list-hosts
  hosts (2):
    172.16.60.212
    172.16.60.213
 
[root@ansible-server ansible]# ansible -i /etc/ansible/hosts web-nodes -m command -a "cat /etc/redhat-release"
172.16.60.213 | CHANGED | rc=0 >>
CentOS Linux release 7.5.1804 (Core)
 
172.16.60.212 | CHANGED | rc=0 >>
CentOS Linux release 7.5.1804 (Core)

Ansible內置變量

驗證ansible, ansible是經過ssh端口探測通訊

[root@ansible-server ~]# cd /etc/ansible/
[root@ansible-server ansible]# cp hosts hosts.bak
[root@ansible-server ansible]# vim hosts                      #以下, 這裏設置了兩組管理清單
...........
#可使用受控節點的ip
[test-hosts]
172.16.60.212
172.16.60.213
172.16.60.214
 
#也可使用受控節點的主機名, 前提是主控節點要能跟受控節點的主機名正常通訊
[web-nodes]
172.16.60.212
172.16.60.213
#ansible-node03                #前提是要能ping通這個主機名, 即作好/etc/hosts主機名映射
 
簡單測試,可設置是否生效
查看ansible清單裏全部節點的uptime狀況
[root@ansible-server ansible]# ansible all -m command -a "uptime"
172.16.60.213 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 22:19,  3 users,  load average: 0.00, 0.01, 0.05
 
172.16.60.214 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 22:19,  3 users,  load average: 0.01, 0.03, 0.05
 
172.16.60.212 | CHANGED | rc=0 >>
 01:43:15 up 13 days, 23:30,  3 users,  load average: 0.00, 0.01, 0.05
 
查看ansible清單裏test-hosts組的節點的主機名
[root@ansible-server ansible]# ansible test-hosts -m command -a "hostname"   
172.16.60.213 | CHANGED | rc=0 >>
ansible-node02
 
172.16.60.214 | CHANGED | rc=0 >>
ansible-node03
 
172.16.60.212 | CHANGED | rc=0 >>
ansible-node01
 
查看ansible清單裏web-nodes組的節點的系統時間
[root@ansible-server ansible]# ansible web-nodes -m command -a "date"         
172.16.60.213 | CHANGED | rc=0 >>
Sun Mar 17 01:51:02 CST 2019
 
172.16.60.212 | CHANGED | rc=0 >>
Sun Mar 17 01:51:02 CST 2019

[root@ansible-server ansible]# ansible test-hosts --list-hosts
  hosts (3):
    172.16.60.212
    172.16.60.213
    172.16.60.214
[root@ansible-server ansible]# ansible web-nodes --list-hosts 
  hosts (2):
    172.16.60.212
    172.16.60.213

[root@ansible-server ansible]# ansible -i /etc/ansible/hosts web-nodes -m command -a "cat /etc/redhat-release" 
172.16.60.213 | CHANGED | rc=0 >>
CentOS Linux release 7.5.1804 (Core) 

172.16.60.212 | CHANGED | rc=0 >>
CentOS Linux release 7.5.1804 (Core)

4) Ansible 經常使用模塊

1.  ping模塊
檢查指定節點機器是否還能連通,用法很簡單,不涉及參數.  主機若是在線,則回覆pong. 測試連通性的模塊.

[root@ansible-server ~]# ansible web-nodes -m ping
172.16.60.213 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
172.16.60.212 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m ping
172.16.60.214 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
172.16.60.213 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
172.16.60.212 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

能夠得到該模塊的說明
[root@ansible-server ~]# ansible-doc -v ping

2.  raw模塊
執行原始的命令,而不是經過模塊子系統。在任何狀況下,使用shell或command命令模塊也是合適的。給定原始的參數直接經過配置的遠程shell運行。可返回標準輸出、錯誤輸出和返回代碼。此模塊沒有變動處理程序支持。 這個模塊不須要遠程系統上的Python,就像腳本模塊同樣。此模塊也支持Windows目標。raw, shell, command三個模塊都能調用對象機器上的某條指令或者某個可執行文件。raw和shell模塊很像, 都支持管道; command模塊不支持管道.

注意下三者之間的微妙區別, 以下會發現raw模塊執行的是系統原始命令, 執行後會主動關閉到被控制節點的鏈接!
[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m raw -a "hostname"
172.16.60.212 | CHANGED | rc=0 >>
ansible-node01
Shared connection to 172.16.60.212 closed.

172.16.60.213 | CHANGED | rc=0 >>
ansible-node02
Shared connection to 172.16.60.213 closed.

172.16.60.214 | CHANGED | rc=0 >>
ansible-node03
Shared connection to 172.16.60.214 closed.

[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m shell -a "hostname"   
172.16.60.214 | CHANGED | rc=0 >>
ansible-node03

172.16.60.213 | CHANGED | rc=0 >>
ansible-node02

172.16.60.212 | CHANGED | rc=0 >>
ansible-node01

[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m command -a "hostname"               
172.16.60.214 | CHANGED | rc=0 >>
ansible-node03

172.16.60.213 | CHANGED | rc=0 >>
ansible-node02

172.16.60.212 | CHANGED | rc=0 >>
ansible-node01

raw和shell模塊支持管道, command模塊不支持管道
[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m raw -a "cat /etc/passwd|grep kevin"
172.16.60.213 | CHANGED | rc=0 >>
kevin:x:1001:1001::/home/kevin:/bin/bash
Shared connection to 172.16.60.213 closed.

172.16.60.212 | CHANGED | rc=0 >>
kevin:x:1003:1003::/home/kevin:/bin/bash
Shared connection to 172.16.60.212 closed.

172.16.60.214 | CHANGED | rc=0 >>
kevin:x:1000:1000::/home/kevin:/bin/bash
Shared connection to 172.16.60.214 closed.

[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m shell -a "cat /etc/passwd|grep kevin"   
172.16.60.213 | CHANGED | rc=0 >>
kevin:x:1001:1001::/home/kevin:/bin/bash

172.16.60.214 | CHANGED | rc=0 >>
kevin:x:1000:1000::/home/kevin:/bin/bash

172.16.60.212 | CHANGED | rc=0 >>
kevin:x:1003:1003::/home/kevin:/bin/bash

[root@ansible-server ~]# ansible -i /etc/ansible/hosts all -m command -a "cat /etc/passwd|grep kevin"     
172.16.60.213 | FAILED | rc=1 >>
cat: /etc/passwd|grep: No such file or directory
cat: kevin: No such file or directorynon-zero return code

172.16.60.212 | FAILED | rc=1 >>
cat: /etc/passwd|grep: No such file or directory
cat: kevin: No such file or directorynon-zero return code

172.16.60.214 | FAILED | rc=1 >>
cat: /etc/passwd|grep: No such file or directory
cat: kevin: No such file or directorynon-zero return code

3.  yum模塊
這個模塊是RedHat 和 CentOS做爲遠端受控節點OS的時候,用的最多的模塊, 是RedHat / CentOS包管理工具的模塊, 使用`yum’軟件包管理器管理軟件包,其選項有:
config_file:yum的配置文件 (optional)
disable_gpg_check:關閉gpg_check (optional)
disablerepo:不啓用某個源 (optional)
enablerepo:啓用某個源(optional)
name要進行操做的軟件包的名字,默認最新的程序包,指明要安裝的程序包,能夠帶上版本號,也能夠傳遞一個url或者一個本地的rpm包的路徑
state:表示是安裝仍是卸載的狀態, 其中present、installed、latest 表示安裝,  absent 、removed表示卸載刪除;  present默認狀態, laster表示安裝最新版本.

舒適提示:
要確保受控節點的python版本對應正確, 不然執行下面命令會報錯 (下面報錯說明受控節點須要python2版本, 而當前是python3):
"msg": "The Python 2 bindings for rpm are needed for this module. If you require Python 3 support use the `dnf` Ansible module instead.. 
The Python 2 yum module is needed for this module. If you require Python 3 support use the `dnf` Ansible module instead."

安裝httpd
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=latest' 
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=present'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=installed'

[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name="@Development tools" state=present'

卸載httpd
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=absent' 
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=removed' 

4.  apt模塊
這個模塊是ubuntu做爲遠端受控節點OS的時候,用的最多的模塊。Apt是Ubuntu/Debian的包管理工具。
deb: 用於安裝遠程機器上的.deb後綴的軟件包(optional)
install_recommends: 這個參數能夠控制遠程電腦上是否只是下載軟件包,仍是下載後安裝,默認參數爲true,設置爲false的時候只下載軟件包,不安裝
update_cache: 當這個參數爲yes的時候等於apt-get update(optional)
name: apt要下載的軟件包名字,支持name=git=1.6 這種制定版本的模式
state: 狀態(present,absent,latest),表示是安裝仍是卸載. 其中present、installed、latest 表示安裝, absent 、removed表示卸載刪除; present默認狀態, laster表示安裝最新版本.

在安裝foo軟件包前更新而後安裝foo
# ansible web-nodes -m apt -a 'name=foo update_cache=yes'

移除foo軟件包
# ansible web-nodes -m apt -a 'name=foo state=absent'

安裝foo軟件包
# ansible web-nodes -m apt -a 'name=foo state=present'

安裝foo 1.0軟件包
# ansible web-nodes -m apt -a 'name=foo=1.00 state=present'

安裝nginx最新的名字爲squeeze-backport發佈包,而且安裝前執行更新
# ansible web-nodes -m apt -a 'name=nginx state=latest default_release=squeeze-backports update_cache=yes'

只下載openjdk-6-jdk最新的軟件包,不安裝
# ansible web-nodes -m apt -a 'name=openjdk-6-jdk state=latest install_recommends=no'

安裝全部軟件包到最新版本
# ansible web-nodes -m apt -a 'upgrade=dist'

更新apt-get的list
# ansible web-nodes -m apt -a 'update_cache=yes'

3600秒後中止update_cache
# ansible web-nodes -m apt -a 'update_cache=yes cache_valid_time=3600'

安裝遠程節點上的/tmp/mypackage.deb軟件包
# ansible web-nodes -m apt -a 'deb=/tmp/mypackage.deb'

5.  pip 模塊
用於管理Python庫依賴項,爲了使用pip模塊,必須提供參數name或者requirements
chdir: 執行pip命令前cd進入的目錄
name:要安裝的Python庫的名稱或遠程包的URL。
requirements:一個pip requirements.txt文件的路徑,它應該是遠程系統的本地文件,若是使用chdir選項,則能夠將文件指定爲相對路徑。
version:指定的Python庫的安裝版本。
extra_args:額外的參數傳遞給pip (後面使用雙引號)。
executable:顯式可執行文件或可執行文件的路徑名,用於爲系統中安裝的特定版本的Python運行pip。 例如pip-3.3,若是系統中安裝了Python 2.7和3.3,而且想要爲Python 3.3安裝運行pip。 它不能與「virtualenv」參數一塊兒指定(在2.1中添加)。 默認狀況下,它將採用適用於python解釋器的版本。 pip3在python 3上,pip2或pip在python 2上。
virtualenv:要安裝到的virtualenv目錄的可選路徑。 它不能與’executable’參數一塊兒指定(在2.1中添加)。 若是virtualenv不存在,則將在安裝軟件包以前建立它。 可選的virtualenv_site_packages,virtualenv_command和virtualenv_python選項會影響virtualenv的建立。
virtualenv_command:用於建立虛擬環境的命令或路徑名。 例如pyvenv,virtualenv,virtualenv2,~/bin /virtualenv,/usr/local/bin/virtualenv。
virtualenv_python:用於建立虛擬環境的Python可執行文件。 例如python3.5,python2.7。 未指定時,將使用用於運行ansible模塊的Python版本。 當virtualenv_command使用pyvenv或-m venv模塊時,不該使用此參數。
state:狀態(present,absent,latest, forcereinstall),表示是安裝仍是卸載的狀態. 其中present表示默認安裝; lastest表示最新版本安裝; absent表示卸載和刪除; forcereinstall表示強制從新安裝, "forcereinstall"選項僅適用於可ansible 2.1及更高版本.

安裝bottle python包
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle' 
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle state=present'          #默認的present狀態能夠省略不寫

卸載bottle python包
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle state=absent'

在0.4.6版安裝bottle python包
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle version=0.4.6 state=present'

使用遠程協議(bzr +,hg +,git +,svn +)安裝MyApp。 沒必要在extra_args中提供'-e'選項。
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=svn+http://myrepo/svn/MyApp#egg=MyApp'

使用遠程協議(bzr +,hg +,git +)安裝MyApp。
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=git+http://myrepo/app/MyApp'

從本地壓縮包安裝MyApp
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=file:///path/to/MyApp.tar.gz'

將bottle安裝到指定的virtualenv中,繼承全局安裝的模塊
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle virtualenv=/my_app/venv virtualenv_site_packages=yes'

使用Python 2.7將bottle安裝到指定的virtualenv中
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle virtualenv=/my_app/venv virtualenv_command=virtualenv-2.7'

在用戶主目錄中安裝bottle (extra_args後面使用雙引號)
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle extra_args="--user"'  

安裝指定的python requirements
[root@ansible-server ~]# ansible web-nodes -m pip -a 'requirements=/my_app/requirements.txt'

在指定的virtualenv中安裝指定的python requirements
[root@ansible-server ~]# ansible web-nodes -m pip -a 'requirements=/my_app/requirements.txt virtualenv=/my_app/venv'

安裝指定的python requirements和自定義pip源URL
[root@ansible-server ~]# ansible web-nodes -m pip -a 'requirements=/my_app/requirements.txt extra_args="-i https://example.com/pypi/simple"'

專門爲Python 3.3安裝bottle,使用'pip-3.3'可執行文件
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle executable=pip-3.3' 

安裝 bottle,若是已安裝,強制從新安裝
[root@ansible-server ~]# ansible web-nodes -m pip -a 'name=bottle state=forcereinstall' 

6.  synchronize 模塊
這個模塊是使用rsync同步文件,將主控方目錄推送到指定受控節點的目錄下。其參數以下:
delete: 刪除不存在的文件,delete=yes 使兩邊的內容同樣(即以推送方爲主),默認no
src: 要同步到目的地的源主機上的路徑; 路徑能夠是絕對的或相對的。若是路徑使用」/」來結尾,則只複製目錄裏的內容,若是沒有使用」/」來結尾,則包含目錄在內的整個內容所有複製
dest:目的地主機上將與源同步的路徑; 路徑能夠是絕對的或相對的。
dest_port:默認目錄主機上的端口 ,默認是22,走的ssh協議。
mode: push或pull,默認push,通常用於從本機向遠程主機上傳文件,pull 模式用於從遠程主機上取文件
rsync_opts:經過傳遞數組來指定其餘rsync選項。

將主控節點上/data/kevin目錄同步到受控節點的/home目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin dest=/home'

將主控節點上/data/kevin/test.file文件同步到受控節點的/opt目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/opt'

將主控節點上/data/kevin/test.file文件同步到受控節點的/root/bobo.file文件
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/root/bobo.file'

將主控節點上/opt/同步到受控節點的/opt/目錄, 使受控節點保持和主控節點的opt目錄一致, 不同的就刪除! 默認delete=no
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt/ dest=/opt/ delete=yes'

注意命令中要加"/", 若是不加"/", 則主控節點的opt目錄就同步到受控節點的/opt目錄下即, 即/opt/opt
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt dest=/opt delete=yes'  

將主控節點上/data/kevin目錄同步到受控節點的/mnt/www目錄下. 可是bobo目錄排除在外!  rsync_opts能夠進行屢次傳遞.
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo"'

強制兩邊同步保持一致! 跟主控節點源目錄保持一致!
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo" delete=yes'

從遠程受控節點上將/usr/local/src/grace.file文件拉取到主控節點的/root目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/usr/local/src/grace.file dest=/root/ rsync_opts="-avpgolr" mode=pull '

synchronize 模塊相比copy模塊來講, 同步速度增長不少.

7.  template 模塊
基於模板方式生成一個文件複製到遠程主機(template使用Jinjia2格式做爲文件模版,進行文檔內變量的替換的模塊。它的每次使用都會被ansible標記爲」changed」狀態。)
backup: 若是原目標文件存在,則先備份目標文件
src: 在ansible控制器上的Jinja2格式化模板的路徑。 這能夠是相對或絕對的路徑。
dest: 將模板渲染到遠程機器上的位置。
force: 是否強制覆蓋,默認爲yes
owner: 目標文件屬主
group: 目標文件屬組
mode: 目標文件的權限模式,模式能夠被指定爲符號模式(例如,u + rwx或u = rw,g = r,o = r)

[root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel  mode=0644" 

一樣的例子,但使用等效於0644的符號模式
[root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r""

具體用法, 可參考playbook劇本寫法.

8.  copy 模塊
把主控節點本地的文件上傳同步到遠程受控節點上, 該模塊不支持從遠程受控節點拉取文件到主控節點上。 參數選項以下:
src:指定源文件路徑,能夠是相對路徑,也能夠是絕對路徑,能夠是目錄(並不是是必須的,可使用content,直接生成文件內容). src便是要複製到遠程主機的文件在本地的地址,能夠是絕對路徑,也能夠是相對路徑。若是路徑是一個目錄,它將遞歸複製。在這種狀況下,若是路徑使用」/」來結尾,則只複製目錄裏的內容,若是沒有使用」/」來結尾,則包含目錄在內的整個內容所有複製,相似於rsync。
dest:指定目標文件路徑,只能是絕對路徑,若是src是目錄,此項必須是目錄. 這個是必選項!
owner:指定屬主;
group:指定屬組;
mode:指定權限,能夠以數字指定好比0644;
content:代替src,直接往dest文件中寫內容,能夠引用變量,也能夠直接使用inventory中的主機變量. 寫後會覆蓋原文件內容!
backup:在覆蓋以前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no
force: 若是目標主機包含該文件,但內容不一樣,若是設置爲yes,則強制覆蓋,若是爲no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲yes ;
directory_mode:遞歸的設定目錄的權限,默認爲系統默認權限;
others:全部的file模塊裏的選項均可以在這裏使用;

特別注意:  src和content不能同時使用!!!!

[root@ansible-server ~]# ansible web-nodes -m copy -a 'src=/data/kevin/ dest=/mnt/www/ backup=yes'

[root@ansible-server ~]# ansible web-nodes -m copy -a 'src=/etc/hosts dest=/mnt/www/ owner=root group=root mode=0644'

[root@ansible-server ~]# ansible web-nodes -m copy -a 'src=/etc/hosts dest=/mnt/www/ owner=root group=root mode="u=rw,g=r,o=r"'

向遠程受控節點的/mnt/www/test.file文件寫入內容, 把原內容覆蓋掉
[root@ansible-server ~]# ansible web-nodes -m copy -a 'content="\nMy age is 26" dest=/mnt/www/test.file'

9.  user 模塊 與 group 模塊
user模塊是請求的是useradd, userdel, usermod三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令

user模塊
home: 指定用戶的家目錄, 須要與createhome配合使用。
groups: 指定用戶的屬組。
uid: 指定用的uid。
password: 設定用戶密碼, password參數須要接受md5加密後的值. 特別注意: 指定password參數時, 不能使用明文密碼, 由於後面這一串密碼會被直接傳送到被管理主機的/etc/shadow文件中, 因此須要先將密碼字符串進行加密處理, 而後將獲得的字符串放到password中便可。
name: 指定用戶名。
system: 是否爲系統用戶。 表示默認建立爲普通用戶, 而非系統用戶, 指定是用yes. 也就是說yes是默認建立爲普通用戶, 而非系統用戶;
update_password: 修改用戶密碼, 其中always: 新密碼和舊密碼不一樣時進行修改; on_create: 爲新建立的用戶指定密碼.
createhome: 建立家目錄, 其中yes表示默認項, 即建立用戶默認是有家目錄的; no表示建立用戶時不建立家目錄.
remove: 其中yes是刪除用戶家目錄, 須要指定此參數; no是默認項, 刪除用戶時默認不刪除用戶的家目錄. 當state=absent時, remove=yes則表示連同家目錄一塊兒刪除, 等價於userdel -r
state: 用戶狀態是建立仍是刪除. (present, absent) ;默認爲present; 其中present表示添加用戶; absent表示刪除用戶
shell: 指定用戶的shell環境。
generate_ssh_key: 是否爲相關用戶生成SSH密鑰。 這不會覆蓋現有的SSH密鑰。
ssh_key_bits: 可選擇指定要建立的SSH密鑰中的位數。
ssh_key_passphrase: 設置SSH密鑰的密碼。 若是沒有提供密碼, SSH密鑰將默認沒有密碼。
ssh_key_file: 指定SSH密鑰文件名(可選). 若是這是一個相對的文件名, 那麼它將是相對於用戶的主目錄。
ssh_key_type: 指定要生成的SSH密鑰的類型(可選). 可用的SSH密鑰類型將取決於目標主機上的實現。

使用bash shell添加用戶haha,將組"管理員"和"開發人員"附加到用戶組
[root@ansible-server ~]# ansible web-nodes -m user -a "name=haha shell=/bin/bash groups=admins,developers append=yes"
 
增長用戶anhui (先對密碼作明文到密文的處理)
[root@ansible-server ~]# echo "anhui@123" | openssl passwd -1 -stdin
$1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui system=yes password=$1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1 state=present'
 
刪除用戶anhui
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui remove=yes state=absent'  
 
更新用戶kevin的密碼 (先對新密碼kevin@bj123作明文到密文的處理)
[root@ansible-server ~]# echo "kevin@bj123"| openssl passwd -1 -stdin  
$1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=kevin update_password=always password=$1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/'
 
在~/.ssh/id_rsa中爲用戶bobo建立一個2048位的SSH密鑰
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=bobo generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa'

[root@ansible-server ~]# ansible web-nodes -m group -a "name=yang gid=888"
[root@ansible-server ~]# ansible web-nodes -m user -a "name=yang uid=888 group=888 shell=/sbin/nologin create_home=no"

group模塊
gid: 指定用的gid。
name: 指定用戶名。
state: 是建立仍是刪除, (present,absent);
system: 若是是,則表示建立的組是系統組;

[root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=present"

[root@ansible-server ~]# ansible web-nodes -m group -a "name=chenzun gid=897 state=present" 

[root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=absent" 

10.  service 模塊
管理服務的模塊, service管理的服務必須是yum安裝的服務, 即默認的系統服務腳本. 編譯安裝的服務很差使用service模塊管理. 
name: 服務名稱;
statestarted/stopped/restarted/reloaded;
enabled: true/false;
runlevel: 運行級別;
sleep: 若是執行了restarted,在stop和start之間沉睡幾秒;
arguments: 給命令行提供一些選項;

[root@ansible-server ~]# ansible web-nodes -m service -a "name=sshd state=restarted"

[root@ansible-server ~]# ansible web-nodes -m service -a "enabled=on name=httpd state=started"
[root@ansible-server ~]# ansible web-nodes -m service -a "enabled=yes name=httpd state=started" 

[root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=reloaded"    

[root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=stopped" 

11.  get_url 模塊
該模塊主要用於從http、ftp、https服務器上下載文件(相似於wget), 主要有以下選項:
sha256sum: 下載完成後進行sha256 check;
timeout: 下載超時時間, 默認10s
url: 下載的URL
url_password、url_username: 主要用於須要用戶名密碼進行驗證的狀況
dest: 將文件下載到哪裏的絕對路徑。若是dest是目錄, 則使用服務器提供的文件名, 或者若是沒有提供, 將使用遠程服務器上的URL的基本名稱。
headers: 以格式「key: value, key: value」爲請求添加自定義HTTP標頭

[root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://lan.Okay686.com/RDPWrap-v1.6.1.zip dest=/usr/local/src/"

[root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://10.0.8.50/ops.sh  dest=/opt/shell.sh mode=0440"

[root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh headers="key:value,key:value"' 

[root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh checksum=sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c' 

12.  fetch 模塊 (從遠程拉取出來文件)
它用於從遠程機器獲取文件,並將其本地存儲在由主機名組織的文件樹中。
src:  指定從遠程控制節點上要拉取的文件, 記住: 這個只能拉取文件!!  不能拉取目錄!!!  後續版本可能會支持遞歸提取。
dest:  將遠程節點拉取的文件保存到本地的目錄路徑. 例如,若是dest目錄是/backup,在主機host.example.com上命名爲/ etc/profile的src文件將被保存到/backup/host.example.com/etc/profile。
flat: 容許覆蓋將目標文件添加到主機名/path/to/file的默認行爲。默認爲no!!   若是設置爲yes, 將不會顯示相似172.16.60.221/root/信息. (即在dest的本機存放目錄下不會建立遠程節點ip命名的目錄)

將web-nodes組內的遠程節點的/root/bobo.file文件拉取到主控節點的/tmp下
[root@ansible-server ~]# ansible web-nodes -m fetch -a "dest=/mnt/ src=/root/bobo.file"

拉取過來後, 會發現dest定義的文件存放目錄下會有以遠程節點ip命名的目錄
[root@ansible-server ~]# ls /mnt/
172.16.60.212  172.16.60.213
[root@ansible-server ~]# ls /mnt/172.16.60.212/root/
bobo.file
[root@ansible-server ~]# ls /mnt/172.16.60.213/root/
bobo.file

flat參數,拉取的時候會自動建立設置的dest中不存在的目錄(同名文件會覆蓋):
[root@ansible-server ~]# ansible web-nodes -m fetch -a "dest=/mnt/wangshibo/ src=/root/bobo.file"
172.16.60.213 | CHANGED => {
    "changed": true, 
    "checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "dest": "/mnt/wangshibo/172.16.60.213/root/bobo.file", 
    "md5sum": "4221d002ceb5d3c9e9137e495ceaa647", 
    "remote_checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "remote_md5sum": null
}
172.16.60.212 | CHANGED => {
    "changed": true, 
    "checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "dest": "/mnt/wangshibo/172.16.60.212/root/bobo.file", 
    "md5sum": "4221d002ceb5d3c9e9137e495ceaa647", 
    "remote_checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "remote_md5sum": null
}

[root@ansible-server ~]# ls /mnt/
172.16.60.212  172.16.60.213  wangshibo
[root@ansible-server ~]# ls /mnt/wangshibo/
172.16.60.212  172.16.60.213
[root@ansible-server ~]# ls /mnt/
172.16.60.212  172.16.60.213  wangshibo
[root@ansible-server ~]# ls /mnt/wangshibo/
172.16.60.212  172.16.60.213
[root@ansible-server ~]# ls /mnt/wangshibo/172.16.60.212/root/
bobo.file
[root@ansible-server ~]# ls /mnt/wangshibo/172.16.60.213/root/
bobo.file

若是不想要從遠程節點拉取過來的文件在本機存放目錄裏已遠程節點ip命名的目錄裏面, 即去掉上面的/mnt裏面的172.16.60.212和172.16.60.213目錄
[root@ansible-server ~]# ansible web-nodes -m fetch -a "dest=/mnt/kevin/ src=/root/bobo.file flat=yes"         
172.16.60.213 | CHANGED => {
    "changed": true, 
    "checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "dest": "/mnt/kevin/bobo.file", 
    "md5sum": "4221d002ceb5d3c9e9137e495ceaa647", 
    "remote_checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "remote_md5sum": null
}
172.16.60.212 | CHANGED => {
    "changed": true, 
    "checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "dest": "/mnt/kevin/bobo.file", 
    "md5sum": "4221d002ceb5d3c9e9137e495ceaa647", 
    "remote_checksum": "804d716fc5844f1cc5516c8f0be7a480517fdea2", 
    "remote_md5sum": null
}

[root@ansible-server ~]# ls /mnt/
172.16.60.212  172.16.60.213  kevin  wangshibo
[root@ansible-server ~]# ls /mnt/kevin/
bobo.file

13.  file 模塊
file模塊主要用於遠程主機上的文件操做,file模塊包含以下選項:
force: 須要在兩種狀況下強制建立軟連接,一種是源文件不存在但以後會創建的狀況下;另外一種是目標軟連接已存在,須要先取消以前的軟鏈,而後建立新的軟鏈,有兩個選項: yes|no
group: 定義文件/目錄的屬組
mode: 定義文件/目錄的權限
owner: 定義文件/目錄的屬主
path: 必選項,定義文件/目錄的路徑
recurse: 遞歸的設置文件的屬性,只對目錄有效
src: 要被連接的源文件的路徑,只應用於state=link的狀況
dest: 被連接到的路徑,只應用於state=link的狀況
state: 表示file的狀態, 主要分爲:
         directory: 若是目錄不存在,建立目錄;
     file: 即便文件不存在,也不會被建立;
     link: 建立軟連接;
     hard: 建立硬連接;
     touch: 若是文件不存在,則會建立一個新的文件,若是文件或目錄已存在,則更新其最後修改時間;
     absent: 刪除目錄、文件或者取消連接文件;

[root@ansible-server ~]# ansible web-nodes -m file -a "path=/data/test state=touch mode="600" owner=kevin group=kevin"

[root@ansible-server ~]# ansible web-nodes -m file -a "path=/data/haha state=directory mode="755" owner=kevin group=kevin"

[root@ansible-server ~]# ansible web-nodes -m file -a "path=/data/test state=absent"     

[root@ansible-server ~]# ansible web-nodes -m file -a "path=/data/test state=touch mode="u+rw,g-wx,o-rwx" owner=kevin group=kevin"

文件的軟連接和硬連接
[root@ansible-server ~]# ansible web-nodes -m file -a "src=/data/test dest=/opt/heihei state=link"

[root@ansible-server ~]# ansible web-nodes -m file -a "src=/data/test dest=/mnt/hh state=hard" 

[root@ansible-server ~]# ansible web-nodes -m file -a "src=/etc/passwd dest=/opt/heihei state=link force=yes"

目錄作軟連接
[root@ansible-server ~]# ansible web-nodes -m file -a "src=/data/haha/ dest=/root/aaa state=link"

14.  lineinfile 模塊
用於對遠程受控節點的文件編輯模塊. 主要選項有:
path: 指定要修改的配置文件, 包括:
         regexp:匹配要修改的內容
         line:要增長或者修改的內容
state: 狀態, 包括:
         absent:表示刪除,當匹配到時進行刪除
         present:表示增長,當匹配到時進行修改,當沒有匹配到時在最後增長一行,默認爲此項
backrefs: 該參數值包括:
         no:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line;
         yes:表示若是沒有匹配到,則不變line;若是匹配成功,則替換line;
backup: 該參數值包括:
         no:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line;不備份原文件
         yes:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line;備份原文件
insertafter(匹配的是此行): 在匹配到的行以後添加一行.  (經測試, 發現是匹配到的行的最後一行的後面添加一行)
insertbefore(匹配的是此行): 在匹配到的行以前添加一行.  (經測試, 發現是匹配到的行的最後一行的前面添加一行)

舒適提示:  經測試,當不添加backerfs: yes參數時,匹配到後也會進行替換,但當匹配到的內容不存在時,會在最後增長一行;因此當不增長backerfs參數時,要肯定匹配到的內容存在;

將遠程受控節點的/data/test文件中的"123"字段修改成"wangshibo"
[root@ansible-server ~]# ansible web-nodes -m lineinfile -a 'path=/data/test regexp="123" line="wangshibo" backrefs=no'

[root@ansible-server ~]# ansible web-nodes -m lineinfile -a 'path=/etc/sudoers regexp="SYSTEM,SOFTWARE" line="STAPLES_ADMIN ALL=(ROOT) NOPASSWD:NETWORKING,LOCATE,STORAGE,DELEGATING,DRIVERS,SYSTEM,SOFTWARE,SERVICES,PROCESSES,FILE" backrefs=no'

匹配到的行後增長一行
[root@ansible-server ~]# ansible web-nodes -m lineinfile -a 'dest=/data/test insertafter="wangshibo" line="huihui"'

匹配到的行前增長一行  
[root@ansible-server ~]# ansible web-nodes -m lineinfile -a 'dest=/data/test insertbefore="root" line="huihui"'

刪除匹配到的行:
[root@ansible-server ~]# ansible web-nodes -m lineinfile -a 'path=/data/test regexp="123" state=absent' 

15.  unarchive模塊
用於解壓文件,模塊包含以下選項:
copy: 在解壓文件以前,是否先將文件複製到遠程主機,默認爲yes。若爲no,則要求目標主機上壓縮包必須存在。
creates: 指定一個文件名,當該文件存在時,則解壓指令不執行
dest: 遠程主機上的一個路徑,即文件解壓的絕對路徑。 必須是一個目錄路徑!
group: 解壓後的目錄或文件的屬組;
list_files: 若是爲yes,則會列出壓縮包裏的文件,默認爲no,2.0版本新增的選項;
mode: 解壓後文件的權限;
src: 若是copy爲yes,則須要指定壓縮文件的源路徑;
owner: 解壓後文件或目錄的屬主;

經測試, 該模塊解壓時識別zip, tgz , tar.gz, tar.bz2 格式的壓縮包, gzip格式的測試時不支持.

將/usr/local/src/nginx.tgz解壓縮到/data/www中
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/usr/local/src/nginx.tgz dest=/data/www/"

解壓遠程受控節點上已存在的文件
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/root/file.zip dest=/usr/local remote_src=yes" 

解壓文檔須要下載的文件(2.0中添加)
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=https://example.com/example.zip dest=/usr/local/bin remote_src=yes"

16.  command模塊 和 shell模塊
用於在各被管理節點運行指定的命令. shell和command的區別:shell模塊能夠特殊字符,而command是不支持!!

command 是ansible的默認模塊, 即不指定模塊的時候默認使用的模塊就是command !  使用ansible自帶模塊執行命令 若是要用 > < | & ‘ ‘ 使用shell 模塊, command是不支持管道符之類的。

可使用"ansible-doc -s shell" 或 "ansible-doc -s command" 查看下shell和command的參數, 二者之間的參數用法上基本同樣的.

[root@ansible-server ~]# ansible-doc -s shell
- name: Execute commands in nodes.
  shell:
      chdir:                 # 在執行命令以前,先cd到指定的目錄下
      creates:               # 用於判斷命令是否要執行,若是指定的文件存在(可使用通配符)存在,則不執行
      executable:            # 再也不使⽤默認的/bin/sh解析並執⾏命令,⽽是使⽤此處指定的命令解析(例如使⽤expect解析expect腳本。必須爲絕對路徑)
      free_form:             # 默認的選項,這裏只是顯示,其實是沒有的
      removes:               # 用於判斷命令是否要執行,若是指定的文件存在(可使用通配符)不存在,則不執行
      stdin:                 # 將命令的stdin直接設置爲指定值
      warn:                  # 設置command的警告信息(在/etc/ansible/ansible.cfg中有配置項)

示例以下: 

[root@ansible-server ~]# ansible all -a "date"
172.16.60.214 | CHANGED | rc=0 >>
Sun Mar 17 15:24:55 CST 2019

172.16.60.212 | CHANGED | rc=0 >>
Sun Mar 17 15:24:55 CST 2019

172.16.60.213 | CHANGED | rc=0 >>
Sun Mar 17 15:24:55 CST 2019

[root@ansible-server ~]# ansible all -m command -a "date"
172.16.60.213 | CHANGED | rc=0 >>
Sun Mar 17 15:25:14 CST 2019

172.16.60.212 | CHANGED | rc=0 >>
Sun Mar 17 15:25:14 CST 2019

172.16.60.214 | CHANGED | rc=0 >>
Sun Mar 17 15:25:14 CST 2019

在命令執行以前, 先切換到指定的目錄路徑下
[root@ansible-server ~]# ansible web-nodes -m command -a "chdir=/tmp pwd"
172.16.60.213 | CHANGED | rc=0 >>
/tmp

172.16.60.212 | CHANGED | rc=0 >>
/tmp

creates 文件是否存在,不存在就執行命令
[root@ansible-server ~]# ansible web-nodes -m command -a "creates=/etc/hosts date"
172.16.60.212 | SUCCESS | rc=0 >>
skipped, since /etc/hosts exists

172.16.60.213 | SUCCESS | rc=0 >>
skipped, since /etc/hosts exists

[root@ansible-server ~]# ansible web-nodes -m command -a "creates=/etc/hosts1231 date"
172.16.60.213 | CHANGED | rc=0 >>
Sun Mar 17 15:26:40 CST 2019

172.16.60.212 | CHANGED | rc=0 >>
Sun Mar 17 15:26:40 CST 2019

removes 文件是否存在,不存在就不執行命令,
[root@ansible-server ~]# ansible web-nodes -m command -a "removes=/etc/hosts uptime"
172.16.60.213 | CHANGED | rc=0 >>
 15:33:01 up 14 days, 12:08,  2 users,  load average: 0.13, 0.04, 0.05

172.16.60.212 | CHANGED | rc=0 >>
 15:33:01 up 14 days, 13:20,  2 users,  load average: 0.06, 0.03, 0.05

[root@ansible-server ~]# ansible web-nodes -m command -a "removes=/etc/hosts1231 uptime"
172.16.60.213 | SUCCESS | rc=0 >>
skipped, since /etc/hosts1231 does not exist

172.16.60.212 | SUCCESS | rc=0 >>
skipped, since /etc/hosts1231 does not exist

shell 模塊:這是個萬能模塊, 執行linux命令時能夠用遠程節點執行命令;
注意: shell 模塊在遠程執行腳本時,遠程主機上必定要有相應的腳本;

[root@ansible-server ~]# ansible web-nodes -m shell -a "/bin/bash /opt/test.sh"
172.16.60.212 | CHANGED | rc=0 >>
ansible-node01
it is OK

172.16.60.213 | CHANGED | rc=0 >>
ansible-node02
it is OK

下面的shell模塊命令中使用了特殊字符, 若是使用comand模塊則就不行了!!
[root@ansible-server ~]# ansible web-nodes -m shell -a "cat /etc/passwd > /tmp/test"  

使用command模塊執行下面命令, 則就會報錯!  command模塊不支持特殊字符!
[root@ansible-server ~]# ansible web-nodes -m command -a "cat /etc/passwd > /tmp/test" 

17.  hostname模塊
修改遠程受控節點的主機名的模塊

使用hostname模塊修改遠程節點的主機名時, 最好指明遠程單節點ip地址進行設置主機名了. 由於不一樣節點的主機名不同

[root@ansible-server ~]# ansible 172.16.60.213 -m hostname -a 'name="web-node03"'                             
172.16.60.213 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "", 
        "ansible_fqdn": "web-node03", 
        "ansible_hostname": "web-node03", 
        "ansible_nodename": "web-node03"
    }, 
    "changed": true, 
    "name": "web-node03"
}

18.  script模塊
在遠程受控節點上執行主控節點的腳本,至關於scp+shell組合

好比在遠程受控節點上執行主控節點的/opt/test.sh腳本
[root@ansible-server ~]# ansible all -m script -a "/opt/test.sh"

須要注意: 使用scripts模塊,不用將腳本傳輸到遠程節點,腳本自己不用進行受權,便可利用script模塊執行。直接執行腳本便可,不須要使用sh 或者 /bin/bash

19.  stat模塊
獲取遠程文件的狀態信息,包括atime,ctime,mtime,md5,uid,gid等信息

[root@ansible-server ~]# ansible all -m stat -a "path=/data/test"

20.  cron模塊
遠程受控節點的crontab配置

設置指定的crontab計劃任務
[root@ansible-server ~]# ansible web-nodes -m cron -a "name='test' hour='2-5' minute='*/5' day='1' month='3,4' weekday='1' job='ls -l' user=root"
172.16.60.212 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test"
    ]
}
172.16.60.213 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test"
    ]
}

而後到172.16.60.212和172.16.60.213受控節點上查看:
[root@ansible-node02 ~]# crontab -l
#Ansible: test
*/5 2-5 1 3,4 1 ls -l

刪除指定crontab
[root@ansible-server ~]# ansible web-nodes -m cron -a "name='test' state=absent"   

======================================================
使用ansible添加一條定時任務
[root@ansible-server ~]# ansible web-nodes -m cron -a "minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh'"

遠程受控節點上查看
[root@ansible-node02 ~]# crontab -l
#Ansible: None
* * * * * /bin/sh /server/scripts/test.sh

設置定時任務註釋信息,防止重複,name設定一個名稱
[root@ansible-server ~]# ansible web-nodes -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"
[root@ansible-server ~]# ansible web-nodes -m cron -a "name='cron02' job='/bin/sh /server/scripts/test2.sh'"

遠程受控節點上查看
[root@ansible-node02 ~]# crontab -l
#Ansible: cron01
* * * * * /bin/sh /server/scripts/test.sh
#Ansible: cron02
* * * * * /bin/sh /server/scripts/test2.sh

刪除相應定時任務
[root@ansible-server ~]# ansible 172.16.60.212 -m cron -a "name='ansible cron02' minute=0 hour=0 job='/bin/sh /server/scripts/test.sh' state=absent"

註釋相應定時任務,使定時任務失效 (disabled=yes 表示註釋掉, 即無效; disabled=no 表示去掉註釋, 即有效)
[root@ansible-server ~]# ansible web-nodes -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh /server/scripts/test.sh' disabled=yes"

21.  mount模塊
在遠程受控節點上掛載文件系統。可用參數:
present: 開機掛載,僅將掛載配置寫入/etc/fstab(不經常使用)
mounted: 掛載設備,並將配置寫入/etc/fstab
unmounted: 卸載設備,不會清除/etc/fstab寫入的配置
absent: 卸載設備,會清理/etc/fstab寫入的配置

mount已經使用path代替了原來的name參數,可是name參數仍是可使用的.

將受控節點的/dev/sd0設備掛載到/mnt/data目錄上, 文件格式爲ext4, 只讀屬性
[root@ansible-server ~]# ansible web-nodes -m mount -a "path=/mnt/data src=/dev/sd0 fstype=ext4 ots=ro state=present"

僅將掛載的配置寫入/etc/fstab,並不會執行掛載操做
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=present"

臨時掛載設備,並將掛載信息寫入/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=mounted"

臨時卸載,不會清理/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=unmounted"

卸載,不只臨時卸載,同時會清理/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=absent"

22.  find模塊
幫助在被管理的受控主機中查找符合條件的文件,就像 find 命令同樣.

經常使用選項:
paths:  必須參數,指定在哪一個目錄中查找文件,能夠指定多個路徑,路徑間用逗號隔開,此參數有別名,使用別名 path 或者別名 name 能夠代替 paths。
recurse: 默認狀況下,只會在指定的目錄中查找文件,也就是說,若是目錄中還包含目錄,ansible 並不會遞歸的進入子目錄查找對應文件,若是想要遞歸的查找文件,須要使用 recurse 參數,當 recurse 參數設置爲 yes 時,表示在指定目錄中遞歸的查找文件。
hidden: 默認狀況下,隱藏文件會被忽略,當 hidden 參數的值設置爲 yes 時,纔會查找隱藏文件。
file_type: 默認狀況下,ansible 只會根據條件查找」文件」,並不會查找」目錄」或」軟連接」等文件類型,若是想要指定查找的文件類型,能夠經過 file_type 指定文件類型,可指定的文件類型有 any、directory、file、link 四種。
patterns: 使用此參數指定須要查找的文件名稱,支持使用 shell(好比通配符)或者正則表達式去匹配文件名稱,默認狀況下,使用 shell 匹配對應的文件名,若是想要使用 python 的正則去匹配文件名,須要將 use_regex 參數的值設置爲 yes。
use_regex:默認狀況下,find 模塊不會使用正則表達式去解析 patterns 參數中對應的內容,當 use_regex 設置爲 yes 時,表示使用 python 正則解析 patterns 參數中的表達式,不然,使用 glob 通配符解析 patterns 參數中的表達式。
contains:使用此參數能夠根據文章內容查找文件,此參數的值爲一個正則表達式,find 模塊會根據對應的正則表達式匹配文件內容。
age: 使用此參數能夠根據時間範圍查找文件,默認以文件的 mtime 爲準與指定的時間進行對比,好比,若是想要查找 mtime 在3天以前的文件,那麼能夠設置 age=3d,若是想要查找 mtime 在3天之內的文件,能夠設置 age=-3d,這裏所說的3天是按照當前時間往前推3天,可使用的單位有秒(s)、分(m)、時(h)、天(d)、星期(w)。
age_stamp: 文件的時間屬性中有三個時間種類,atime、ctime、mtime,當咱們根據時間範圍查找文件時,能夠指定以哪一個時間種類爲準,當根據時間查找文件時,默認以 mtime 爲準。
size: 使用此參數能夠根據文件大小查找文件,好比,若是想要查找大於3M的文件,那麼能夠設置 size=3m,若是想要查找小於50k的文件,能夠設置 size=-50k,可使用的單位有 t、g、m、k、b。
get_checksum: 當有符合查找條件的文件被找到時,會同時返回對應文件的 sha1校驗碼,若是要查找的文件比較大,那麼生成校驗碼的時間會比較長

在受控主機的 /data目錄中查找文件內容中包含wang字符串的文件,隱藏文件會被忽略,不會進行遞歸查找。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*"" 

在受控主機的的 /data目錄以及其子目錄中查找文件內容中包含wang字符串的文件,隱藏文件會被忽略。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*" recurse=yes" 

在受控主機的的 /data目錄中查找以 .sh 結尾的文件,包括隱藏文件,可是不包括目錄或其餘文件類型,不會進行遞歸查找。
[root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns="*.sh" file_type=any hidden=yes'

在受控主機的的 /data目錄中查找以 .sh 結尾的文件,只不過patterns對應的表達式爲正則表達式,查找範圍包括隱藏文件,包括全部文件類型,
可是不會進行遞歸查找,不會對/data目錄的子目錄進行查找。
[root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns=".*\.sh" use_regex=yes file_type=any hidden=yes'  

在受控主機的的 /data目錄中以及其子目錄中查找 mtime 在1天之內的文件,不包含隱藏文件,不包含目錄或軟連接文件等文件類型。
[root@ansible-server ~]# ansible web-nodes -m find -a "path=/data age=-1d recurse=yes"

在受控主機的的 /data目錄中以及其子目錄中查找大於 2g 的文件,不包含隱藏文件,不包含目錄或軟連接文件等文件類型。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data size=2g recurse=yes"

在受控主機的的 /data目錄中以及其子目錄中查找以 .sh 結尾的文件,而且返回符合條件文件的 sha1 校驗碼,包括隱藏文件
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data patterns=*.sh get_checksum=yes hidden=yes recurse=yes"

23.  selinux模塊
管理遠程受控節點的selinux的模塊

[root@ansible-server ~]# ansible web-nodes -m selinux -a 'state=disabled'  
172.16.60.212 | SUCCESS => {
    "changed": false, 
    "configfile": "/etc/selinux/config", 
    "msg": "", 
    "policy": "targeted", 
    "reboot_required": false, 
    "state": "disabled"
}
172.16.60.213 | SUCCESS => {
    "changed": false, 
    "configfile": "/etc/selinux/config", 
    "msg": "", 
    "policy": "targeted", 
    "reboot_required": false, 
    "state": "disabled"
}

24.  setup模塊
用於收集遠程受控主機的一些基本信息. 

filter參數:用於進行條件過濾。若是設置,僅返回匹配過濾條件的信息

不加過濾參數, 就會將受控主機的全部信息都打印出來
[root@ansible-server ~]# ansible web-nodes -m setup

獲取受控主機的 IPV4 地址
[root@ansible-server ~]# ansible web-nodes -m setup -a "filter=ansible_all_ipv4_addresses"
172.16.60.212 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.16.60.212"
        ]
    }, 
    "changed": false
}
172.16.60.213 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.16.60.213", 
            "172.19.0.1", 
            "172.17.0.1"
        ]
    }, 
    "changed": false
}


獲取受控主機的內存信息
[root@ansible-server ~]# ansible web-nodes -m setup -a "filter=ansible_memory_mb"
172.16.60.213 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 7244, 
                "used": 578
            }, 
            "real": {
                "free": 4772, 
                "total": 7822, 
                "used": 3050
            }, 
            "swap": {
                "cached": 0, 
                "free": 8063, 
                "total": 8063, 
                "used": 0
            }
        }
    }, 
    "changed": false
}
172.16.60.212 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 7194, 
                "used": 628
            }, 
            "real": {
                "free": 3544, 
                "total": 7822, 
                "used": 4278
            }, 
            "swap": {
                "cached": 0, 
                "free": 8063, 
                "total": 8063, 
                "used": 0
            }
        }
    }, 
    "changed": false
}


經過通配符實現模糊匹配,好比以」mb」關鍵字結尾的信息
[root@ansible-server ~]# ansible web-nodes -m setup -a "filter=*mb"
172.16.60.212 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 3543, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 7193, 
                "used": 629
            }, 
            "real": {
                "free": 3543, 
                "total": 7822, 
                "used": 4279
            }, 
            "swap": {
                "cached": 0, 
                "free": 8063, 
                "total": 8063, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 7822, 
        "ansible_swapfree_mb": 8063, 
        "ansible_swaptotal_mb": 8063
    }, 
    "changed": false
}
172.16.60.213 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 4771, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 7243, 
                "used": 579
            }, 
            "real": {
                "free": 4771, 
                "total": 7822, 
                "used": 3051
            }, 
            "swap": {
                "cached": 0, 
                "free": 8063, 
                "total": 8063, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 7822, 
        "ansible_swapfree_mb": 8063, 
        "ansible_swaptotal_mb": 8063
    }, 
    "changed": false
}

其餘經常使用信息列出:

ansible_all_ipv4_addresses:僅顯示ipv4的信息。
ansible_devices:僅顯示磁盤設備信息。
ansible_distribution:顯示是什麼系統,例:centos,suse等。
ansible_distribution_major_version:顯示是系統主版本。
ansible_distribution_version:僅顯示系統版本。
ansible_machine:顯示系統類型,例:32位,仍是64位。
ansible_eth0:僅顯示eth0的信息。
ansible_hostname:僅顯示主機名。
ansible_kernel:僅顯示內核版本。
ansible_lvm:顯示lvm相關信息。
ansible_memtotal_mb:顯示系統總內存。
ansible_memfree_mb:顯示可用系統內存。
ansible_memory_mb:詳細顯示內存狀況。
ansible_swaptotal_mb:顯示總的swap內存。
ansible_swapfree_mb:顯示swap內存的可用內存。
ansible_mounts:顯示系統磁盤掛載狀況。
ansible_processor:顯示cpu個數(具體顯示每一個cpu的型號)。
ansible_processor_vcpus:顯示cpu個數(只顯示總的個數).

                                                                                 Ansible系列命令介紹                                                                                 

Ansible命令是平常工做中最長使用的命令,主要的使用場景爲非固化需求,臨時一次性的操做。

1)  ansible命令的用法
ansible命令其實在運維工做中用的最多的命令,它的主要目的或者說是主要的應用場景是:在作臨時性的操做的時候(好比只想看看被控端的一臺主機或者多臺主機是否存活),在man中的定義是:run a command somewhere else ansible經過ssh實現配置管理、應用部署、任務執行等功能,建議配置ansible端能基於密鑰認證的方式聯繫各個被管理節點.  ansible命令在運維工做中是尤其重要的在操做的時候結合ansible的模塊(ansible-doc --list命令查看模塊)能夠實現不少功能:

語法:ansible <host-pattern> [options]

使用ansible --help能夠查看到命令參數, 
經常使用選項參數:
--version               #顯示版本
-m module               #指定使用的模塊,默認爲command
-v                      #查看執行的詳細過程(-vv、-vvvv更詳細)
--list-hosts            #顯示主機列表(能夠簡寫爲--list)
-k,--ask-pass           #提示輸入ssh鏈接密碼,默認使用key驗證
-K,--ask-become-pass    #提示執行輸入sudo的密碼
-C,--check              #檢查,並不執行
-T,--timeout=TIMEOUT    #執行命令的超時時間,默認10s
-u,--user=REMOTE_USER   #指定遠程執行的執行用戶
-b,--become             #代替舊版本的sudo切換
-h,--help               #顯示使用幫助
-u                      #指定遠程主機運行此命令的用戶
-s                      #至關於sudo
-S                      #使用sudo

======================================================
[普通選項]
-a MODULE_ARGS
--args=MODULE_ARGS
傳遞參數給模塊
 
--ask-vault-pass
詢問vault的密碼
 
-B SECONDS
--background=SECONDS
異步後臺⽅式執⾏任務,並在指定的秒數後超時,超時會殺掉任務的進程。默認是同步,即保持長鏈接,它會等待
全部執⾏完畢(即阻塞模式)。但有時候是不必這樣的,⽐如某些命令的執⾏時間⽐ssh的超時時間還長。若是
不指定超時秒數,將以同步⽅式運⾏任務
 
-P POLL_INTERVAL
--poll=POLL_INTERVAL
異步模式下輪詢任務的時間間隔,默認60秒
 
-C
--check
不對遠程主機作一些改變,而是預測某些可能發生的改變(檢查功能)
 
-e EXTRA_VARS
--extra-vars=EXTRA_VARS
配置額外的配置變量(key=value或者YAML/JSON格式)
 
-f FORKS
--forks=FORKS
指定並行處理的進程數量,默認5個
 
-h
--help
顯示幫助信息
 
-i INVENTORY
--inventory-file=INVENTORY
指定inventory⽂件,多個⽂件使⽤逗號分隔。默認爲/etc/ansible/hosts
 
-l SUBSET
--limit=SECONDS
使⽤額外的匹配模式來篩選⽬標主機列表。
此處的匹配模式是在已有匹配模式下進⾏的,因此是更嚴格的篩選。例如指定了主機組的狀況下,使⽤-l選項從中只選⼀臺主機進⾏控制
 
--list-hosts
不會執行任何操做,而是列出匹配到的主機列表
 
-m MODULE_NAME
--module-name=MODULE_NAME
指定要執行的模塊名,默認的模塊爲"command"
 
--new-vault-password-file=NEW_VAULT_PASSWORD_FILE
new vault password f ile f or rekey
 
-o
--one-line
簡化輸出(一行輸出模式)
 
--output-OUTPUT_FILE
output f ile name f or encrypt or decrypt; use - f or stdout
 
--syntax-check
檢查playbook的語法,不會執行
 
-t TREE
--tree=TREE
記錄輸出到此⽬錄中(測試時以每一個host名如IP地址爲⽂件名記錄,結果記錄到對應的⽂件中)。
此選項在ansible巨慢的時候(如瞬間應該返回的命令還須要10多秒才完成)有奇⽤,或者將ansible的結果重
定向到某個⽂件中也能解決,爲何如此,我也不明⽩(表⾯看來和輸出⽅式有關係),屢次親測有效。
 
--vault-password-file=VAULT_PASSWORD_FILE
指定vault密碼文件
 
-v
--verbose
輸出詳細信息,-vvv和-vvvv輸出更詳細的信息
 
--version
顯示ansbile的版本
 
======================================================
[如下是鏈接選項,⽤於控制誰以及如何鏈接主機]
-k
--ask-pass
詢問鏈接時的密碼
 
--private-key=KEY_FILE
--key-file=KEY_FILE
使用文件來認證SSH鏈接的過程
 
-u REMOTE_USER
--user=REMOTE_USER
使用指定的用戶名進行鏈接
 
-c CINNECTION
--connection=CINNECTION
鏈接類型,默認爲ssh。paramiko (SSH), ssh, winrm and local. local is mostly usef ul f or crontab or kickstarts.
 
-T TIMEOUT
--time=TIMEOUT
鏈接的超時時間,單位爲秒,默認10秒
 
--ssh-common-args=SSH_COMMON_ARGS
指定傳遞給sftp/scp/ssh等⼯具的通⽤額外參數
 
--sftp-extra-args=SFTP_EXTRA_ARGS
指定只傳遞給sftp的額外參數,如-f
 
--scp-extra-args=SCP_EXTRA_ARGS
指定只傳遞給scp的額外參數,如-l
 
--ssh-extra-args=SSH_EXTRA_ARGS
指定只傳遞給ssh的額外參數,如-R
 
======================================================
[如下是權限控制選項:控制在⽬標主機上以什麼⾝份和權限運⾏任務]
-s
--sudo
爲運行ansible命令的用戶提高權限爲sudo_user的權限,此命令已經報廢,使用become代替
 
-u SUDO_USER
--sudo-user=SUDO_USER
指望的sudo_user,默認爲root,已報廢,使用become代替
 
-S
--su
使⽤su的⽅式執⾏操做,已廢棄,使⽤become替代
 
-R SU_USER
--su-user=SU_USER
使⽤此user的su執⾏操做,默認爲root,已廢棄,使⽤become替代
 
-b
--become
使用become的方式升級權限
 
--become-method=BECOME_METHOD
指定提高權限的方式,可選如下⼏種:sudo/su/pbrun/pf exec/doas/dzdo/ksu/runas值
 
--become-user=BECOME_USER
要提高爲哪一個user的權限,默認爲root
 
--ask-sudo-pass
詢問sudo密碼,已廢棄,使⽤become替代
 
--ask-su-pass
詢問su的密碼,已廢棄,使⽤become替代
 
-K
--ask-become-pass
詢問become提高權限時的密碼

 Ansible返回結果通常會使用紅色,橘色,橘黃色顯示,紅色表示執行過程異常,會終止剩餘任務的執行,綠色和橘黃色表示執行過程沒有異常,但橘黃色表示命令執行結束後目標有狀態變化,綠色表示命令執行結束後目標沒有狀態變化。

2)  ansible-doc
ansible-doc是查看ansible模塊(插件)文檔說明,針對每一個模塊都有詳細的用法說明,功能和Linux的man命令相似

語法:ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]
參數:
-a, --all                                   #顯示文檔全部的模塊(這個選項有個bug)
-h, --help                                  #顯示使用幫助
-j, --json                                  #將全部的模塊轉儲爲JSON格式
-l, --list                                  #查看模塊列表
-F, --list_files                            #顯示模塊的名稱和模塊原路徑
-M MODULE_PATH, --module-path=MODULE_PATH   #
-s, --snippet                               #簡介的顯示模塊的幫助信息
-t TYPE, --type=TYPE                        #指定模塊類型(默認爲module)
-v, --verbose                               #查看執行的詳細過程(-vv、-vvvv更詳細)
--version                                   #查看版本
 
執行 ansible-doc 模塊名  查看模塊的詳細信息
示例:
查看模塊詳細信息
[root@ansible ~]# ansible-doc ping
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)
 
        A trivial test module, this module always returns `pong' on successful contact. It does not make sense in playbooks, but it is useful from `/usr/bin/ansible' to verify the
        ability to login and that a usable Python is configured. This is NOT ICMP ping, this is just a trivial test module that requires Python on the remote-node. For Windows targets,
        use the [win_ping] module instead. For Network targets, use the [net_ping] module instead.
 
OPTIONS (= is mandatory):
 
- data
        Data to return for the `ping' return value.
        If this parameter is set to `crash', the module will cause an exception.
        [Default: pong]
 
 
NOTES:
      * For Windows targets, use the [win_ping] module instead.
      * For Network targets, use the [net_ping] module instead.
 
AUTHOR: Ansible Core Team, Michael DeHaan
        METADATA:
          status:
          - stableinterface
          supported_by: core
         
 
EXAMPLES:
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
 
# Example from an Ansible Playbook
- ping:
 
# Induce an exception to see what happens
- ping:
    data: crash
 
RETURN VALUES:
 
 
ping:
    description: value provided with the data parameter
    returned: success
    type: string
    sample: pong
 
查看模塊的簡單信息
[root@ansible ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.

3)  ansible-playbook
ansible-playbook是平常用的最多的命令,其工做機制是:經過讀取預先編寫好的playbook文件實現批量管理,要實現的功能與命令ansbile同樣,能夠理解爲按必定的條件組成ansible的任務集ansible-playbook命令後跟YML格式的playbook文件,執行事先編排好的任務集

語法: ansible-playbook [options] playbook.yml [playbook2 ...]
參數:大部分的參數和ansible的參數一致
可使用:ansible-playbook --help能夠查看到命令參數

例如: 使用ansible-playbook執行一個yaml文件
[root@ansible ~]# ansible-playbook -C /opt/ansible-playbook/test.yaml

4)  ansible-galaxy
這個命令是一個下載互聯網上roles集合的工具(這裏提到的roles集合其實就是多個playbook文件的集合)
roles集合所在地址: https://galaxy.ansible.com

使用方法:
語法:ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...
參數:
-h, --help                          #查看命令幫助
-c, --ignore-certs                  #忽略SSL證書驗證錯誤
-s API_SERVER, --server=API_SERVER  #API服務器地址         
-v, --verbose                       #查看執行的詳細過程(-vv、-vvvv更詳細)                  
--version                           #查看版本
 
示例:
搜索roles
[root@ansible ~]# ansible-galaxy search nginx

查看search的使用幫助
[root@ansible ~]# ansible-galaxy search --help
 
安裝roles
[root@ansible ~]# ansible-galaxy install geerlingguy.nginx
- downloading role 'nginx', owned by geerlingguy
- downloading role from https://github.com/geerlingguy/ansible-role-nginx/archive/2.6.2.tar.gz
- extracting geerlingguy.nginx to /root/.ansible/roles/geerlingguy.nginx
- geerlingguy.nginx (2.6.2) was installed successfully
上面能夠看到實際上就是互聯網上的geerlingguy.nginx下載到本地的/root/.ansible/roles/中
查看install的使用幫助
[root@ansible ~]# ansible-galaxy install --help
 
刪除roles
[root@ansible ~]# ansible-galaxy remove geerlingguy.nginx
這個步驟就是把/root/.ansible/roles/中的geerlingguy.nginx文件夾刪除
查看remove的使用幫助
[root@ansible ~]# ansible-galaxy remove --help
 
列出安裝的roles
[root@ansible ~]# ansible-galaxy list
- geerlingguy.nginx, 2.6.2
查看list的使用幫助
[root@ansible ~]# ansible-galaxy list --help

====================================================================
舒適提示:
ansible-galaxy的使用方法還有不少,在語法中能夠看到能執行的操做,可使用示例中的相同方法查看各個功能的幫助信息!!!
====================================================================

5)  ansible-pull
該指令設計到了ansible的另外一種的工做模式: pull模式 (ansible默認使用的是push模式),這個和一般使用的push模式的工做機制正好相反(push拉取,pull推送)
ansible的pull模式適用於:
-> 你有數量巨大的機器須要配置,即便使用高併發線程依然須要花費大量的時間
-> 你要在剛啓動的,沒有聯網的主機上執行ansible

語法: ansible-pull -U <repository> [options] [<playbook.yml>]
參數: 大部分的參數和ansible的參數一直,由於不經常使用全部就不列舉了
可使用 ansible-pull --help查看具體的幫助

經過ansible-pull結合Git和crontab一併實現,其原理以下:經過crontab按期拉取指定的Git版本到本地,並以指定模式自動運行預先制訂好的指令。

具體示例參考以下:
*/20 * * * * root /usr/local/bin/ansible-pull -o -C 2.1.0 -d /srv/www/king-gw/ -i /etc/ansible/hosts -U git:// git.kingifa.com/king-gw-ansiblepull >> /var/log/ansible-pull.log 2>&1

===========================================================
舒適提示:
ansible-pull一般在配置大批量的機器的場景下使用,靈活性有小小的欠缺,但效率幾乎能夠無限的提高,對於運維人員的技術水平和前瞻性的規劃有很高要求!!!
===========================================================

6)  ansible-console (ansible本身的終端)
Ansible-console是ansible爲用戶提供的一款交互式工具,用戶可在ansible-console虛擬出的終端上使用ansible內置的各類命令。全部的操做與shell相似,並支持tab補全.

語法:ansible-console [<host-pattern>] [options]
參數:大部分的參數和ansible的參數一直,由於不經常使用全部就不列舉了
可使用:ansible-console --help 查看幫助

===============使用示例================
對全部的被控客戶機進行終端命令操做
[root@ansible ~]# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
 
root@all (3)[f:5]$ 而後在虛擬終端裏執行命令, 好比輸入"uptime", 就會顯示全部被控客戶機的uptime命令結果
 
對/etc/ansible/hosts裏面定義的某個清單列表進行終端命令操做
[root@ansible ~]# ansible-console web-nodes
Welcome to the ansible console.
Type help or ? to list commands.

root@web-nodes (9)[f:5]$ list
172.16.60.212
172.16.60.213

root@web-nodes (9)[f:5]$ cat /etc/passwd|grep root
172.16.60.212 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
dockerroot:x:998:995:Docker User:/var/lib/docker:/sbin/nologin

172.16.60.213 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
dockerroot:x:998:995:Docker User:/var/lib/docker:/sbin/nologin
 
root@web (2)[f:5]$
 
在終端可作的操做
設置併發數: forks n  例如:forks 10
切換組: cd 組名      例如:cd web
列出當前組主機列表   例如:list
列出全部的內置命令(其實就是內置的模塊)   例如:?或者help
 
exit命令退出終端

7)  ansible-config (該命令不經常使用)
查看,編輯管理ansible的配置文件

語法:ansible-config [view|dump|list] [--help] [options] [ansible.cfg]
參數:
-c CONFIG_FILE, --config=CONFIG_FILE    #指定配置文件所在的路徑
-h, --help                              #查看幫助信息
-v, --verbose                           #查看執行的詳細過程(-vv、-vvvv更詳細) 
--version                               #查看版本

8)  ansible-connection
這是一個插件,指定執行模式(測試用)

9)  ansible-inventory
查看被控制端主機清單的詳細信息默認狀況下它使用庫存腳本,返回JSON格式:

[root@ansible ~]# ansible-inventory --list
{
    "_meta": {
        "hostvars": {
            "172.16.60.205": {}, 
            "172.16.60.206": {}, 
            "172.16.60.207": {}, 
            "172.16.60.212": {}, 
            "172.16.60.213": {}, 
            "172.16.60.214": {}, 
            "172.16.60.220": {}, 
            "172.16.60.221": {}, 
            "172.16.60.222": {}
        }
    }, 
    "all": {
        "children": [
            "test", 
            "ungrouped", 
            "web-nodes"
        ]
    }, 
    "test": {
        "hosts": [
            "172.16.60.212", 
            "172.16.60.213"
        ]
    }, 
    "ungrouped": {}, 
    "web-nodes": {
        "hosts": [
            "172.16.60.205", 
            "172.16.60.206", 
            "172.16.60.207", 
            "172.16.60.212", 
            "172.16.60.213", 
            "172.16.60.214", 
            "172.16.60.220", 
            "172.16.60.221", 
            "172.16.60.222"
        ]
    }
}

10)  ansible-vault
ansible-vault主要用於配置文件的加密,如編寫的playbook配置文件中包含敏感的信息,不但願其餘人隨便的看,ansible-vault可加密/解密這個配置文件:

語法:ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml]
參數:
--ask-vault-pass      ask for vault password
-h, --help                                          #查看幫助信息
--new-vault-id=NEW_VAULT_ID                         #設置用於rekey的新vault標識
--new-vault-password-file=NEW_VAULT_PASSWORD_FILE   #新的保險庫密碼文件爲rekey
--vault-id=VAULT_IDS                                #要使用的保險庫標識
--vault-password-file=VAULT_PASSWORD_FILES          #庫密碼文件
-v, --verbose                                       #查看執行的詳細過程(-vv、-vvvv更詳細)
--version                                           #查看版本
 
使用參數:
encrypt (加密)
decrypt (解密)
create (建立)
view (查看)
edit (編輯)
rekey (修改密碼)
 
示例說明
新建一個yml的文件,寫入一些數據
[root@ansible-server ~]# echo "kevin123" > bo.yaml

給test.yml設置密碼
[root@ansible-server ~]# ansible-vault encrypt bo.yaml
New Vault password: 
Confirm New Vault password: 
Encryption successful

查看這個yaml文件
[root@ansible-server ~]# cat bo.yaml 
$ANSIBLE_VAULT;1.1;AES256
33663035323365353562633732366331336261356561636531393039336166623537383263346533
3634363730303134376230653163376239386536626533640a356461633233663937343061313563
36313036643738626531373331623237373636313332313830333738343561306132643836306232
3139393632343163620a313939333639333362373663323065666161646231663263363338663934
6431

上面查看到明顯被加密了. 正確的查看方式以下 (即先解密, 而後再查看):
[root@ansible-server ~]# ansible-vault decrypt bo.yaml 
Vault password: 
Decryption successful

[root@ansible-server ~]# cat bo.yaml
kevin123

查看被加密的文件
[root@ansible-server ~]# ansible-vault encrypt bo.yaml 
New Vault password: 
Confirm New Vault password: 
Encryption successful

[root@ansible-server ~]# ansible-vault view bo.yaml   
Vault password: 
kevin123

接着編輯被加密的文件
[root@ansible-server ~]# ansible-vault edit bo.yaml 
Vault password:   #輸入密碼後, 就進入了bo.yaml文件的打開方式(至關於vim進入編輯)

[root@ansible-server ~]# ansible-vault view bo.yaml 
Vault password: 
kevin123
this is test

建立被加密的文件
[root@ansible-server ~]# ansible-vault create grace.yaml
New Vault password:     #輸定這個新文件密碼
Confirm New Vault password:   #再次確認密碼後, 就直接進入到這個新文件中進行編輯

 [root@ansible-server ~]# ansible-vault view grace.yaml
Vault password: 
this is test of grace

                                                                         Ansible 其餘用法                                                                           

1)  ansible限制後臺運行時間

後臺運行老是耗費比較長的時間,從而其狀態在隨後老是可以查看的,若是踢掉主機,又不想輪訓,以下:
[root@ansible-server ~]# ansible web-nodes -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"

若是要檢查服務的狀態,可使用模塊async_status,傳遞job id,以下:
[root@ansible-server ~]# ansible web-nodes -m async_status -a "jid=488359678239.2844"

輪訓是內建的, 以下:
[root@ansible-server ~]# ansible web-nodes -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"

解釋說明:
參數-B表示運行最多30分鐘,30*60,-P 60 輪訓其狀態每60S,
當時間運行在-B參數後的時間以後,此服務會被中止運行。
可使用參數—forksvalue,來確保服務儘快運行

2)  ansible收集和查看相關信息, 用於過濾等

[root@ansible-server ~]# ansible all -m setup
[root@ansible-server ~]# ansible web-nodes -m setup
[root@ansible-server ~]# ansible 172.16.60.214 -m setup

3)  Ansible的委託、併發、任務超時

Ansible-playbook 併發運行async、poll, 即ansible的異步執行
ansible方便在於能批量下發,並返回結果和呈現。簡單、高效。但有的任務執行起來卻不那麼直接,可能會花比較長的時間,甚至可能會比ssh的超時時間還要長。這種狀況任務是否是無法執行了?
ansible考慮到了這種狀況,解決方法就是讓下發的任務執行的鏈接變爲異步:任務下發以後,長鏈接再也不保持,而是每隔一段時間輪詢結果,直到任務結束。這就須要在playbook的任務中加入兩個參數:async和poll。其中:
-> async參數值表明了這個任務執行時間的上限值。即任務執行所用時間若是超出這個時間,則認爲任務失敗。此參數若未設置,則爲同步執行。
-> poll參數值表明了任務異步執行時輪詢的時間間隔。

ansible默認只會建立5個進程,因此一次任務只能同時控制5臺機器執行,那若是你有大量的機器須要控制,或者你但願減小進程數,那你能夠採起異步執行。ansible的模塊能夠把task放進後臺,而後輪詢它.這使得在必定進程數下能讓大量須要的機器同時運做起來。使用async和poll這兩個關鍵字即可以並行運行一個任務。async這個關鍵字觸發ansible並行運做任務,而async的值是ansible等待運行這個任務的最大超時值,而poll就是ansible檢查這個任務是否完成的頻率時間。

1.  異步和輪詢
Ansible 有時候要執行等待時間很長的操做, 這個操做可能要持續很長時間,設置超過ssh的timeout,這時候你能夠在step中指定async 和 poll 來實現異步操做。
async 表示這個step的最長等待時長,若是設置爲0,表示一直等待下去直到動做完成。
poll 表示檢查step操做結果的間隔時長。

示例1

---
- name: Test
  hosts: localhost
  tasks:
    - name: wair for
      shell: sleep 16
      async: 10
      poll: 2

結果:
TASK: [wair for] ************************************************************** 
ok: [localhost]
<job 207388424975.101038> polling, 8s remaining
ok: [localhost]
<job 207388424975.101038> polling, 6s remaining
ok: [localhost]
<job 207388424975.101038> polling, 4s remaining
ok: [localhost]
<job 207388424975.101038> polling, 2s remaining
ok: [localhost]
<job 207388424975.101038> polling, 0s remaining
<job 207388424975.101038> FAILED on localhost

這個step失敗, 由於操做時間超過了最大等待時長

示例2

---
- name: Test
  hosts: localhost
  tasks:
    - name: wair for
      shell: sleep 16
      async: 10
      poll: 0

結果:
TASK: [wair for] ************************************************************** 
<job 621720484791.102116> finished on localhost

PLAY RECAP ********************************************************************

poll 設置爲0, 表示不用等待執行結果, 該step執行成功

示例3

---
- name: Test
  hosts: localhost
  tasks:
    - name: wair for
      shell: sleep 16
      async: 0
      poll: 10

結果:
# time ansible-playbook xiama.yml 
TASK: [wair for] ************************************************************** 
changed: [localhost]

PLAY RECAP ******************************************************************** 
localhost                  : ok=2    changed=1    unreachable=0    failed=0   


real    0m16.693s

async設置爲0, 會一直等待直到該操做完成.

2.  ansible-playbook執行時的併發限制
通常狀況下, ansible會同時在全部服務器上執行用戶定義的操做, 可是用戶能夠經過serial參數來定義同時能夠在多少太機器上執行操做。

- name: test play
  hosts: webservers
  serial: 3

webservers組中的3臺機器徹底完成play後, 其餘3臺機器纔會開始執行

serial參數在ansible-1.8之後就開始支持百分比

最大失敗百分比
默認狀況下, 只要group中還有server沒有失敗, ansible就是繼續執行tasks. 實際上, 用戶能夠經過"max_fail_percentage" 來定義, 只要超過max_fail_percentage臺的server失敗, ansible 就能夠停止tasks的執行:

- hosts: webservers
  max_fail_percentage: 30
  serial: 10

注意: 實際失敗機器必須大於這個百分比時, tasks纔會被停止. 等於時是不會停止tasks的

3.  委託
經過"delegate_to", 用戶能夠把某一個任務放在委託的機器上執行.

- hosts: webservers
  serial: 5

  tasks:

  - name: take out of load balancer pool
    command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

上面的task會在跑ansible的機器上執行, "delegate_to: 127.0.0.1" 能夠用local_action來代替:

  tasks:

  - name: take out of load balancer pool
    local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}

委託者的facts
默認狀況下, 委託任務的facts是inventory_hostname中主機的facts, 而不是被委託機器的facts。在ansible 2.0 中, 設置delegate_facts爲true可讓任務去收集被委託機器的facts

- hosts: app_servers
  tasks:
    - name: gather facts from db servers
      setup:
      delegate_to: "{{item}}"
      delegate_facts: True
      with_items: "{{groups[‘dbservers‘}}"

該例子會收集dbservers的facts並分配給這些機器, 而不會去收集app_servers的facts

RUN ONCE
經過run_once: true來指定該task只能在某一臺機器上執行一次. 能夠和delegate_to 結合使用

- command: /opt/application/upgrade_db.py
  run_once: true
  delegate_to: web01.example.org

指定在"web01.example.org"上執行這

若是沒有delegate_to, 那麼這個task會在第一臺機器上執行

相關文章
相關標籤/搜索