日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > linux >内容正文

linux

LinuxProbe 0x21 使用Ansible服务实现自动化运维

發(fā)布時間:2024/3/13 linux 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LinuxProbe 0x21 使用Ansible服务实现自动化运维 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Ansible是最近幾年特別火的一款開源運(yùn)維自動化工具,它能夠幫助運(yùn)維人員肉眼可見地提高工作效率,并減少人為失誤。Ansible有上千個功能豐富且實(shí)用的模塊,而且有詳盡的幫助信息可供查閱,因此即便是小白用戶也可以輕松上手。

  • Ansible介紹與安裝

Ansible目前是運(yùn)維自動化工具中最簡單、容易上手的一款優(yōu)秀軟件,能夠用來管理各種資源。

可以使用Ansible自動部署應(yīng)用程序,以此實(shí)現(xiàn)IT基礎(chǔ)架構(gòu)的全面部署。

例如,借助于Ansible,可以輕松地對服務(wù)器進(jìn)行初始化配置、安全基線配置,以及進(jìn)行更新和打補(bǔ)丁操作。

相較于Chef、Puppet、SaltStack等C/S(客戶端/服務(wù)器)架構(gòu)的自動化工具來講,盡管Ansible的性能并不是最好的,但由于它基于SSH遠(yuǎn)程會話協(xié)議,不需要客戶端程序,只要知道受管主機(jī)的賬號密碼,就能直接用SSH協(xié)議進(jìn)行遠(yuǎn)程控制,因此使用起來優(yōu)勢明顯。

?

Ansible服務(wù)本身并沒有批量部署的功能,它僅僅是一個框架,真正具有批量部署能力的是其所運(yùn)行的模塊。

Ansible內(nèi)置的模塊非常豐富,幾乎可以滿足一切需求,使用起來也非常簡單,一條命令甚至影響上千臺主機(jī)。

如果需要更高級的功能,也可以運(yùn)用Python語言對Ansible進(jìn)行二次開發(fā)。

?Ansible服務(wù)專用術(shù)語對照表

術(shù)語

中文叫法

含義

Control node

控制節(jié)點(diǎn)

指的是安裝了Ansible服務(wù)的主機(jī),也被稱為Ansible控制端,主要是用來發(fā)布運(yùn)行任務(wù)、調(diào)用功能模塊,對其他主機(jī)進(jìn)行批量控制。

Managed nodes

受控節(jié)點(diǎn)

指的是被Ansible服務(wù)所管理的主機(jī),也被稱為受控主機(jī)或客戶端,是模塊命令的被執(zhí)行對象。

Inventory

主機(jī)清單

指的是受控節(jié)點(diǎn)的列表,可以是IP地址、主機(jī)名稱或者域名。

Modules

模塊

指的是上文提到的特定功能代碼,默認(rèn)自帶有上千款功能模塊,在Ansible Galaxy有超多可供選擇。

Task

任務(wù)

指的是Ansible客戶端上面要被執(zhí)行的操作。

Playbook

劇本

指的是通過YAML語言編寫的可重復(fù)執(zhí)行的任務(wù)列表,把常做的操作寫入到劇本文件中,下次可以直接重復(fù)執(zhí)行一遍。

Roles

角色

從Ansible 1.2版本開始引入的新特性,用于結(jié)構(gòu)化的組織Playbook,通過調(diào)用角色實(shí)現(xiàn)一連串的功能。

由于受控節(jié)點(diǎn)不需要安裝客戶端,外加SSH協(xié)議是Linux系統(tǒng)的標(biāo)配,因此可以直接通過SSH協(xié)議進(jìn)行遠(yuǎn)程控制。在控制節(jié)點(diǎn)上,也不用每次都重復(fù)開啟服務(wù)程序,使用ansible命令直接調(diào)用模塊進(jìn)行控制即可。

RHEL 8系統(tǒng)的鏡像文件默認(rèn)不帶有Ansible服務(wù)程序,需要從Extra Packages for Enterprise?Linux(EPEL)擴(kuò)展軟件包倉庫獲取。EPEL軟件包倉庫由紅帽公司提供,是一個用于創(chuàng)建、維護(hù)和管理企業(yè)版Linux的高質(zhì)量軟件擴(kuò)展倉庫,通用于RHEL、CentOS、Oracle Linux等多種紅帽系企業(yè)版系統(tǒng),目的是對于默認(rèn)系統(tǒng)倉庫軟件包進(jìn)行擴(kuò)展。

下面準(zhǔn)備在系統(tǒng)上部署Ansible服務(wù)程序。

第1步:在“虛擬機(jī)設(shè)置”界面中,將“網(wǎng)絡(luò)適配器”的“網(wǎng)絡(luò)連接”選項(xiàng)調(diào)整為“橋接模式”,并將系統(tǒng)的網(wǎng)卡設(shè)置成“Automatic(DHCP)”模式

?

[root@localhost ~]# ping www.baidu.com -c 4 PING www.baidu.com (180.101.49.11) 56(84) bytes of data. 64 bytes from 180.101.49.11 (180.101.49.11): icmp_seq=1 ttl=52 time=24.7 ms 64 bytes from 180.101.49.11 (180.101.49.11): icmp_seq=2 ttl=52 time=96.6 ms 64 bytes from 180.101.49.11 (180.101.49.11): icmp_seq=3 ttl=52 time=16.2 ms 64 bytes from 180.101.49.11 (180.101.49.11): icmp_seq=4 ttl=52 time=16.6 ms--- www.baidu.com ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 173ms rtt min/avg/max/mdev = 16.173/38.527/96.608/33.703 ms [root@localhost ~]#

第2步:在原有軟件倉庫配置的下方,追加EPEL擴(kuò)展軟件包安裝源的信息。

[root@localhost ~]# ls /etc/yum.repos.d/ redhat.repo rhel8.repo [root@localhost ~]# vim /etc/yum.repos.d/rhel8.repo [BaseOS] name=BaseOS baseurl=file:///media/cdrom/BaseOS enabled=1 gpgcheck=0[AppStream] name=AppStream baseurl=file:///media/cdrom/AppStream enabled=1 gpgcheck=0[EPEL] name=EPEL baseurl=https://dl.fedoraproject.org/pub/epel/8/Everything/x86_64/ enabled=1 gpgcheck=0 [root@localhost ~]#

第3步:安裝!

[root@localhost ~]# dnf install -y ansible Updating Subscription Management repositories. Unable to read consumer identity This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. AppStream 351 kB/s | 3.2 kB 00:00 BaseOS 184 kB/s | 2.7 kB 00:00 EPEL 479 kB/s | 10 MB 00:21 Dependencies resolved. ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: ansible noarch 2.9.24-1.el8 EPEL 17 M Installing dependencies: python3-babel noarch 2.5.1-3.el8 AppStream 4.8 M python3-jinja2 noarch 2.10-9.el8 AppStream 537 k python3-jmespath noarch 0.9.0-11.el8 AppStream 45 k python3-markupsafe x86_64 0.23-19.el8 AppStream 39 k python3-pyasn1 noarch 0.3.7-6.el8 AppStream 126 k libsodium x86_64 1.0.18-2.el8 EPEL 162 k python3-bcrypt x86_64 3.1.6-2.el8.1 EPEL 44 k python3-pynacl x86_64 1.3.0-5.el8 EPEL 100 k sshpass x86_64 1.06-9.el8 EPEL 27 k Installing weak dependencies: python3-paramiko noarch 2.4.3-1.el8 EPEL 289 kTransaction Summary ================================================================================ Install 11 PackagesTotal size: 23 M Total download size: 18 M Installed size: 122 M Downloading Packages: (1/6): python3-bcrypt-3.1.6-2.el8.1.x86_64.rpm 18 kB/s | 44 kB 00:02 (2/6): libsodium-1.0.18-2.el8.x86_64.rpm 52 kB/s | 162 kB 00:03 (3/6): python3-pynacl-1.3.0-5.el8.x86_64.rpm 37 kB/s | 100 kB 00:02 (4/6): sshpass-1.06-9.el8.x86_64.rpm 103 kB/s | 27 kB 00:00 (5/6): python3-paramiko-2.4.3-1.el8.noarch.rpm 60 kB/s | 289 kB 00:04 (6/6): ansible-2.9.24-1.el8.noarch.rpm 529 kB/s | 17 MB 00:32 -------------------------------------------------------------------------------- Total 548 kB/s | 18 MB 00:32 Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transactionPreparing : 1/1Installing : sshpass-1.06-9.el8.x86_64 1/11Installing : python3-bcrypt-3.1.6-2.el8.1.x86_64 2/11Installing : libsodium-1.0.18-2.el8.x86_64 3/11Installing : python3-pynacl-1.3.0-5.el8.x86_64 4/11Installing : python3-pyasn1-0.3.7-6.el8.noarch 5/11Installing : python3-paramiko-2.4.3-1.el8.noarch 6/11Installing : python3-markupsafe-0.23-19.el8.x86_64 7/11Installing : python3-jmespath-0.9.0-11.el8.noarch 8/11Installing : python3-babel-2.5.1-3.el8.noarch 9/11Installing : python3-jinja2-2.10-9.el8.noarch 10/11Installing : ansible-2.9.24-1.el8.noarch 11/11Running scriptlet: ansible-2.9.24-1.el8.noarch 11/11Verifying : python3-babel-2.5.1-3.el8.noarch 1/11Verifying : python3-jinja2-2.10-9.el8.noarch 2/11Verifying : python3-jmespath-0.9.0-11.el8.noarch 3/11Verifying : python3-markupsafe-0.23-19.el8.x86_64 4/11Verifying : python3-pyasn1-0.3.7-6.el8.noarch 5/11Verifying : ansible-2.9.24-1.el8.noarch 6/11Verifying : libsodium-1.0.18-2.el8.x86_64 7/11Verifying : python3-bcrypt-3.1.6-2.el8.1.x86_64 8/11Verifying : python3-paramiko-2.4.3-1.el8.noarch 9/11Verifying : python3-pynacl-1.3.0-5.el8.x86_64 10/11Verifying : sshpass-1.06-9.el8.x86_64 11/11 Installed products updated.Installed:ansible-2.9.24-1.el8.noarch python3-paramiko-2.4.3-1.el8.noarch python3-babel-2.5.1-3.el8.noarch python3-jinja2-2.10-9.el8.noarch python3-jmespath-0.9.0-11.el8.noarch python3-markupsafe-0.23-19.el8.x86_64 python3-pyasn1-0.3.7-6.el8.noarch libsodium-1.0.18-2.el8.x86_64 python3-bcrypt-3.1.6-2.el8.1.x86_64 python3-pynacl-1.3.0-5.el8.x86_64 sshpass-1.06-9.el8.x86_64 Complete! [root@localhost ~]#

