Ansible - Dynamic inventory - Script
程序员文章站
2022-07-05 07:58:28
...
inventory的几种方式:
静态inventory:
hosts中的分组
动态inventory:
enable inventory plugins, default: 'host_list', 'script', 'yaml', 'ini', 'auto'
这一篇,我们可以通过脚本生成inventory。必须为json格式。
0. prepare
0.1 字典 操作
0.1.1 设置值
a = dict()
a['a'] = '1'
a['b'] = '2'
inventory['all'] = dict(x = a)
inventory['group'] = dict(a)
0.2 json 操作
json.dumps(inventory, indent=4, separators=(',', ': '), sort_keys=True)
==================================================
1. 创建文件夹,写脚本
mkdir inventories
vim inventories/dynamic_inventory.py
#! /bin/env python
# 第一行必须写这个。不然无法识别。
def generate_inventory():
inventory = dict()
inventory['all'] = ...
inventory['grouop1'] = ...
return inventory
def main():
if '--list' == sys.argv[1]: # 必须有--list 参数,执行的时候会带这个参数
inventory = generate_inventory()
print (json.dumps(inventory, indent=4, separators=(',', ': '), sort_keys=True))
elif '--debug-host' == sys.argv[1]:
if len(sys.argv) > 2:
inventory = generate_inventory(filter_host=sys.argv[2])
print (json.dumps(inventory, indent=4, separators=(',', ': '), sort_keys=True))
else:
print ('{}')
else:
print ('{}')
if __name__ == "__main__":
main()
2. 配置
2.1 文件必须为可执行文件,否则无法辨认为script
chmod +x inventories/dynamic_inventory.py
2.2 ansible.cfg
vim ansible.cfg
inventory = inventories/dynamic_inventory.py
3. 输出内容
标签中必须有
’all‘
{
"group001": {
"hosts": ["host001", "host002"],
"vars": {
"var1": true
},
"children": ["group002"]
},
"group002": {
"hosts": ["host003","host004"],
"vars": {
"var2": 500
},
"children":[]
}
}
{
# results of inventory script as above go here
# ...
"_meta": {
"hostvars": {
"host001": {
"var001" : "value"
},
"host002": {
"var002": "value"
}
}
}
}
上一篇: 售票问题