1.Ansible Inventory 介绍;
Ansible Inventory 是包含静态 Inventory 和动态 Inventory 两部分的,静态 Inventory 指的是在文件中指定的主机和组,动态 Inventory 指通过外部脚本获取主机列表,并按照 ansible 所要求的格式返回给 ansilbe 命令的。这部分一般会结合 CMDB 资管系统、云计算平台等获取主机信息。由于主机资源一般会动态的进行增减,而这些系统一般会智能更新。我们可以通过这些工具提供的 API 或者接入库查询等方式返回主机列表。
2.mysql数据结构如下;
3.本章节演示从mysql数据作为数据源生成动态ansible 主机;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#!/usr/bin/env python36 def commmysql(): import mysql.connector import json mydb = mysql.connector.connect( host = "192.168.1.23" , # 数据库主机地址 user = "root" , # 数据库用户名 passwd = "123456" , database = "test" ) mycursor = mydb.cursor() mycursor.execute( " select host,`group` from ansible_hosts;" ) #mycursor. myresult = mycursor.fetchall() data = dict () #####查询出group分组并去重############# groups = list ( set ([i[ 1 ].decode() for i in myresult])) data[ "all" ] = { "children" : groups} data[ "_meta" ] = { "hostvars" : {}} for group in groups: data[group] = dict () data[group][ "hosts" ] = list () for x in myresult: if x[ 1 ].decode( "utf-8" ) = = group: data[group][ "hosts" ].append(x[ 0 ].decode( "utf-8" )) return json.dumps(data,indent = 3 ) def main(): from optparse import OptionParser parse = OptionParser() parse.add_option( "-l" , "--list" , action = "store_true" , dest = "list" , default = False ) (option, arges) = parse.parse_args() if option. list : print (commmysql()) else : print ( "abc" ) if __name__ = = '__main__' : from optparse import OptionParser parse = OptionParser() parse.add_option( "-l" , "--list" , action = "store_true" , dest = "list" , default = False ) (option, arges) = parse.parse_args() if option. list : print (commmysql()) else : print ( "test" ) |
4.数据格式结果如下;
5.ansible 执行动态主机如下;
总结
以上所述是小编给大家介绍的Python中的 ansible 动态Inventory 脚本,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
原文链接:https://blog.51cto.com/breaklinux/2384877