安裝完畢后,Ansible服務(wù)便默認(rèn)已經(jīng)啟動。使用--version參數(shù)可以看到Ansible服務(wù)的版本及配置信息。

[root@localhost ~]# ansible --version ansible 2.9.25config file = /etc/ansible/ansible.cfgconfigured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']ansible python module location = /usr/lib/python3.6/site-packages/ansibleexecutable location = /usr/bin/ansiblepython version = 3.6.8 (default, Jan 11 2019, 02:17:16) [GCC 8.2.1 20180905 (Red Hat 8.2.1-3)] [root@localhost ~]#

  • 設(shè)置主機(jī)清單

Ansible服務(wù)的主配置文件存在優(yōu)先級的順序關(guān)系,默認(rèn)存放在/etc/ansible目錄中的主配置文件優(yōu)先級最低。如果在當(dāng)前目錄或用戶家目錄中也存放著一份主配置文件,則以當(dāng)前目錄或用戶家目錄中的主配置文件為主。同時存在多個Ansible服務(wù)主配置文件時,

Ansible服務(wù)主配置文件優(yōu)先級順序

優(yōu)先級

文件位置

./ansible.cfg

~/.ansible.cfg

/etc/ansible/ansible.cfg

Ansible服務(wù)是用于實(shí)現(xiàn)主機(jī)批量自動化控制的管理工具,可以把要管理的主機(jī)IP地址預(yù)先寫入主機(jī)清單文件(/etc/ansible/hosts),這樣后續(xù)再通過執(zhí)行ansible命令來執(zhí)行任務(wù)時就自動包含這些主機(jī)了

?測試受管主機(jī)信息

操作系統(tǒng)

IP地址

功能用途

RHEL 8

192.168.10.20

dev

RHEL 8

192.168.10.30

test

將測試主機(jī)寫入到主機(jī)清單文件中,并將主機(jī)進(jìn)行分組,主機(jī)清單文件在修改后會立即生效,一般使用“ansible-inventory --graph”命令以結(jié)構(gòu)化的方式顯示出受管主機(jī)的信息。

[root@localhost ~]# vim /etc/ansible/hosts [dev] 192.168.10.20 [test] 192.168.10.30 [root@localhost ~]# ansible-inventory --graph @all:|--@dev:| |--192.168.10.20|--@test:| |--192.168.10.30|--@ungrouped: [root@localhost ~]#

Ansible常用變量匯總

參數(shù)

作用

ansible_ssh_host

受管主機(jī)名

ansible_ssh_port

端口號

ansible_ssh_user

默認(rèn)賬號

ansible_ssh_pass

默認(rèn)密碼

ansible_shell_type

Shell終端類型

? 再次配置主機(jī)清單文件,使其登錄各主機(jī)時自動登錄,因測試主機(jī)密碼都一樣,可以使用all統(tǒng)一配置。

[root@localhost ~]# cat /etc/ansible/hosts [dev] 192.168.10.20 [test] 192.168.10.30 [root@localhost ~]# vim /etc/ansible/hosts [root@localhost ~]# cat /etc/ansible/hosts [dev] 192.168.10.20 [test] 192.168.10.30 [all:vars] ansible_user=root ansible_password=123456 [root@localhost ~]#

將Ansible主配置文件中的第71行設(shè)置成默認(rèn)不需要SSH協(xié)議的指紋驗(yàn)證,以及將第107行設(shè)置成默認(rèn)執(zhí)行劇本時所使用的管理員名稱為root

[root@localhost ~]# vim /etc/ansible/ansible.cfg ... 70 # uncomment this to disable SSH key host checking - 71 #host_key_checking = False + 71 host_key_checking = False 72 73 # change the default callback, you can only have one 'stdout' type enabled at a time. ... 106 # (/usr/bin/ansible will use current user as default) - 107 #remote_user = root + 107 remote_user = root 108 109 # logging is off by default unless this path is defined [root@localhost ~]#

不需要重啟服務(wù),在以上操作完全搞定后就可以開始后面的實(shí)驗(yàn)了。

由于剛才是將Ansible服務(wù)器設(shè)置成了橋接及DHCP模式,現(xiàn)在將網(wǎng)絡(luò)適配器修改回“僅主機(jī)模式”以及192.168.10.10/24的IP地址。在修改完成后重啟網(wǎng)卡,然后執(zhí)行ping操作,測試?192.168.10.20、192.168.10.30?通信。

[root@localhost ~]# ifconfig ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 192.168.0.133 netmask 255.255.255.0 broadcast 192.168.0.255inet6 fe80::a7bc:9261:b95:a2f6 prefixlen 64 scopeid 0x20<link>ether 00:0c:29:4a:53:0b txqueuelen 1000 (Ethernet)RX packets 10650 bytes 12302250 (11.7 MiB)RX errors 0 dropped 0 overruns 0 frame 0TX packets 2147 bytes 170750 (166.7 KiB)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536inet 127.0.0.1 netmask 255.0.0.0inet6 ::1 prefixlen 128 scopeid 0x10<host>loop txqueuelen 1000 (Local Loopback)RX packets 48 bytes 4608 (4.5 KiB)RX errors 0 dropped 0 overruns 0 frame 0TX packets 48 bytes 4608 (4.5 KiB)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255ether 52:54:00:53:93:e3 txqueuelen 1000 (Ethernet)RX packets 0 bytes 0 (0.0 B)RX errors 0 dropped 0 overruns 0 frame 0TX packets 0 bytes 0 (0.0 B)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0[root@localhost ~]# ifconfig ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 192.168.10.10 netmask 255.255.255.0 broadcast 192.168.10.255inet6 fe80::a7bc:9261:b95:a2f6 prefixlen 64 scopeid 0x20<link>ether 00:0c:29:4a:53:0b txqueuelen 1000 (Ethernet)RX packets 10723 bytes 12309131 (11.7 MiB)RX errors 0 dropped 0 overruns 0 frame 0TX packets 2222 bytes 179074 (174.8 KiB)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536inet 127.0.0.1 netmask 255.0.0.0inet6 ::1 prefixlen 128 scopeid 0x10<host>loop txqueuelen 1000 (Local Loopback)RX packets 83 bytes 8112 (7.9 KiB)LinuxProbe 0x17 DHCP動態(tài)管理主機(jī)地址、電子郵件系統(tǒng)RX errors 0 dropped 0 overruns 0 frame 0TX packets 83 bytes 8112 (7.9 KiB)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255ether 52:54:00:53:93:e3 txqueuelen 1000 (Ethernet)RX packets 0 bytes 0 (0.0 B)RX errors 0 dropped 0 overruns 0 frame 0TX packets 0 bytes 0 (0.0 B)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0[root@localhost ~]# [root@localhost ~]# ping 192.168.10.20 -c 4 PING 192.168.10.20 (192.168.10.20) 56(84) bytes of data. 64 bytes from 192.168.10.20: icmp_seq=1 ttl=64 time=0.749 ms 64 bytes from 192.168.10.20: icmp_seq=2 ttl=64 time=0.669 ms 64 bytes from 192.168.10.20: icmp_seq=3 ttl=64 time=0.574 ms 64 bytes from 192.168.10.20: icmp_seq=4 ttl=64 time=0.539 ms--- 192.168.10.20 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 97ms rtt min/avg/max/mdev = 0.539/0.632/0.749/0.087 ms [root@localhost ~]# ping 192.168.10.30 -c 4 PING 192.168.10.30 (192.168.10.30) 56(84) bytes of data. 64 bytes from 192.168.10.30: icmp_seq=1 ttl=64 time=0.893 ms 64 bytes from 192.168.10.30: icmp_seq=2 ttl=64 time=97.0 ms 64 bytes from 192.168.10.30: icmp_seq=3 ttl=64 time=1.00 ms 64 bytes from 192.168.10.30: icmp_seq=4 ttl=64 time=0.459 ms--- 192.168.10.30 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 18ms rtt min/avg/max/mdev = 0.459/24.845/97.030/41.676 ms [root@localhost ~]#

  • 運(yùn)行臨時命令

Ansible服務(wù)的強(qiáng)大之處在于只需要一條命令,便可以操控成千上萬臺的主機(jī)節(jié)點(diǎn),而ansible命令便是最得力的工具之一。

可以使用“ansible-doc模塊名稱”的命令格式查詢使用方法 ,或是使用ansibe-doc -l命令列出所有的模塊信息以供選擇。

Ansible服務(wù)常用模塊名稱及作用?? ?

模塊名稱

模塊作用

ping

檢查受管節(jié)點(diǎn)主機(jī)網(wǎng)絡(luò)是否能夠聯(lián)通。

yum

安裝、更新及卸載軟件包。

yum_repository

管理主機(jī)的軟件倉庫配置文件。

template

復(fù)制模板文件到受管節(jié)點(diǎn)主機(jī)。

copy

新建、修改及復(fù)制文件。

user

創(chuàng)建、修改及刪除用戶。

group

創(chuàng)建、修改及刪除用戶組。

service

啟動、關(guān)閉及查看服務(wù)狀態(tài)。

get_url

從網(wǎng)絡(luò)中下載文件。

file

設(shè)置文件權(quán)限及創(chuàng)建快捷方式。

