第2天:Ansible-Inventory管理
在Ansible中,將可管理的服務(wù)器集合成為Inventory。因此,Inventory管理便是服務(wù)器管理。
hosts文件位置
我們知道,Ansible在執(zhí)行操作時(shí),首先需要確定對(duì)哪些服務(wù)器執(zhí)行操作。默認(rèn)情況下,Ansible讀取/etc/ansible/hosts文件中的服務(wù)器配置,獲取需要操作的服務(wù)器列表。Ansible定義與獲取服務(wù)器列表的方式比這個(gè)要靈活的多。
在Ansible中,有三種方式指定hosts文件:
1)默認(rèn)讀取/etc/ansible/hosts文件
2)通過(guò)命令行參數(shù)的 -i 指定hosts文件
3)通過(guò)ansible.cfg文件的inventory選項(xiàng)
ansible命令的--list-hosts選項(xiàng)用來(lái)顯示匹配的服務(wù)器列表,我們可以通過(guò)該參數(shù)驗(yàn)證服務(wù)器的匹配情況
[heboan@c1 ~]$ ansible test --list-hostshosts (2):192.168.88.2192.168.88.3我們?cè)诩夷夸浵聞?chuàng)建個(gè)hosts,然后用-i指定這個(gè)hosts
[heboan@c1 ~]$ cat hosts [test] 192.168.20.1 192.168.20.2 [heboan@c1 ~]$ [heboan@c1 ~]$ ansible test -i hosts --list-hostshosts (2):192.168.20.1192.168.20.2 [heboan@c1 ~]$ [heboan@c1 ~]$ ansible test --list-hosts #默認(rèn)情況hosts (2):192.168.88.2192.168.88.3我們也可以在ansible.cfg中通過(guò)inventory選項(xiàng)指定hosts文件路徑
[heboan@c1 ~]$ cat /etc/ansible/ansible.cfg [defaults] remote_port = 2202 remote_user = heboan inventory = /home/heboan/hosts [heboan@c1 ~]$ [heboan@c1 ~]$ ansible test --list-hostshosts (2):192.168.20.1192.168.20.2靈活定義hosts文件內(nèi)容
Ansible支持更加靈活的方式定義hosts文件,例如將服務(wù)器進(jìn)行分組,以便對(duì)不同的服務(wù)器類型進(jìn)行不同的操作, 如下
mail.heboan.com #不屬于任何一個(gè)組 [webservers] foo.heboan.com bar.heboan.com[dbserver] one.heboan.com two.heboan.com three.heboan.com在服務(wù)器匹配時(shí),all或星號(hào)是一個(gè)特殊的名稱,用于匹配所有的服務(wù)器
[heboan@c1 ~]$ ansible '*' --list-hostshosts (6):mail.heboan.comfoo.heboan.combar.heboan.comone.heboan.comtwo.heboan.comthree.heboan.com 匹配所有服務(wù)器使用組名,匹配該組所有服務(wù)器
[heboan@c1 ~]$ ansible dbserver --list-hostshosts (3):one.heboan.comtwo.heboan.comthree.heboan.com 匹配組服務(wù)器?Ansible也可以定義一個(gè)組,這個(gè)組下面定義的不是服務(wù)器列表,而是包含其他組的名稱, 通過(guò)":children"的方式來(lái)聲明
[common:children] webserver dbserver如果我有一批服務(wù)器,并且這些服務(wù)器有相同的模式,我們可以向下面這樣定義服務(wù)器
[webservers] web[1:3].heboan.com bar.heboan.com[dbservers] db[a:d].heboan.com靈活匹配hosts文件內(nèi)容
| 規(guī)則 | 含義 |
| 192.168.88.2或c2.heboan.com | 匹配模板IP地址或服務(wù)器名,如果有多個(gè)ip或服務(wù)器,使用":"分隔 |
| webservers | ?匹配目標(biāo)組為webservers,多個(gè)組使用":"分隔 |
| ?all或'*' | ?匹配所有服務(wù)器 |
| ?webservers:!dbservers | ?匹配在webservers中,不在dbservers組中的服務(wù)器 |
| ?webservers:&dbservers | ?匹配同時(shí)在webservers組以及在dbservers組中的服務(wù)器 |
| ?*.example.com或192.168.* | ?使用通配符匹配 |
| ?webservers[0],webservers[1:],webservers[-1] | ?使用索引或切片操作的方式匹配組中的服務(wù)器 |
| ?~(web|db).*example.com | ?以~開(kāi)頭的匹配,表示使用正則表達(dá)式匹配 |
動(dòng)態(tài)Inventory獲取
從前面的介紹可以看到,Ansible提供給你了非常靈活的方式來(lái)編寫hosts文件,可以節(jié)省不必要的時(shí)間浪費(fèi)、提高工作效率。此外,Ansible還可以通過(guò)調(diào)用云計(jì)算服務(wù)的API,編寫自定義腳本的方式獲取服務(wù)器列表。如果公司有使用CMDB系統(tǒng)來(lái)管理服務(wù)器,那么,我們可以通過(guò)讀取CMDB數(shù)據(jù)庫(kù)中的記錄得到服務(wù)器列表。
既然 我們可以通過(guò)調(diào)用云計(jì)算系統(tǒng)的API,或者讀取CMDB系統(tǒng)的數(shù)據(jù)庫(kù)獲取服務(wù)器列表,那么,再將服務(wù)器地址寫入hosts文件就顯得比較冗余,且沒(méi)有任何必要。
一個(gè)動(dòng)態(tài)獲取服務(wù)器列表的腳本必須支持如下兩個(gè)命令行參數(shù):
1)--host=<hostname>: 用于列出某臺(tái)服務(wù)器的詳細(xì)信息
2)--list:用于列出群組以及群組中的服務(wù)器
例如,我們才CMDB系統(tǒng)庫(kù)中包含了一些服務(wù)器的信息, 如果將這些服務(wù)器信息從數(shù)據(jù)庫(kù)中拷貝到hosts文件中,效果如下:
[root@c1 ~]# cat /etc/ansible/hosts [test] 192.168.88.2 ansible_user=heboan ansible_port=22 192.168.88.3 ansible_user=heboan ansible_port=22[uat] 192.168.88.4 ansible_user=heboan ansible_port=22按照Ansible的約定,我們需要編寫一個(gè)動(dòng)態(tài)腳本來(lái)獲取服務(wù)器的列表,這個(gè)腳本必須支持--list選項(xiàng)和--host選項(xiàng)。其中,--list選項(xiàng)以json的格式返回以組名為key,服務(wù)器列表為value的數(shù)據(jù)。--host返回一個(gè)字典,該字典中包含了這個(gè)服務(wù)器的詳細(xì)信息,如下:
[heboan@c1 ~]$ python hosts.py --list {"test": ["192.168.88.2", "192.168.88.3"], "uat": ["192.168.88.4"] } [heboan@c1 ~]$ [heboan@c1 ~]$ python hosts.py --host='192.168.88.2' {"ansible_port": "22", "asnible_user": "heboan" }接下來(lái)我們來(lái)看下如何編寫這樣一個(gè)動(dòng)態(tài)獲取服務(wù)器的腳本。假設(shè)。我們的CMDB數(shù)據(jù)庫(kù)中,存在一張名為hosts的表:
CREATE TABLE hosts( id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, host varchar(15) DEFAULT NULL, groupname varchar(15) DEFAULT NULL, username varchar(15) DEFAULT NULL, port int(11) DEFAULT NULL );INSERT INTO hosts values(null, '192.168.88.2', 'test', 'heboan', 22); INSERT INTO hosts values(null, '192.168.88.3', 'test', 'heboan', 22); INSERT INTO hosts values(null, '192.168.88.3', 'uat', 'heboan', 22);下面是動(dòng)態(tài)獲取服務(wù)器列表的程序
#!/usr/bin/python #_*_ coding: UTF-8 _*_import argparse import json from collections import defaultdict from contextlib import contextmanager import pymysqldef to_json(in_dict):return json.dumps(in_dict, sort_keys=True, indent=4)@contextmanager def get_conn(**kwargs):conn = pymysql.connect(**kwargs)try:yield connfinally:conn.close()def parse_args():parser = argparse.ArgumentParser(description='Heboan Inventory Module')group = parser.add_mutually_exclusive_group(required=True)group.add_argument('--list', action='store_true', help='list active servers')group.add_argument('--host', help='List details about the specific host')return parser.parse_args()def list_all_hosts(conn):hosts = defaultdict(list)with conn as cur:cur.execute('select * from hosts')rows = cur.fetchall()for row in rows:no, host, group, user, port = rowhosts[group].append(host)return hostsdef get_host_detail(conn, host):details = {}with conn as cur:cur.execute("select * from hosts where host='{}'".format(host))rows = cur.fetchall()if rows:no, host, group, user, port = rows[0]details.update(asnible_user=user, ansible_port=port)return detailsdef main():parser = parse_args()with get_conn(host='127.0.0.1', user='root', password='root', db='cmdb' ) as conn:if parser.list:hosts = list_all_hosts(conn)print(to_json(hosts))else:details = get_host_detail(conn, parser.host)print(to_json(details))if __name__ == '__main__':main() hosts.py為了讓我們動(dòng)態(tài)獲取服務(wù)器列表程序能夠應(yīng)用在Ansible中,需要為hosts.py加上可執(zhí)行權(quán)限。其他使用方式和普通的hosts文件一模一樣。
定義服務(wù)器變量
...
?
轉(zhuǎn)載于:https://www.cnblogs.com/sellsa/p/9946448.html
總結(jié)
以上是生活随笔為你收集整理的第2天:Ansible-Inventory管理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C#反射基础理解1(转)
- 下一篇: JS 学习笔记--11---内置对象(G