動態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