cron

添加、修改及刪除計(jì)劃任務(wù)。

command

直接執(zhí)行用戶指定的命令。

shell

直接執(zhí)行用戶指定的命令(支持特殊字符)。

debug

輸出調(diào)試或報(bào)錯信息。

mount

掛載硬盤設(shè)備文件。

filesystem

格式化硬盤設(shè)備文件。

lineinfile

通過正則表達(dá)式修改文件內(nèi)容。

setup

收集受管節(jié)點(diǎn)主機(jī)上的系統(tǒng)及變量信息。

firewalld

添加、修改及刪除防火墻策略。

lvg

管理主機(jī)的物理卷及卷組設(shè)備。

lvol

管理主機(jī)的邏輯卷設(shè)備。

在Ansible服務(wù)中,ansible是用于執(zhí)行臨時任務(wù)的命令,也就在是執(zhí)行后即結(jié)束(與劇本文件的可重復(fù)執(zhí)行不同)。

在使用ansible命令時,必須指明受管主機(jī)的信息,如果已經(jīng)設(shè)置過主機(jī)清單文件(/etc/ansible/hosts),則可以使用all參數(shù)來指代全體受管主機(jī),或是用dev、test等主機(jī)組名稱來指代某一組的主機(jī)。

ansible命令常用的語法格式為“ansible受管主機(jī)節(jié)點(diǎn) -m模塊名稱[-a模塊參數(shù)]”。

其中,-a是要傳遞給模塊的參數(shù),只有功能極其簡單的模塊才不需要額外參數(shù),所以大多情況下-m與-a參數(shù)都會同時出現(xiàn)。

? ?ansible命令常用參數(shù)

參數(shù)

作用

-k

手動輸入SSH協(xié)議密碼

-i

指定主機(jī)清單文件

-m

指定要使用的模塊名

-M

指定要使用的模塊路徑

-S

使用su命令

-T

設(shè)置SSH協(xié)議連接超時時間

-a

設(shè)置傳遞給模塊的參數(shù)

--version

查看版本信息

-h

幫助信息

如果想實(shí)現(xiàn)某個功能,但是卻不知道用什么模塊,又或者是知道了模塊名稱,但不清楚模塊具體的作用,則建議使用ansible-doc命令進(jìn)行查找。

例:列舉出當(dāng)前Ansible服務(wù)所支持的所有模塊信息

[root@localhost ~]# ansible-doc -l a10_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object a10_server_axapi3 Manage A10 Networks AX/SoftAX/Thunder/vThunder devices a10_service_group Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups a10_virtual_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers aci_aaa_user Manage AAA users (aaa:User) aci_aaa_user_certificate Manage AAA user certificates (aaa:UserCert) aci_access_port_block_to_access_port Manage port blocks of Fabric interface policy leaf profile interface sele... aci_access_port_to_interface_policy_leaf_profile Manage Fabric interface policy leaf profile interface selectors (infra:HP... aci_access_sub_port_block_to_access_port Manage sub port blocks of Fabric interface policy leaf profile interface ... aci_aep Manage attachable Access Entity Profile (AEP) objects (infra:AttEntityP, ... aci_aep_to_domain Bind AEPs to Physical or Virtual Domains (infra:RsDomP) aci_ap Manage top level Application Profile (AP) objects (fv:Ap) aci_bd Manage Bridge Domains (BD) objects (fv:BD) aci_bd_subnet Manage Subnets (fv:Subnet) aci_bd_to_l3out Bind Bridge Domain to L3 Out (fv:RsBDToOut) aci_config_rollback Provides rollback and rollback preview functionality (config:ImportP) aci_config_snapshot Manage Config Snapshots (config:Snapshot, config:ExportP) aci_contract Manage contract resources (vz:BrCP) aci_contract_subject Manage initial Contract Subjects (vz:Subj) aci_contract_subject_to_filter Bind Contract Subjects to Filters (vz:RsSubjFiltAtt) aci_domain Manage physical, virtual, bridged, routed or FC domain profiles (phys:Dom... aci_domain_to_encap_pool Bind Domain to Encap Pools (infra:RsVlanNs) aci_domain_to_vlan_pool Bind Domain to VLAN Pools (infra:RsVlanNs) aci_encap_pool Manage encap pools (fvns:VlanInstP, fvns:VxlanInstP, fvns:VsanInstP) aci_encap_pool_range Manage encap ranges assigned to pools (fvns:EncapBlk, fvns:VsanEncapBlk) aci_epg Manage End Point Groups (EPG) objects (fv:AEPg) aci_epg_monitoring_policy Manage monitoring policies (mon:EPGPol) aci_epg_to_contract Bind EPGs to Contracts (fv:RsCons, fv:RsProv) aci_epg_to_domain Bind EPGs to Domains (fv:RsDomAtt) aci_fabric_node Manage Fabric Node Members (fabric:NodeIdentP) aci_fabric_scheduler This modules creates ACI schedulers aci_filter Manages top level filter objects (vz:Filter) aci_filter_entry Manage filter entries (vz:Entry) aci_firmware_group This module creates a firmware group aci_firmware_group_node This modules adds and remove nodes from the firmware group aci_firmware_policy This creates a firmware policy : ...

?按?q?退出

ansible-doc命令會在屏幕上顯示出這個模塊的作用、可用參數(shù)及實(shí)例等信息

[root@localhost ~]# ansible-doc a10_server > A10_SERVER (/usr/lib/python3.6/site-packages/ansible/modules/network/a10/a>Manage SLB (Server Load Balancer) server objects on A10Networks devices via aXAPIv2.* This module is maintained by The Ansible Community OPTIONS (= is mandatory):- client_certPEM formatted certificate chain file to be used for SSL clientauthentication.This file can also include the key as well, and if the key isincluded, `client_key' is not required.[Default: (null)]type: path- client_key ...

檢查一下這些主機(jī)的網(wǎng)絡(luò)連通性。

ping模塊用于進(jìn)行簡單的網(wǎng)絡(luò)測試(類似于常用的ping命令)。

可以使用ansible命令直接針對所有主機(jī)調(diào)用ping模塊,不需要增加額外的參數(shù),返回值若為SUCCESS,則表示主機(jī)當(dāng)前在線。

[root@localhost ~]# ansible all -m ping 192.168.10.20 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false,"ping": "pong" } 192.168.10.30 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false,"ping": "pong" } [root@localhost ~]#

除了使用-m參數(shù)直接指定模塊名稱之外,還可以用-a參數(shù)將參數(shù)傳遞給模塊,讓模塊的功能更高級,更好地滿足當(dāng)前生產(chǎn)的需求。

例如,yum_repository模塊的作用是管理主機(jī)的軟件倉庫,能夠添加、修改及刪除軟件倉庫的配置信息,參數(shù)相對比較復(fù)雜。遇到這種情況時,建議先用ansible-doc命令對其進(jìn)行了解。尤其是下面的EXAMPLES結(jié)構(gòu)段會有該模塊的實(shí)例,對用戶來說有非常高的參考價值。

[root@localhost ~]# ansible-doc yum_repository > YUM_REPOSITORY (/usr/lib/python3.6/site-packages/ansible/modules/packaging>Add or remove YUM repositories in RPM-based Linuxdistributions. If you wish to update an existing repositorydefinition use [ini_file] instead.* This module is maintained by The Ansible Core Team OPTIONS (= is mandatory):- asyncIf set to `yes' Yum will download packages and metadata fromthis repo in parallel, if possible.[Default: yes]type: bool- attributesThe attributes the resulting file or directory should have.To get supported flags look at the man page for `chattr' onthe target system.This string should contain the attributes in the same order asthe one displayed by `lsattr'.The `=' operator is assumed as default, otherwise `+' or `-'operators need to be included in the string. [root@localhost ~]#

例:? 為主機(jī)清單中的所有服務(wù)器新增一個軟件倉庫,

新增軟件倉庫信息

倉庫名稱

EX294_BASE

倉庫描述

EX294 base software

倉庫地址

file:///media/cdrom/BaseOS

GPG簽名

啟用

GPG密鑰文件

file:///media/cdrom/RPM-GPG-KEY-redhat-release

可以對照著EXAMPLE實(shí)例段,逐一對應(yīng)填寫需求值和參數(shù),其標(biāo)準(zhǔn)格式是在-a參數(shù)后接整體參數(shù)(用單引號圈起),而各個參數(shù)字段的值則用雙引號圈起。這是最嚴(yán)謹(jǐn)?shù)膶懛ā?/p>

在執(zhí)行下述命令后如果出現(xiàn)CHANGED字樣,則表示修改已經(jīng)成功:

[root@localhost ~]# ansible all -m yum_repository -a 'name="EX294_BASE" description="EX294 base software" baseurl="file:///media/cdrom/BaseOS" gpgcheck=yes enabled=1' 192.168.10.20 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": true,"repo": "EX294_BASE","state": "present" } 192.168.10.30 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": true,"repo": "EX294_BASE","state": "present" } [root@localhost ~]#

在命令執(zhí)行成功后,可以到主機(jī)清單中的任意機(jī)器上查看新建成功的軟件倉庫配置文件。

[ 192.168.10.20 ]

[root@localhost ~]# cd /etc/yum.repos.d/ [root@localhost yum.repos.d]# ls EX294_BASE.repo redhat.repo rhel8.repo [root@localhost yum.repos.d]# cat EX294_BASE.repo [EX294_BASE] baseurl = file:///media/cdrom/BaseOS enabled = 1 gpgcheck = 1 name = EX294 base software[root@localhost yum.repos.d]#

  • 劇本文件實(shí)戰(zhàn)

Ansible服務(wù)允許用戶根據(jù)需求,在類似于Shell腳本的模式下編寫自動化運(yùn)維腳本,然后由程序自動、重復(fù)地執(zhí)行,從而大大提高了工作效率。

Ansible服務(wù)的劇本(playbook)文件采用YAML語言編寫,具有強(qiáng)制性的格式規(guī)范,它通過空格將不同信息分組,因此有時會因一兩個空格錯位而導(dǎo)致報(bào)錯。

