动态Inventory脚本的Python实现,简单方便清晰,可根据环境本身随机定制。python
1. 直接上代码:数据库
#!/usr/bin/python3 ''' 给予Python的动态Inventory脚本举例 ''' import json import argparse class ExampleInventory: def __init__(self): self.inventory = {} self.read_cli_args() # 定义--list选项 if self.args.list: self.inventory = self.example_inventory() # 定义--host选项 elif self.args.host: self.inventory = self.empty_inventory() # 若是没有就返回一个空的Inventory else: self.inventory = self.empty_inventory() print(json.dumps(self.inventory)) def example_inventory(self): return { 'group': { 'hosts': ['10.0.10.35', '10.0.10.36'], 'vars': { 'ansible_ssh_user': 'root', 'ansible_ssh_private_key_file': '/root/.ssh/id_rsa', 'example_variable': 'value' } }, '_meta': { 'hostvars': { '10.0.10.35': { 'host_specific_var': 'foo' }, '10.0.10.36': { 'host_specific_var': 'bar' } } } } # 测试所用的空的Inventory def empty_inventory(self): return {'_meta': {'hostvars': {}}} # 参数解析 def read_cli_args(self): parser = argparse.ArgumentParser() parser.add_argument('--list', action='store_true') parser.add_argument('--host', action='store') self.args = parser.parse_args() ExampleInventory()
执行:json
./inventory.py --list
结果:网络
{ "group": { "hosts": ["10.0.10.35", "10.0.10.36"], "vars": { "ansible_ssh_user": "root", "ansible_ssh_private_key_file": "/root/.ssh/id_rsa", "example_variable": "value" } }, "_meta": { "hostvars": { "10.0.10.35": { "host_specific_var": "foo" }, "10.0.10.36": { "host_specific_var": "bar" } } } }
2. 使用Ansible来调用这个脚原本测试这两台虚拟机的网络是否正常ssh
ansible all -i inventory.py -m ping
运行结果以下:ide
10.0.10.36 | SUCCESS => { "changed": false, "ping": "pong" } 10.0.10.35 | SUCCESS => { "changed": false, "ping": "pong" }
3. 验证主机所设置变量是否生效:函数
ansible all -i inventory.py -m debug -a 'var=host_specific_var'
运行结果以下:测试
10.0.10.35 | SUCCESS => { "host_specific_var": "foo" } 10.0.10.36 | SUCCESS => { "host_specific_var": "bar"
总结:spa
生产环境中咱们只须要根据业务特性修改example_inventory()函数,既能够经过调用外部API也能够给予CMDB系统去数据库查询所需主机信息,将其最终转化为JSON格式代码,供Ansible使用debug