Ansible常用模塊介紹和使用
一、簡(jiǎn)介
前面我們介紹了,ansible能作為自動(dòng)化配置管理,其實(shí)是由ansible的多種多樣的模塊來(lái)實(shí)現(xiàn)的。截止目前,ansible的模塊已經(jīng)高達(dá)3000+之多。但是個(gè)人在日常工作中,比較常見(jiàn)的大約20多個(gè)。下面我就大概介紹一些常見(jiàn)常用的模塊。
二、invenroty清單文件
# cat /etc/ansible/hosts
[websrvs]
10.10.108.[30:33]
[dbsrvs]
10.10.108.30
[appsrvs]
10.10.108.[30:33]
三、常用模塊
3.1 ping 模塊
ping模塊執(zhí)行成功后,會(huì)給你返回綠色的消息,并且有一個(gè)pong響應(yīng)。all代表所有被管理的主機(jī)。
[root@ayunw ansible-example]# ansible dbsrvs -m ping
10.10.108.30 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@ayunw ansible-example]# ansible all -m ping
10.10.108.30 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.32 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.31 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.33 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
3.2 command 模塊
因?yàn)閍nsible的默認(rèn)模塊是command,所以這里可以使用 -m 指定模塊名 command,也可以直接省略。
[root@ayunw ansible-example]# ansible dbsrvs -m command -a "free -m"
10.10.108.30 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7821 395 7110 16 314 7179
Swap: 4095 0 4095
[root@ayunw ansible-example]# ansible dbsrvs -a "free -m"
10.10.108.30 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7821 395 7111 16 314 7179
Swap: 4095 0 4095
3.3 shell模塊
shell模塊和command模塊比較類(lèi)似,但是shell被大家稱(chēng)為萬(wàn)能模塊,很多操作command不支持,但是shell卻支持。注意最后一種情況shell模塊也是不支持的。但是可以將命令寫(xiě)在一個(gè)腳本,將腳本拷貝到遠(yuǎn)端執(zhí)行,然后執(zhí)行shell模塊獲取結(jié)果。
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "touch /tmp/a.txt"
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you need to use command because file is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
10.10.108.30 | CHANGED | rc=0 >>
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep 'a.txt'"
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Aug 9 09:37 a.txt
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep "a.txt""
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Aug 9 09:37 a.txt
# 會(huì)報(bào)錯(cuò),shell萬(wàn)能模塊也不支持這種方式
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/passwd |awk -F ':' '{print $1,$3}' >> /tmp/pwd.txt"
10.10.108.30 | FAILED | rc=1 >>
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ unexpected newline or end of stringnon-zero return code
注意: 你可能會(huì)注意到上面出現(xiàn)了WARNING?警告。這不是報(bào)錯(cuò),它只是告訴你,應(yīng)該選擇file?模塊進(jìn)行創(chuàng)建文件的操作會(huì)更好,而不是使用shell?模塊操作。當(dāng)然它還告訴你可以在ansible.cfg?配置文件中設(shè)置command_warnings=False以關(guān)閉警告。
3.4 copy 模塊
從ansible管理節(jié)點(diǎn)拷貝文件到遠(yuǎn)程主機(jī)。
[root@ayunw ansible-example]# cat getPasswd.sh
#!/bin/bash
# -*- Author -*- : ayunw
cat /etc/passwd |awk -F ':' '{print $1}'
[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=getPasswd.sh dest=/usr/local/src/ mode=0755 owner=root group=root"
10.10.108.30 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "ce9c09f15cb6f62b550f819276d06b0e6cd59110",
"dest": "/usr/local/src/getPasswd.sh",
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/usr/local/src/getPasswd.sh",
"secontext": "system_u:object_r:usr_t:s0",
"size": 54,
"state": "file",
"uid": 0
}
# 默認(rèn)目標(biāo)節(jié)點(diǎn)存在文件會(huì)覆蓋,所以最好設(shè)置 backup=yes
[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=getPasswd.sh dest=/usr/local/src/ mode=0755 owner=root group=root backup=yes"
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep 'getPasswd.sh'"
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 54 Aug 9 09:50 getPasswd.sh
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /tmp/getPasswd.sh"
10.10.108.30 | CHANGED | rc=0 >>
#!/bin/bash
cat /etc/passwd |awk -F ':' '{print $1}'
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "bash /usr/local/src/getPasswd.sh"
10.10.108.30 | CHANGED | rc=0 >>
root
bin
daemon
adm
lp
sync
shutdown
halt
operator
games
ftp
nobody
systemd-network
dbus
polkitd
sshd
postfix
# 拷貝目錄下所有文件到遠(yuǎn)程,不包括目錄本身。文件多了以后,速度會(huì)非常慢
[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=/etc/ansible/ dest=/opt/"
10.10.108.30 | CHANGED => {
"changed": true,
"dest": "/opt/",
"src": "/etc/ansible/"
}
3.5 fetch 模塊
從遠(yuǎn)程主機(jī)獲取文件到ansible管理節(jié)點(diǎn),但是不支持目錄操作
[root@ayunw ansible-example]# ansible dbsrvs -m fetch -a "src=/etc/yum.repos.d/epel.repo dest=/usr/local/src"
10.10.108.30 | CHANGED => {
"changed": true,
"checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
"dest": "/usr/local/src/10.10.108.30/etc/yum.repos.d/epel.repo",
"md5sum": "bddf35db56cf6be9190fdabeae71c801",
"remote_checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
"remote_md5sum": null
}
[root@ayunw ansible-example]# ls -al /usr/local/src/10.10.108.30/etc/yum.repos.d/
total 4
drwxr-xr-x. 2 root root 23 Aug 11 15:05 .
drwxr-xr-x. 3 root root 25 Aug 11 15:05 ..
-rw-r--r--. 1 root root 664 Aug 11 15:05 epel.repo
3.6 file 模塊
# 創(chuàng)建軟連接
[root@ayunw ansible-example]# ansible test -m file -a 'src=/etc/passwd path=/tmp/passwd.link state=link'
# 查看剛創(chuàng)建的/tmp下的軟連接
[root@ayunw ansible-example]# ansible all -m shell -a 'ls -l /tmp/passwd.link'
# 創(chuàng)建文件。如果文件已經(jīng)存在,則會(huì)更新文件的時(shí)間戳
[root@ayunw ansible-example]# ansible all -m file -a 'name=d.txt state=touch'
# 刪除文件
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/cc.txt state=absent'
# 創(chuàng)建目錄(可以遞歸創(chuàng)建,直接加上文件名即可)
# 如果state=directory,那么如果目錄不存在,那么所有的子目錄將被創(chuàng)建(而且提供權(quán)限的創(chuàng)建),如果目錄# 已經(jīng)存在,則不進(jìn)行任何操作。如果state=file,文件將不會(huì)被創(chuàng)建
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=directory'
# 刪除目錄(可以遞歸刪除,無(wú)需任何參數(shù),直接加上)
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=absent'
# 修改文件權(quán)限等屬性
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bb.txt mode=700 owner=root group=root'
# 遞歸授權(quán)目錄權(quán)限
ansible dbsrvs -m file -a "path=/data owner=bgx group=bgx recurse=yes"
3.7 hostname 模塊
管理遠(yuǎn)程主機(jī)上的主機(jī)名
# 查看主機(jī)名
[root@ayunw ansible-example]# ansible test -m shell -a 'hostname'
# 更改主機(jī)名
[root@ayunw ansible-example]# ansible test -m hostname -a 'name=master'
3.8 yum 模塊
# 安裝一個(gè)httpd服務(wù),默認(rèn)安裝最新版
# 使用state=present來(lái)安裝,多個(gè)包用','分割
[root@ansible-server ~]# ansible dbsrvs -m yum -a 'name=httpd'
[root@ayunw ansible-example]# ansible test -m yum -a 'name=httpd state=present'
# 檢查是否安裝成功
[root@ansible-server ~]# ansible dbsrvs -a 'rpm -qi httpd'
3.9 cron 模塊
# 創(chuàng)建計(jì)劃任務(wù)
[root@ayunw ansible-example]# ansible test -m cron -a 'minute=*/5 name=Ajob job="/usr/sbin/ntpdate 172.16.8.100 &> /dev/null" state=present'
[root@ayunw ansible-example]# ansible dbsrvs -m cron -a "minute=* hour=* day=* month=* weekday=* job='/bin/sh test.sh'"
[root@ayunw ansible-example]# ansible dbsrvs -m cron -a "job='/bin/sh /server/scripts/test.sh'"
# 設(shè)置定時(shí)任務(wù)注釋信息,防止重復(fù),name設(shè)定
ansible dbsrvs -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"
# 注釋相應(yīng)定時(shí)任務(wù),使定時(shí)任務(wù)失效
ansible dbsrvs -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh test.sh' disabled=yes"
# 刪除相應(yīng)定時(shí)任務(wù)(怎么創(chuàng)建的就要怎么刪除)
[root@ayunw ansible-example]# ansible test -m cron -a 'minute=*/5 name=Ajob job="/usr/sbin/ntpdate 172.16.8.100 &> /dev/null state=absent"'
# 查看計(jì)劃任務(wù)
[root@ayunw ansible-example]# ansible test -m shell -a "crontab -l"
172.16.20.115 | SUCCESS | rc=0 >>
#Ansible: Ajob
*/5 * * * * /usr/sbin/ntpdate 172.16.8.100 &> /dev/null
# 刪除任務(wù)計(jì)劃
[root@ayunw ansible-example]# ansible test -m shell -a "crontab -r"
3.10 service 模塊
用來(lái)管理服務(wù)器上的服務(wù)
# 利用ansible的yum模塊安裝一個(gè)nginx
[root@ayunw ansible-example]# ansible test -m yum -a 'name=nginx state=present'
# 啟動(dòng)nginx
[root@ayunw ansible-example]# ansible test -m shell -a '/etc/init.d/nginx start'
# 或者利用ansible的service模塊(推薦)
[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=started'
# 查看狀態(tài)
[root@ayunw ansible-example]# ansible test -m shell -a 'service nginx status'
[WARNING]: Consider using service module rather than running service
# 停止nginx服務(wù)
[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=stopped'
[root@ayunw ansible-example]# ansible test -m shell -a 'service nginx status'
[WARNING]: Consider using service module rather than running service
[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=started enabled=yes runlevel=2345'
[root@ayunw ansible-example]# ansible test -m shell -a 'chkconfig --list nginx'
3.11 group 模塊
用于添加遠(yuǎn)程主機(jī)上的組
[root@ayunw ansible-example]# ansible test -m group -a 'name=hr gid=2000 state=present'
3.12 user 模塊
管理遠(yuǎn)程主機(jī)上的用戶(hù)的賬號(hào)
# 創(chuàng)建用戶(hù)指定uid和gid,不創(chuàng)建家目錄也不允許登陸
ansible dbsrvs -m user -a "name=ayunw uid=888 group=888 shell=/sbin/nologin create_home=no"
[root@ayunw ansible-example]# ansible dbsrvs -m user -a 'name=martin group=hr groups=root uid=500 shell=/bin/bash home=/home/martin comment="martin user"'
# 刪除用戶(hù)
[root@ayunw ansible-example]# ansible dbsrvs -m user -a 'name=martin state=absent remove=yes'
# 給新創(chuàng)建的用戶(hù)生成ssh密鑰對(duì)
ansible dbsrvs -m user -a "name=oo uid=6677 group=adm generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" -i ./hosts
# 將明文密碼進(jìn)行hash加密,然后進(jìn)行用戶(hù)創(chuàng)建
ansible dbsrvs -m debug -a "msg={{ '123456' | password_hash('sha512', 'salt') }}"
3.13 setup 模塊
可收集遠(yuǎn)程主機(jī)的facts變量的信息,相當(dāng)于收集了目標(biāo)主機(jī)的相關(guān)信息(如內(nèi)核版本、操作系統(tǒng)信息、cpu、…),保存在ansible的內(nèi)置變量中,之后我們有需要用到時(shí),直接調(diào)用變量即可.這在ansible-playbook 中很有用。
[root@ayunw ansible-example]# ansible dbsrvs -m setup
# 使用setup獲取ip地址以及主機(jī)名使用filter過(guò)濾
ansible dbsrvs -m setup -a 'filter=ansible_default_ipv4'
# 獲取內(nèi)存信息
ansible dbsrvs -m setup -a 'filter=ansible_memory_mb'
# 獲取主機(jī)名
ansible dbsrvs -m setup -a 'filter=ansible_nodename'
# 僅顯示與ansible相關(guān)的內(nèi)存信息
ansible dbsrvs -m setup -a 'filter=ansible_*_mb'
3.14 authorized_key模塊
為特定的用戶(hù)賬號(hào)添加或刪除 SSH authorized keys
# 方法一
ansible web -m authorized_key -a "user=root key='{{lookup('file','/root/.ssh/id_rsa.pub')}}' path=/root/.ssh/authorized_keys manage_dir=no"
# 方法二、
vim pub_ssh_key.yml
---
- hosts: webs
remote_user: osmgr
become: yes
become_user: root
become_method: sudo
tasks:
- name: deliver authorized_keys
authorized_key:
user: osmgr
key: "{{ lookup('file', '/home/osmgr/.ssh/id_rsa.pub') }}"
state: present
ansible-playbook pub_ssh_key.yml
3.15 synchronize 模塊
使用rsync 模塊,系統(tǒng)必須安裝rsync 包,否則無(wú)法使用這個(gè)模塊
ansible dbsrvs -m shell -a 'yum -y install rsync'
ansible web -m synchronize -a 'src=time.sh dest=/tmp/'
3.16 lineinfile 模塊
正則匹配,更改某個(gè)關(guān)鍵參數(shù)值。比如這里修改SELINUX的值
ansible dbsrvs -a 'cat /etc/selinux/config | grep ^SELINUX='
ansible dbsrvs -m shell -a 'cat /etc/selinux/config|grep "^SELINUX="'
10.10.108.30 | CHANGED | rc=0 >>
SELINUX=enforcing
# 通過(guò)lineinfifle模塊修改SELinux的配置信息,改為disable
ansible dbsrvs -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"
# 或者是使用ansible-playbook
vim set_selinux_disable.yml
---
- hosts: dbsrvs
tasks:
- name: seline modify enforcing
lineinfile:
dest: /etc/selinux/config
regexp: '^SELINUX='
line: 'SELINUX=enforcing'
# 刪除/etc/fstab文件中以#號(hào)開(kāi)頭的行
ansible dbsrvs -m lineinfile -a "dest=/etc/fstab state=absent regexp='^#'"
3.17 replace 模塊
和 sed 命令比較類(lèi)似,用于正則匹配和替換
# 查看遠(yuǎn)端節(jié)點(diǎn)的 /etc/fstab 源文件
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue Jul 5 14:09:37 2022
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
# 使用replace模塊
[root@ayunw ansible-example]# ansible dbsrvs -m replace -a "path=/etc/fstab regexp=^(UUID.*) replace='#\1'"
10.10.108.30 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"msg": "1 replacements made"
}
# 查看結(jié)果
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue Jul 5 14:09:37 2022
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
#UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
# 將注釋的UUID信息恢復(fù)
ansible dbsrvs -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>
/etc/fstab
Created by anaconda on Tue Jul 5 14:09:37 2022
Accessible filesystems, by reference, are maintained under '/dev/disk'
See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
/dev/mapper/centos-root / xfs defaults 0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
參數(shù)說(shuō)明:
- \1:表示引用前面的小括號(hào)內(nèi)容