YAML文件的開頭需要先寫3個減號(---),多個分組的信息需要間隔一致才能執(zhí)行,而且上下也要對齊,后綴名一般為.yml。

劇本文件在執(zhí)行后,會在屏幕上輸出運(yùn)行界面,內(nèi)容會根據(jù)工作的不同而變化。在運(yùn)行界面中,綠色表示成功,黃色表示執(zhí)行成功并進(jìn)行了修改,而紅色則表示執(zhí)行失敗。

劇本文件的結(jié)構(gòu)由4部分組成,分別是target、variable、task、handler,其各自的作用如下。

target:用于定義要執(zhí)行劇本的主機(jī)范圍。

variable:用于定義劇本執(zhí)行時要用到的變量。

task:用于定義將在遠(yuǎn)程主機(jī)上執(zhí)行的任務(wù)列表。

handler:用于定義執(zhí)行完成后需要調(diào)用的后續(xù)任務(wù)。

YAML語言編寫的Ansible劇本文件會按照從上到下的順序自動運(yùn)行,格式有嚴(yán)格的要求。

例如,創(chuàng)建一個名為packages.yml的劇本,讓dev、test組的主機(jī)可以自動安裝數(shù)據(jù)庫軟件,并且將dev組主機(jī)的軟件更新至最新。

安裝和更新軟件需要使用yum模塊。先看一下幫助信息中的示例吧:?

[root@localhost ~]# ansible-doc yum > YUM (/usr/lib/python3.6/site-packages/ansible/modules/packaging/os/yum.py)Installs, upgrade, downgrades, removes, and lists packages andgroups with the `yum' package manager. This module only workson Python 2. If you require Python 3 support see the [dnf]module.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.OPTIONS (= is mandatory):- allow_downgradeSpecify if the named package and version is allowed todowngrade a maybe already installed higher version of thatpackage. Note that setting allow_downgrade=True can make thismodule behave in a non-idempotent way. The task could end upwith a set of packages that does not match the complete listof specified packages to install (because dependencies betweenthe downgraded package and others can cause changes to thepackages which were in the earlier transaction).[Default: no]type: bool ...

在知道yum模塊的使用方法和格式后,就可以開始編寫劇本了。初次編寫劇本文件時,務(wù)必看準(zhǔn)格式,模塊及play(動作)格式也要上下對齊,否則會出現(xiàn)“參數(shù)一模一樣,但不能執(zhí)行”的情況。

[root@localhost ~]# vim packages.yml [root@localhost ~]# cat packages.yml --- - name: 安裝軟件包hosts: dev,testtasks:- name: oneyum:name: mariadbstate: latest [root@localhost ~]#

其中,

name字段表示此項(xiàng)play(動作)的名字,用于在執(zhí)行過程中提示用戶執(zhí)行到了哪一步,以及幫助管理員在日后閱讀時能想起這段代碼的作用。

hosts字段表示要在哪些主機(jī)上執(zhí)行該劇本,多個主機(jī)組之間用逗號間隔;如果需要對全部主機(jī)進(jìn)行操作,則使用all參數(shù)。

tasks字段用于定義要執(zhí)行的任務(wù),每個任務(wù)都要有一個獨(dú)立的name字段進(jìn)行命名,并且每個任務(wù)的name字段和模塊名稱都要嚴(yán)格上下對齊,參數(shù)要單獨(dú)縮進(jìn)。

在編寫Ansible劇本文件時,RHEL 8系統(tǒng)自帶的Vim編輯器具有自動縮進(jìn)功能,這可以給我們提供很多幫助。在確認(rèn)無誤后就可以用ansible-playbook命令運(yùn)行這個劇本文件了。

[root@localhost ~]# ansible-playbook packages.ymlPLAY [安裝軟件包] *******************************************************************************TASK [Gathering Facts] ********************************************************************* ok: [192.168.10.20] ok: [192.168.10.30]TASK [one] ********************************************************************************* changed: [192.168.10.20] changed: [192.168.10.30]PLAY RECAP ********************************************************************************* 192.168.10.20 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.30 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@localhost ~]#

在執(zhí)行成功后,主要觀察最下方的輸出信息。

其中,ok和changed表示執(zhí)行及修改成功。

如遇到unreachable或failed大于0的情況,建議手動檢查劇本是否在所有主機(jī)中都正確運(yùn)行了,以及有無安裝失敗的情況。

在正確執(zhí)行過packages.yml文件后,隨機(jī)切換到dev、test組中的任意一臺主機(jī)上,再次安裝mariadb軟件包,此時會提示該服務(wù)已經(jīng)存在。這說明剛才的操作一切順利!

[root@localhost yum.repos.d]# dnf install mariadb Updating Subscription Management repositories. Unable to read consumer identity This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. AppStream 1.7 MB/s | 3.2 kB 00:00 BaseOS 1.3 MB/s | 2.7 kB 00:00 Package mariadb-3:10.3.11-1.module+el8+2765+cfa4f87b.x86_64 is already installed. Dependencies resolved. Nothing to do. Complete! [root@localhost yum.repos.d]#

(?實(shí)驗(yàn)與實(shí)驗(yàn)之間有可能存在沖突,建議實(shí)驗(yàn)與實(shí)驗(yàn)之間可以恢復(fù)下虛擬機(jī),避免沖突。?這里就因?yàn)榍耙粋€實(shí)驗(yàn)在控制主機(jī)中新增了個倉庫EX294_BASE,?在分主機(jī)上測試安裝執(zhí)行?dnf install mariadb?出現(xiàn)以下情況,刪除EX294_BASE配置文件再次?執(zhí)行??dnf install mariadb? 則正常)

[root@localhost ~]# dnf install mariadb Updating Subscription Management repositories. Unable to read consumer identity This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.You have enabled checking of packages via GPG keys. This is a good thing. However, you do not have any GPG public keys installed. You need to download the keys for packages you wish to install and install them. You can do that by running the command:rpm --import public.gpg.keyAlternatively you can specify the url to the key you would like to use for a repository in the 'gpgkey' option in a repository section and DNF will install it for you.For more information contact your distribution or package provider.Problem repository: [EX294_BASE] bandwidth: 0 baseurl: [file:///media/cdrom/BaseOS] cachedir: /var/cache/dnf cost: 1000 deltarpm: 1 deltarpm_percentage: 75 enabled: 1 enabled_metadata: enablegroups: 1 exclude: [] excludepkgs: [] fastestmirror: 0 gpgcheck: 1 gpgkey: [] includepkgs: [] ip_resolve: whatever max_parallel_downloads: 3 mediaid: metadata_expire: 172800 metalink: minrate: 1000 mirrorlist: module_hotfixes: 0 name: EX294 base software password: priority: 99 protected_packages: [dnf, dnf, systemd, systemd-udev, sudo, dnf, systemd, systemd-udev, sudo] proxy: proxy_auth_method: any proxy_password: proxy_username: repo_gpgcheck: 0 retries: 10 skip_if_unavailable: 1 sslcacert: sslclientcert: sslclientkey: sslverify: 1 throttle: 0 timeout: 30 type: username: [root@localhost ~]#

  • 創(chuàng)建及使用角色

在日常編寫劇本時,會存在劇本越來越長的情況,這不利于進(jìn)行閱讀和維護(hù),而且還無法讓其他劇本靈活地調(diào)用其中的功能代碼。

角色(role)這一功能則是自Ansible 1.2版本開始引入的新特性,用于層次性、結(jié)構(gòu)化地組織劇本。角色功能分別把變量、文件、任務(wù)、模塊及處理器配置放在各個獨(dú)立的目錄中,然后對其進(jìn)行便捷加載。

簡單來說,角色功能是把常用的一些功能“類模塊化”,然后在用的時候加載即可。

Ansible服務(wù)的角色功能類似于編程中的封裝技術(shù)—將具體的功能封裝起來,用戶不僅可以方便地調(diào)用它,而且甚至可以不用完全理解其中的原理。

角色的好處就在于將劇本組織成了一個簡潔的、可重復(fù)調(diào)用的抽象對象,使得用戶把注意力放到劇本的宏觀大局上,統(tǒng)籌各個關(guān)鍵性任務(wù),只有在需要時才去深入了解細(xì)節(jié)。角色的獲取有3種方法,分別是加載系統(tǒng)內(nèi)置角色、從外部環(huán)境獲取角色以及自行創(chuàng)建角色。

加載系統(tǒng)內(nèi)置角色

在使用RHEL系統(tǒng)的內(nèi)置角色時,不需要聯(lián)網(wǎng)就能實(shí)現(xiàn)。用戶只需要配置好軟件倉庫的配置文件,然后安裝包含系統(tǒng)角色的軟件包rhel-system-roles,隨后便可以在系統(tǒng)中找到它們了,然后就能夠使用劇本文件調(diào)用角色了。

[root@localhost ~]# dnf install -y rhel-system-roles Updating Subscription Management repositories. Unable to read consumer identity This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. AppStream 34 kB/s | 3.2 kB 00:00 BaseOS 140 kB/s | 2.7 kB 00:00 EPEL 0.0 B/s | 0 B 00:20 Failed to synchronize cache for repo 'EPEL', ignoring this repo. Dependencies resolved. =========================================================================================================================== Package Arch Version Repository Size =========================================================================================================================== Installing: rhel-system-roles noarch 1.0-5.el8 AppStream 127 kTransaction Summary =========================================================================================================================== Install 1 PackageTotal size: 127 k Installed size: 827 k Downloading Packages: Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transactionPreparing : 1/1Installing : rhel-system-roles-1.0-5.el8.noarch 1/1Verifying : rhel-system-roles-1.0-5.el8.noarch 1/1 Installed products updated.Installed:rhel-system-roles-1.0-5.el8.noarch Complete! [root@localhost ~]#

安裝完畢后,使用ansible-galaxy list命令查看RHEL 8系統(tǒng)中有哪些自帶的角色可用

[root@localhost ~]# ansible-galaxy list # /usr/share/ansible/roles - linux-system-roles.kdump, (unknown version) - linux-system-roles.network, (unknown version) - linux-system-roles.postfix, (unknown version) - linux-system-roles.selinux, (unknown version) - linux-system-roles.timesync, (unknown version) - rhel-system-roles.kdump, (unknown version) - rhel-system-roles.network, (unknown version) - rhel-system-roles.postfix, (unknown version) - rhel-system-roles.selinux, (unknown version) - rhel-system-roles.timesync, (unknown version) # /etc/ansible/roles [WARNING]: - the configured path /root/.ansible/roles does not exist. [root@localhost ~]#

?ansible系統(tǒng)角色描述

角色名稱

作用

rhel-system-roles.kdump

配置kdump崩潰恢復(fù)服務(wù)

rhel-system-roles.network

配置網(wǎng)絡(luò)接口

rhel-system-roles.selinux

配置SELinux策略及模式

rhel-system-roles.timesync

配置網(wǎng)絡(luò)時間協(xié)議

rhel-system-roles.postfix

配置郵件傳輸服務(wù)

rhel-system-roles.firewall

配置防火墻服務(wù)

rhel-system-roles.tuned

配置系統(tǒng)調(diào)優(yōu)選項(xiàng)

以rhel-system-roles.timesync角色為例,它用于設(shè)置系統(tǒng)的時間和NTP服務(wù),讓主機(jī)能夠同步準(zhǔn)確的時間信息。劇本模板文件存放在/usr/share/doc/rhel-system-roles/目錄中,可以復(fù)制過來修改使用

[root@localhost ~]# cp /usr/share/doc/rhel-system-roles/timesync/example-timesync-playbook.yml timesync.yml [root@localhost ~]#

NTP服務(wù)器主要用于同步計(jì)算機(jī)的時間,可以提供高精度的時間校準(zhǔn)服務(wù),幫助計(jì)算機(jī)校對系統(tǒng)時鐘。在復(fù)制來的劇本模板文件中,刪除掉多余的代碼,將NTP服務(wù)器的地址填寫到timesync_ntp_servers變量的hostname字段中即可。

? timesync_ntp_servers變量參數(shù)含義

參數(shù)

作用

hostname

NTP服務(wù)器主機(jī)名

iburst

啟用快速同步

[root@localhost ~]# vim timesync.yml --- - hosts: allvars:timesync_ntp_servers:- hostname: pool.ntp.orgiburst: yesroles:- rhel-system-roles.timesync [root@localhost ~]#

從外部獲取角色

Ansible Galaxy (https://galaxy.ansible.com/) 是Ansible的一個官方社區(qū),用于共享角色和功能代碼,用戶可以在網(wǎng)站自由地共享和下載Ansible角色。該社區(qū)是管理和使用角色的不二之選。

Ansible Galaxy官網(wǎng)中,左側(cè)有3個功能選項(xiàng),分別是首頁(Home)、搜索(Search)以及社區(qū)(Community)。單擊Search按鈕進(jìn)入到搜索界面,這里以nginx服務(wù)為例進(jìn)行搜索,即可找到Nginx官方發(fā)布的角色信息

當(dāng)單擊nginx角色進(jìn)入到詳情頁面后,會顯示這個項(xiàng)目的軟件版本、評分、下載次數(shù)等信息。在Installation字段可以看到相應(yīng)的安裝方式。

如果需要使用這個角色,可以在虛擬機(jī)聯(lián)網(wǎng)的狀態(tài)下直接按照“ansible-galaxy install角色名稱”的命令格式自動獲取:

[root@localhost ~]# ansible-galaxy install nginxinc.nginx - downloading role 'nginx', owned by nginxinc - downloading role from https://github.com/nginxinc/ansible-role-nginx/archive/0.21.0.tar.gz - extracting nginxinc.nginx to /root/.ansible/roles/nginxinc.nginx - nginxinc.nginx (0.21.0) was installed successfully [root@localhost ~]#

執(zhí)行完畢后,再次查看系統(tǒng)中已有的角色,便可找到nginx角色信息了

[root@localhost ~]# ansible-galaxy list # /root/.ansible/roles - nginxinc.nginx, 0.21.0 # /usr/share/ansible/roles - linux-system-roles.kdump, (unknown version) - linux-system-roles.network, (unknown version) - linux-system-roles.postfix, (unknown version) - linux-system-roles.selinux, (unknown version) - linux-system-roles.timesync, (unknown version) - rhel-system-roles.kdump, (unknown version) - rhel-system-roles.network, (unknown version) - rhel-system-roles.postfix, (unknown version) - rhel-system-roles.selinux, (unknown version) - rhel-system-roles.timesync, (unknown version) # /etc/ansible/roles [root@localhost ~]#

如果加載非官網(wǎng)的角色需要自行編寫一個YAML語言格式的文件, 指明網(wǎng)址鏈接和角色名稱,然后再用?ansible-galaxy install -r filename? 進(jìn)行加載。

# cat nginx.yml --- - src: https:網(wǎng)站地址/nginxinc-nginx_core-0.3.0.tar.gzname: nginx-core # ansible-galaxy install -r nginx.yml

創(chuàng)建新的角色

創(chuàng)建一個名為apache的新角色,它能夠幫助我們自動安裝、運(yùn)行httpd網(wǎng)站服務(wù),設(shè)置防火墻的允許規(guī)則,以及根據(jù)每個主機(jī)生成獨(dú)立的index.html首頁文件。

在Ansible的主配置文件中,第68行定義的是角色保存路徑。如果用戶新建的角色信息不在規(guī)定的目錄內(nèi),則無法使用ansible-galaxy list命令找到。因此需要手動填寫新角色的目錄路徑,或是進(jìn)入/etc/ansible/roles目錄內(nèi)再進(jìn)行創(chuàng)建。

[root@localhost ~]# vim /etc/ansible/ansible.cfg 67 # additional paths to search for roles in, colon separated - 68 #roles_path = /etc/ansible/roles + 68 roles_path = /etc/ansible/roles 69 70 # uncomment this to disable SSH key host checking 71 #host_key_checking = False [root@localhost ~]#

在ansible-galaxy命令后面跟一個init參數(shù),創(chuàng)建一個新的角色信息,且建立成功后便會在當(dāng)前目錄下生成出一個新的目錄

[root@localhost ~]# cd /etc/ansible/roles [root@localhost roles]# ansible-galaxy init apache - Role apache was created successfully [root@localhost roles]# ls apache [root@localhost roles]#

此時的apache即是角色名稱,也是用于存在角色信息的目錄名稱。切換到該目錄下,查看它的結(jié)構(gòu)

[root@localhost roles]# cd apache [root@localhost apache]# ls defaults files handlers meta README.md tasks templates tests vars [root@localhost apache]#

在創(chuàng)建新角色時,最關(guān)鍵的便是能夠正確理解目錄結(jié)構(gòu)。

?Ansible角色目錄結(jié)構(gòu)及含義

目錄

含義

defaults

包含角色變量的默認(rèn)值(優(yōu)先級低)。

files

包含角色執(zhí)行tasks任務(wù)時做引用的靜態(tài)文件。

handlers

包含角色的處理程序定義。

meta

包含角色的作者、許可證、頻臺和依賴關(guān)系等信息。

tasks

包含角色所執(zhí)行的任務(wù)。

templates

包含角色任務(wù)所使用的Jinja2模板。

tests

包含用于測試角色的劇本文件。

vars

包含角色變量的默認(rèn)值(優(yōu)先級高)。

第1步:打開用于定義角色任務(wù)的tasks/main.yml文件。

在該文件中不需要定義要執(zhí)行的主機(jī)組列表,因?yàn)楹竺鏁为?dú)編寫劇本進(jìn)行調(diào)用,此時應(yīng)先對apache角色能做的事情(任務(wù))有一個明確的思路,在調(diào)用角色后yml文件會按照從上到下的順序自動執(zhí)行。

?? ??? ?任務(wù)1:安裝httpd網(wǎng)站服務(wù)。

?? ??? ?任務(wù)2:運(yùn)行httpd網(wǎng)站服務(wù),并加入到開機(jī)啟動項(xiàng)中。

?? ??? ?任務(wù)3:配置防火墻,使其放行HTTP協(xié)議。

?? ??? ?任務(wù)4:根據(jù)每臺主機(jī)的變量值,生成不同的主頁文件。

先寫出第一個任務(wù)。使用yum模塊安裝httpd網(wǎng)站服務(wù)程序

[root@localhost apache]# vim tasks/main.yml --- - name: oneyum:name: httpdstate: latest [root@localhost apache]#

第2步:使用service模塊啟動httpd網(wǎng)站服務(wù)程序,并加入到啟動項(xiàng)中,保證能夠一直為用戶提供服務(wù)。在初次使用模塊前,先用ansible-doc命令查看一下幫助和實(shí)例信息。

# ansible-doc service > SERVICE (/usr/lib/python3.6/site-packages/ansible/modules/system/service.py)Controls services on remote hosts. Supported init systemsinclude BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.For Windows targets, use the [win_service] module instead.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.………………省略部分輸出信息………………EXAMPLES:- name: Start service httpd, if not startedservice:name: httpdstate: started- name: Enable service httpd, and not touch the stateservice:name: httpdenabled: yes

通過輸出信息可得知,啟動服務(wù)為“state: started”參數(shù),而加入到開機(jī)啟動項(xiàng)則是“enabled: yes”參數(shù)

[root@localhost apache]# vim tasks/main.yml --- - name: oneyum:name: httpdstate: latest - name: twoservice:name: httpdstate: startedenabled: yes [root@localhost apache]#

第3步:配置防火墻的允許策略,讓其他主機(jī)可以正常訪問。在配置防火墻時,需要使用firewalld模塊

# ansible-doc firewalld > FIREWALLD (/usr/lib/python3.6/site-packages/ansible/modules/system/firewalld.py)This module allows for addition or deletion of services andports (either TCP or UDP) in either running or permanentfirewalld rules.* This module is maintained by The Ansible Community OPTIONS (= is mandatory): EXAMPLES:- firewalld:service: httpspermanent: yesstate: enabled- firewalld:port: 8081/tcppermanent: yesstate: disabledimmediate: yes

依據(jù)輸出信息可得知,在firewalld模塊設(shè)置防火墻策略時,指定協(xié)議名稱為“service: http”參數(shù),放行該協(xié)議為“state: enabled”參數(shù),設(shè)置為永久生效為“permanent: yes”參數(shù),當(dāng)前立即生效為“immediate: yes”參數(shù)。

[root@localhost apache]# vim tasks/main.yml --- - name: oneyum:name: httpdstate: latest - name: twoservice:name: httpdstate: startedenabled: yes - name: threefirewalld:service: httppermanent: yesstate: enabledimmediate: yes [root@localhost apache]#

第4步:讓每臺主機(jī)顯示的主頁文件均不相同。

在使用Ansible的常規(guī)模塊時,都是采用“查詢版主示例并模仿”的方式搞定的,這里為了增加難度,再提出個新需求,即能否讓每臺主機(jī)上運(yùn)行的httpd網(wǎng)站服務(wù)都能顯示不同的內(nèi)容呢?例如顯示當(dāng)前服務(wù)器的主機(jī)名及IP地址。

這就要用到template模塊及Jinja2技術(shù)了。

使用ansible-doc命令來查詢template模塊的使用方法

# ansible-doc template > TEMPLATE (/usr/lib/python3.6/site-packages/ansible/modules/files/template.>Templates are processed by the L(Jinja2 templatinglanguage,http://jinja.pocoo.org/docs/). Documentation on thetemplate formatting can be found in the L(Template DesignerDocumentation,http://jinja.pocoo.org/docs/templates/).Additional variables listed below can be used in templates.`ansible_managed' (configurable via the `defaults' section of`ansible.cfg') contains a string which can be used to describethe template name, host, modification time of the templatefile and the owner uid. `template_host' contains the node nameof the template's machine. `template_uid' is the numeric userid of the owner. `template_path' is the path of the template.`template_fullpath' is the absolute path of the template.`template_destpath' is the path of the template on the remotesystem (added in 2.8). `template_run_date' is the date thatthe template was rendered.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.………………省略部分輸出信息………………EXAMPLES:- name: Template a file to /etc/files.conftemplate:src: /mytemplates/foo.j2dest: /etc/file.confowner: bingroup: wheelmode: '0644'

從template模塊的輸出信息中可得知,這是一個用于復(fù)制文件模板的模塊,能夠把文件從Ansible服務(wù)器復(fù)制到受管主機(jī)上。其中,src參數(shù)用于定義本地文件的路徑,dest參數(shù)用于定義復(fù)制到受管主機(jī)的文件路徑,而owner、group、mode參數(shù)可選擇性地設(shè)置文件歸屬及權(quán)限信息。

[root@localhost apache]# vim tasks/main.yml --- - name: oneyum:name: httpdstate: latest - name: twoservice:name: httpdstate: startedenabled: yes - name: threefirewalld:service: httppermanent: yesstate: enabledimmediate: yes - name: fourtemplate:src: index.html.j2dest: /var/www/html/index.html [root@localhost apache]#

Jinja2?是Python語言中一個被廣泛使用的模板引擎,最初的設(shè)計(jì)思想源自Django的模塊引擎。Jinja2基于此發(fā)展了其語法和一系列強(qiáng)大的功能,能夠讓受管主機(jī)根據(jù)自身變量產(chǎn)生出不同的文件內(nèi)容。 使用Jinja2技術(shù)時,不是在原始文件中直接寫入文件內(nèi)容,而是寫入一系列的變量名稱。在使用template模塊進(jìn)行復(fù)制的過程中,由Ansible服務(wù)負(fù)責(zé)在受管主機(jī)上收集這些變量名稱所對應(yīng)的值,然后再逐一填寫到目標(biāo)文件中,從而讓每臺主機(jī)的文件都根據(jù)自身系統(tǒng)的情況獨(dú)立生成。

想要讓每個網(wǎng)站的輸出信息值為“Welcome to主機(jī)名on主機(jī)地址”,也就是用每個主機(jī)自己獨(dú)有的名稱和IP地址來替換文本中的內(nèi)容,這樣就有趣太多了。這個實(shí)驗(yàn)的難點(diǎn)在于查詢到對應(yīng)的變量名稱、主機(jī)名及地址所對應(yīng)的值保存在哪里?可以用setup模塊進(jìn)行查詢。

# ansible-doc setup > SETUP (/usr/lib/python3.6/site-packages/ansible/modules/system/setup.py)This module is automatically called by playbooks to gatheruseful variables about remote hosts that can be used inplaybooks. It can also be executed directly by`/usr/bin/ansible' to check what variables are available to ahost. Ansible provides many `facts' about the system,automatically. This module is also supported for Windowstargets.

setup模塊的作用是自動收集受管主機(jī)上的變量信息,使用-a參數(shù)外加filter命令可以對收集來的信息進(jìn)行二次過濾。

相應(yīng)的語法格式為ansible all -m setup -a 'filter="*關(guān)鍵詞*"',其中*號是第3章節(jié)講到的通配符,用于進(jìn)行關(guān)鍵詞查詢。

例如,如果想搜索各個主機(jī)的名稱,可以使用通配符搜索所有包含fqdn關(guān)鍵詞的變量值信息。

FQDN(Fully Qualified Domain Name,完全限定域名)用于在邏輯上準(zhǔn)確表示出主機(jī)的位置。FQDN常常被作為主機(jī)名的完全表達(dá)形式,比/etc/hostname文件中定義的主機(jī)名更加嚴(yán)謹(jǐn)和準(zhǔn)確。通過輸出信息可得知,ansible_fqdn變量保存有主機(jī)名稱。隨后進(jìn)行下一步操作:

[root@localhost apache]# ansible all -m setup -a 'filter="*fqdn*"' 192.168.10.20 | SUCCESS => {"ansible_facts": {"ansible_fqdn": "localhost.localdomain","discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false } 192.168.10.30 | SUCCESS => {"ansible_facts": {"ansible_fqdn": "localhost.localdomain","discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false } [root@localhost apache]#

用于指定主機(jī)地址的變量可以用ip作為關(guān)鍵詞進(jìn)行檢索。可以看到,ansible_all_ipv4_addresses變量中的值是我們想要的信息。如果想輸出IPv6形式的地址,則可用ansible_all_ipv6_addresses變量。

[root@localhost apache]# ansible all -m setup -a 'filter="*ip*"' 192.168.10.20 | SUCCESS => {"ansible_facts": {"ansible_all_ipv4_addresses": ["192.168.10.20","192.168.122.1"],"ansible_all_ipv6_addresses": ["fe80::a7bc:9261:b95:a2f6","fe80::b10f:c9ee:e04b:f32a"],"ansible_default_ipv4": {"address": "192.168.10.20","alias": "ens160","broadcast": "192.168.10.255","gateway": "192.168.10.1","interface": "ens160","macaddress": "00:0c:29:79:79:70","mtu": 1500,"netmask": "255.255.255.0","network": "192.168.10.0","type": "ether"},"ansible_default_ipv6": {},"ansible_fips": false,"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false } 192.168.10.30 | SUCCESS => {"ansible_facts": {"ansible_all_ipv4_addresses": ["192.168.10.30","192.168.122.1"],"ansible_all_ipv6_addresses": ["fe80::bd99:7be7:aa88:d431"],"ansible_default_ipv4": {"address": "192.168.10.30","alias": "ens160","broadcast": "192.168.10.255","gateway": "192.168.10.1","interface": "ens160","macaddress": "00:0c:29:96:ad:24","mtu": 1500,"netmask": "255.255.255.0","network": "192.168.10.0","type": "ether"},"ansible_default_ipv6": {},"ansible_fips": false,"discovered_interpreter_python": "/usr/libexec/platform-python"},"changed": false } [root@localhost apache]#

在確認(rèn)了主機(jī)名與IP地址所對應(yīng)的具體變量名稱后,在角色所對應(yīng)的templates目錄內(nèi)新建一個與上面的template模塊參數(shù)相同的文件名稱(index.html.j2)。Jinja2在調(diào)用變量值時,格式為在變量名稱的兩側(cè)格加兩個大括號

[root@localhost apache]# vim templates/index.html.j2 Welcome to {{ ansible_fqdn }} on {{ ansible_all_ipv4_addresses }} [root@localhost apache]#

進(jìn)行到這里,任務(wù)基本就算完成了。

最后要做的就是編寫一個用于調(diào)用apache角色的yml文件,以及執(zhí)行這個文件。

[root@localhost apache]# cd ~ [root@localhost ~]# vim roles.yml --- - name: 調(diào)用自建角色hosts: allroles:- apache [root@localhost ~]# ansible-playbook roles.ymlPLAY [調(diào)用自建角色] *****************************************************************************************************************TASK [Gathering Facts] ******************************************************************************************************** ok: [192.168.10.20] ok: [192.168.10.30]TASK [apache : one] *********************************************************************************************************** changed: [192.168.10.20] changed: [192.168.10.30]TASK [apache : two] *********************************************************************************************************** changed: [192.168.10.20] changed: [192.168.10.30]TASK [apache : three] ********************************************************************************************************* changed: [192.168.10.20] changed: [192.168.10.30]TASK [apache : four] ********************************************************************************************************** changed: [192.168.10.20] changed: [192.168.10.30]PLAY RECAP ******************************************************************************************************************** 192.168.10.20 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.30 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@localhost ~]#

執(zhí)行完畢后,在瀏覽器中隨機(jī)輸入幾臺主機(jī)的IP地址,即可訪問到包含主機(jī)FQDN和IP地址的網(wǎng)頁了

?

創(chuàng)建和使用邏輯卷

創(chuàng)建一個能批量、自動管理邏輯卷設(shè)備的劇本,不但能大大提高硬盤設(shè)備的管理效率,而且還能避免手動創(chuàng)建帶來的錯誤。

在每臺受管主機(jī)上都創(chuàng)建出一個名為data的邏輯卷設(shè)備,大小為150MB,歸屬于research卷組。如果創(chuàng)建成功,則進(jìn)一步用Ext4文件系統(tǒng)進(jìn)行格式化操作;如果創(chuàng)建失敗,則給用戶輸出一條報(bào)錯提醒,以便排查原因。

在這種情況下,使用Ansible劇本要比使用Shell腳本的優(yōu)勢大,原因主要有下面兩點(diǎn)。

?? ??? ?Ansible模塊化的功能讓操作更標(biāo)準(zhǔn),只要在執(zhí)行過程中無報(bào)錯,那么便會依據(jù)遠(yuǎn)程主機(jī)的系統(tǒng)版本及配置自動做出判斷和操作,不用擔(dān)心因系統(tǒng)變化而導(dǎo)致命令失效的問題。

?? ??? ?Ansible服務(wù)在執(zhí)行劇本文件時會進(jìn)行判斷:如果該文件或該設(shè)備已經(jīng)被創(chuàng)建過,或是某個動作(play)已經(jīng)被執(zhí)行過,則絕對不會再重復(fù)執(zhí)行;而使用Shell腳本有可能導(dǎo)致設(shè)備被重復(fù)格式化,導(dǎo)致數(shù)據(jù)丟失。

在兩臺主機(jī)上分別添加一塊硬盤設(shè)備,大小為5GB,類型為SATA,其余選項(xiàng)選擇默認(rèn)值。

讓劇本文件依次創(chuàng)建物理卷(PV)、卷組(VG)及邏輯卷(LV)。

需要先使用lvg模塊讓設(shè)備支持邏輯卷技術(shù),然后創(chuàng)建一個名為research的卷組。

lvg模塊的幫助信息如下

# ansible-doc lvg > LVG (/usr/lib/python3.6/site-packages/ansible/modules/system/lvg.py)This module creates, removes or resizes volume groups.* This module is maintained by The Ansible Community………………省略部分輸出信息………………EXAMPLES:- name: Create a volume group on top of /dev/sda1 with physical extent size = 3>lvg:vg: vg.servicespvs: /dev/sda1pesize: 32- name: Create a volume group on top of /dev/sdb with physical extent size = 12>lvg:vg: vg.servicespvs: /dev/sdbpesize: 128K

通過輸出信息可得知,創(chuàng)建PV和VG的lvg模塊總共有3個必備參數(shù)。其中,vg參數(shù)用于定義卷組的名稱,pvs參數(shù)用于指定硬盤設(shè)備的名稱,pesize參數(shù)用于確定最終卷組的容量大小(可以用PE個數(shù)或容量值進(jìn)行指定)。這樣一來,我們先創(chuàng)建出一個由/dev/sdb設(shè)備組成的名稱為research、大小為150MB的卷組設(shè)備。

[root@localhost ~]# vim lv.yml --- - name: 創(chuàng)建和使用邏輯卷hosts: alltasks:- name: onelvg:vg: researchpvs: /dev/sdbpesize: 150M [root@localhost ~]#

接下來使用lvol模塊創(chuàng)建出邏輯卷設(shè)備

# ansible-doc lvol > LVOL (/usr/lib/python3.6/site-packages/ansible/modules/system/lvol.py)This module creates, removes or resizes logical volumes.* This module is maintained by The Ansible Community………………省略部分輸出信息………………EXAMPLES:- name: Create a logical volume of 512mlvol:vg: fireflylv: testsize: 512- name: Create a logical volume of 512m with disks /dev/sda and /dev/sdblvol:vg: fireflylv: testsize: 512pvs: /dev/sda,/dev/sdb

lvol是用于創(chuàng)建邏輯卷設(shè)備的模塊。

其中,vg參數(shù)用于指定卷組名稱,lv參數(shù)用于指定邏輯卷名稱,size參數(shù)則用于指定最終邏輯卷設(shè)備的容量大小(不用加單位,默認(rèn)為MB)。

填寫好參數(shù),創(chuàng)建出一個大小為150MB、歸屬于research卷組且名稱為data的邏輯卷設(shè)備

[root@localhost ~]# vim lv.yml --- - name: 創(chuàng)建和使用邏輯卷hosts: alltasks:- name: onelvg:vg: researchpvs: /dev/sdbpesize: 150M- name: twolvol:vg: researchlv: datasize: 150M [root@localhost ~]#

使用filesystem模塊來完成設(shè)備的文件系統(tǒng)格式化操作

# ansible-doc filesystem > FILESYSTEM (/usr/lib/python3.6/site-packages/ansible/modules/system/filesy>This module creates a filesystem.* This module is maintained by The Ansible Community………………省略部分輸出信息………………EXAMPLES:- name: Create a ext2 filesystem on /dev/sdb1filesystem:fstype: ext2dev: /dev/sdb1

filesystem模塊的參數(shù)真是簡練,fstype參數(shù)用于指定文件系統(tǒng)的格式化類型,dev參數(shù)用于指定要格式化的設(shè)備文件路徑。

[root@localhost ~]# vim lv.yml --- - name: 創(chuàng)建和使用邏輯卷hosts: alltasks:- name: onelvg:vg: researchpvs: /dev/sdbpesize: 150M- name: twolvol:vg: researchlv: datasize: 150M- name: threefilesystem:fstype: ext4dev: /dev/research/data [root@localhost ~]#

用block操作符將上述的3個模塊命令作為一個整體(相當(dāng)于對這3個模塊的執(zhí)行結(jié)果作為一個整體進(jìn)行判斷),然后使用rescue操作符進(jìn)行救援,且只有block塊中的模塊執(zhí)行失敗后才會調(diào)用rescue中的救援模塊。

其中,debug模塊的msg參數(shù)的作用是,如果block中的模塊執(zhí)行失敗,則輸出一條信息到屏幕,用于提醒用戶。

[root@localhost ~]# vim lv.yml --- - name: 創(chuàng)建和使用邏輯卷hosts: alltasks:- block:- name: onelvg:vg: researchpvs: /dev/sdbpesize: 150M- name: twolvol:vg: researchlv: datasize: 150M- name: threefilesystem:fstype: ext4dev: /dev/research/datarescue: - debug:msg: "Could not create logical volume of that size" [root@localhost ~]#

YAML語言對格式有著硬性的要求,既然rescue是對block內(nèi)的模塊進(jìn)行救援的功能代碼,因此recue和block兩個操作符必須嚴(yán)格對齊,錯開一個空格都會導(dǎo)致劇本執(zhí)行失敗。

[root@localhost ~]# ansible-playbook lv.ymlPLAY [創(chuàng)建和使用邏輯卷] **************************************************************************TASK [Gathering Facts] ******************************************************************* ok: [192.168.10.20] ok: [192.168.10.30]TASK [one] ******************************************************************************* changed: [192.168.10.20] changed: [192.168.10.30]TASK [two] ******************************************************************************* changed: [192.168.10.20] changed: [192.168.10.30]TASK [three] ***************************************************************************** changed: [192.168.10.20] changed: [192.168.10.30]PLAY RECAP ******************************************************************************* 192.168.10.20 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.30 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@localhost ~]#

在執(zhí)行了邏輯卷主機(jī)上?輸入?# lvdisplay ?可以查看到新創(chuàng)建的邏輯卷

[ 192.168.10.20 ]

[root@localhost ~]# lvdisplay--- Logical volume ---LV Path /dev/research/dataLV Name dataVG Name researchLV UUID WltmOq-4l5T-or3D-0MTY-oty5-cSNm-JNkK7xLV Write Access read/writeLV Creation host, time localhost.localdomain, 2021-11-26 14:21:28 +0800LV Status available# open 0LV Size 150.00 MiBCurrent LE 1Segments 1Allocation inheritRead ahead sectors auto- currently set to 8192Block device 253:2--- Logical volume ---LV Path /dev/rhel/swapLV Name swapVG Name rhelLV UUID gdsTVM-5yAN-oej7-FQq7-Mtfh-LRel-YPjy1LLV Write Access read/writeLV Creation host, time localhost, 2021-04-01 14:46:09 +0800LV Status available# open 2LV Size 2.00 GiBCurrent LE 512Segments 1Allocation inheritRead ahead sectors auto- currently set to 8192Block device 253:1--- Logical volume ---LV Path /dev/rhel/rootLV Name rootVG Name rhelLV UUID o2vlUv-ZZ2U-vfYg-5kwM-uzB8-EFIx-Cxa6uoLV Write Access read/writeLV Creation host, time localhost, 2021-04-01 14:46:09 +0800LV Status available# open 1LV Size <17.00 GiBCurrent LE 4351Segments 1Allocation inheritRead ahead sectors auto- currently set to 8192Block device 253:0[root@localhost ~]#

判斷主機(jī)組名

在每個客戶端中都會有一個名為inventory_hostname的變量,用于定義每臺主機(jī)所對應(yīng)的Ansible服務(wù)的主機(jī)組名稱,也就是/etc/ansible/hosts文件中所對應(yīng)的分組信息,例如dev、test、prod、balancers。

inventory_hostname是Ansible服務(wù)中的魔法變量,這意味著無法使用setup模塊直接進(jìn)行查詢,諸如ansible all -m setup -a 'filter="*關(guān)鍵詞*"'這樣的命令將對它失效。

魔法變量需要在執(zhí)行劇本文件時的Gathering Facts階段進(jìn)行搜集,直接查詢是看不到的,只能在劇本文件中進(jìn)行調(diào)用。

在獲得了存儲主機(jī)組名稱的變量名稱后,接下來開始實(shí)戰(zhàn)。

需求:

?? ??? ?若主機(jī)在dev分組中,則修改/etc/issue文件內(nèi)容為Development;

?? ??? ?若主機(jī)在test分組中,則修改/etc/issue文件內(nèi)容為Test;

?? ??? ?

可以用? Ansible?的?copy?來完成此需求,copy 模塊的主要作用是新建、修改及復(fù)制文件。

# ansible-doc copy > COPY (/usr/lib/python3.6/site-packages/ansible/modules/files/copy.py)The `copy' module copies a file from the local or remotemachine to a location on the remote machine. Use the [fetch]module to copy files from remote locations to the local box.If you need variable interpolation in copied files, use the[template] module. Using a variable in the `content' fieldwill result in unpredictable output. For Windows targets, usethe [win_copy] module instead.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.………………省略部分輸出信息………………EXAMPLES:- name: Copy file with owner and permissionscopy:src: /srv/myfiles/foo.confdest: /etc/foo.confowner: foogroup: foomode: '0644'- name: Copy using inline contentcopy:content: '# This file was moved to /etc/other.conf'dest: /etc/mine.conf

在輸出信息中列舉了兩種管理文件內(nèi)容的示例。

第一種用于文件的復(fù)制行為,

第二種是通過content參數(shù)定義內(nèi)容,通過dest參數(shù)指定新建文件的名稱。

依據(jù)inventory_hostname變量中的值進(jìn)行判斷。若主機(jī)為dev組,則執(zhí)行第一個動作;若主機(jī)為test組,則執(zhí)行第二個動作;

[root@localhost ~]# vim issue.yml --- - name: 修改文件內(nèi)容hosts: alltasks:- name: onecopy:content: 'Development'dest: /etc/issuewhen: "inventory_hostname in groups.dev"- name: twocopy:content: 'Test'dest: /etc/issue when: "inventory_hostname in groups.test" [root@localhost ~]# [root@localhost ~]# ansible-playbook issue.ymlPLAY [修改文件內(nèi)容] ****************************************************************************TASK [Gathering Facts] ******************************************************************* ok: [192.168.10.20] ok: [192.168.10.30]TASK [one] ******************************************************************************* skipping: [192.168.10.30] changed: [192.168.10.20]TASK [two] ******************************************************************************* skipping: [192.168.10.20] changed: [192.168.10.30]PLAY RECAP ******************************************************************************* 192.168.10.20 : ok=2 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 192.168.10.30 : ok=2 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 [root@localhost ~]#

[ 192.168.10.20 ]

[root@localhost ~]# cat /etc/issue Development

管理文件屬性

學(xué)習(xí)劇本的目的是為了滿足日常的工作需求,把重復(fù)的事情寫入到腳本中,然后再批量執(zhí)行下去,從而提高運(yùn)維工作的效率。

其中,創(chuàng)建文件、管理權(quán)限以及設(shè)置快捷方式幾乎是每天都用到的技能。

Ansible服務(wù)將常用的文件管理功能都合并到了file模塊中。

# ansible-doc file > FILE (/usr/lib/python3.6/site-packages/ansible/modules/files/file.py)Set attributes of files, symlinks or directories.Alternatively, remove files, symlinks or directories. Manyother modules support the same options as the `file' module -including [copy], [template], and [assemble]. For Windowstargets, use the [win_file] module instead.* This module is maintained by The Ansible Core Team………………省略部分輸出信息………………EXAMPLES:- name: Change file ownership, group and permissionsfile:path: /etc/foo.confowner: foogroup: foomode: '0644'- name: Create a symbolic linkfile:src: /file/to/link/todest: /path/to/symlinkowner: foogroup: foostate: link- name: Create a directory if it does not existfile:path: /etc/some_directorystate: directorymode: '0755'- name: Remove file (delete file)file:path: /etc/foo.txtstate: absent

通過上面的輸出示例,已經(jīng)能夠了解file模塊的基本參數(shù)了。其中,path參數(shù)定義了文件的路徑,owner參數(shù)定義了文件所有者,group參數(shù)定義了文件所屬組,mode參數(shù)定義了文件權(quán)限,src參數(shù)定義了源文件的路徑,dest參數(shù)定義了目標(biāo)文件的路徑,state參數(shù)則定義了文件類型。

實(shí)驗(yàn):

?? ??? ?創(chuàng)建出一個名為 /zhangsan 的新目錄,所有者及所屬組均為root管理員身份;

?? ??? ?設(shè)置所有者和所屬于組擁有對文件的完全控制權(quán),而其他人則只有閱讀和執(zhí)行權(quán)限;

?? ??? ?給予SGID特殊權(quán)限;

?? ??? ?僅在dev主機(jī)組的主機(jī)上實(shí)施。

?? ??? ?再創(chuàng)建一個名稱為 /lisi 的快捷方式文件,指向剛剛建立的 /zhangsan 目錄

[root@localhost ~]# vim chmod.yml --- - name: 管理文件屬性hosts: devtasks:- name: onefile:path: /zhangsanstate: directoryowner: rootgroup: rootmode: '2775'- name: twofile:src: /zhangsandest: /lisistate: link [root@localhost ~]# [root@localhost ~]# ansible-playbook chmod.ymlPLAY [管理文件屬性] ****************************************************************************TASK [Gathering Facts] ******************************************************************* ok: [192.168.10.20]TASK [one] ******************************************************************************* changed: [192.168.10.20]TASK [two] ******************************************************************************* changed: [192.168.10.20]PLAY RECAP ******************************************************************************* 192.168.10.20 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@localhost ~]#

[ 192.168.10.20 ]

[root@localhost ~]# ls -ld /zhangsan drwxrwsr-x. 2 root root 6 Nov 26 14:27 /zhangsan [root@localhost ~]# ls -ld /lisi lrwxrwxrwx. 1 root root 9 Nov 26 14:27 /lisi -> /zhangsan [root@localhost ~]#

管理密碼庫文件

自Ansible 1.5版本發(fā)布后,vault作為一項(xiàng)新功能進(jìn)入到了運(yùn)維人員的視野。

它不僅能對密碼、劇本等敏感信息進(jìn)行加密,而且還可以加密變量名稱和變量值,從而確保數(shù)據(jù)不會被他人輕易閱讀。

使用ansible-vault命令可以實(shí)現(xiàn)內(nèi)容的新建(create)、加密(encrypt)、解密(decrypt)、修改密碼(rekey)及查看(view)等功能。

第1步:創(chuàng)建出一個名為locker.yml的配置文件,其中保存了兩個變量值

[root@localhost ~]# vim locker.yml --- pw_developer: Imadev pw_manager: Imamgr [root@localhost ~]#

第2步:使用ansible-vault命令對文件進(jìn)行加密。由于需要每次輸入密碼比較麻煩,因此還應(yīng)新建一個用于保存密碼值的文本文件,以便讓ansible-vault命令自動調(diào)用。為了保證數(shù)據(jù)的安全性,在新建密碼文件后將該文件的權(quán)限設(shè)置為600,確保僅管理員可讀可寫

[root@localhost ~]# vim /root/secret.txt whenyouwishuponastar [root@localhost ~]# chmod 600 /root/secret.txt [root@localhost ~]#

在Ansible服務(wù)的主配置文件中,在第140行的vault_password_file參數(shù)后指定密碼值保存的文件路徑

[root@localhost ~]# vim /etc/ansible/ansible.cfg 138 # If set, configures the path to the Vault password file as an alternative to 139 # specifying --vault-password-file on the command line. - 140 #vault_password_file = /path/to/vault_password_file + 140 vault_password_file = /root/secret.txt 141 142 # format of string {{ ansible_managed }} available within Jinja2 [root@localhost ~]#

第3步:在設(shè)置好密碼文件的路徑后,Ansible服務(wù)便會自動進(jìn)行加載。用戶也就不用在每次加密或解密時都重復(fù)輸入密碼了。

在加密剛剛創(chuàng)建的locker.yml文件時,只需要使用encrypt參數(shù)即可

[root@localhost ~]# ansible-vault encrypt locker.yml Encryption successful [root@localhost ~]# cat locker.yml $ANSIBLE_VAULT;1.1;AES256 34623765653933353164353962336431303961336438313037366436323639316234333362333233 6465386466356332626235643239663438363466616635340a373031313463313536326139386231 63653366623538643939383031646661613730663435633463363937346330366333356565636631 6231353762333163660a373431666266333335613139376633356434363438303132643462333466 37666264626330313665633334633137383239646166343638376536393965303663643566613237 3739386566383439363533653333643539373536383862616637 [root@localhost ~]#

如果不想使用原始密碼了呢?也可以使用rekey參數(shù)手動對文件進(jìn)行改密操作,同時應(yīng)結(jié)合--ask-vault-pass參數(shù)進(jìn)行修改,否則Ansible服務(wù)會因接收不到用戶輸入的舊密碼值而拒絕新的密碼變更請求

[root@localhost ~]# ansible-vault rekey --ask-vault-pass locker.yml Vault password: #舊密碼 New Vault password: #新密碼 Confirm New Vault password: #重復(fù)新密碼 Rekey successful [root@localhost ~]#

第4步:如果想查看和修改加密文件中的內(nèi)容,該怎么操作呢?對于已經(jīng)加密過的文件,需要使用ansible-vault命令的edit參數(shù)進(jìn)行修改,隨后用view參數(shù)即可查看到修改后的內(nèi)容。ansible-vault命令對加密文件的編輯操作默認(rèn)使用的是Vim編輯器,在修改完畢后請記得執(zhí)行wq操作保存后退出

[root@localhost ~]# ansible-vault edit locker.yml --- pw_developer: Imadev pw_manager: Imamgr pw_production: Imaprod [root@localhost ~]#

最后,再用view參數(shù)進(jìn)行查看,便是最新的內(nèi)容了

[root@localhost ~]# ansible-vault view locker.yml --- pw_developer: Imadev pw_manager: Imamgr pw_production: Imaprod [root@localhost ~]#

總結(jié)

以上是生活随笔為你收集整理的LinuxProbe 0x21 使用Ansible服务实现自动化运维的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。