一. ansible 资源inventory 动态,脚本规范说明需要实现--list ,--host 选项,并输出json数据即可。
1. --list 输出:
[root@master_101 ansible]# ./dy_host.py --list { "all": [ "192.168.8.101", "192.168.8.102" ], "web": { "hosts": [ "192.168.8.101" ], "vars": { "aa": 10 } }, "web2": { "hosts": [ "192.168.8.101", "192.168.8.102" ] } }
## 其中 hosts,vars 是关键字符,不能改变
2. --host 输出:
[root@master_101 ansible]# ./dy_host.py --host 192.168.8.102 { "ansible_host": "192.168.8.102", "ansible_port": 22, "ansible_user": "sun", "ansible_password": "qweasd", "ansible_become": "true", "ansible_become_method": "su", "ansible_become_user": "root", "ansible_become_pass": "qweasd" }
3. _meta 关键字使用
如果inventory脚本返回的顶级元素为”_meta”,它可能会返回所有主机的变量.如果这个元素中包含一个名为”hostvars”的value,这个inventory脚本对每一台主机使用调用时候,就不会调用 --host 选项对目标主机进行操作,而是使用hostvars 中目标主机的信息对目标主机进行操作。
[root@master_101 ansible]# ./dy_host.py --list { "_meta": { "hostvars": { "192.168.8.101": { "ansible_user": "root", "ansible_password": "qweasd" }, "192.168.8.102": { "ansible_user": "sun", "ansible_password": "qweasd", "ansible_become": "true", "ansible_become_method": "su", "ansible_become_user": "root", "ansible_become_pass": "qweasd" } } }, "all": [ "192.168.8.101", "192.168.8.102" ], "web": { "hosts": [ "192.168.8.101" ], "vars": { "aa": 10 } }, "web2": { "hosts": [ "192.168.8.101", "192.168.8.102" ] } }
4 脚本例子
[root@master_101 ansible]# cat dy_host.py
#!/usr/bin/env python3
#coding:utf8
import json
import sys
def group():
hosts = {
'_meta' : {
"hostvars": {
'192.168.8.101':{'ansible_user':'root','ansible_password':'qweasd'},
'192.168.8.102':{'ansible_user':'sun','ansible_password': 'qweasd',
'ansible_become':'true',
'ansible_become_method':'su',
'ansible_become_user':'root',
'ansible_become_pass':'qweasd'
}
}
},
'all': ['192.168.8.101','192.168.8.102'],
'web':{"hosts": ['192.168.8.101'],'vars': {'aa':10},},
'web2': {"hosts":['192.168.8.101','192.168.8.102']}
}
print(json.dumps(hosts,indent=4))
def host(ip):
hosts = {
"192.168.8.101": {
"ansible_host":"192.168.8.101",
"ansible_port":22,
"ansible_user":"root",
"ansible_pass":"qweasd"
},
"192.168.8.102": {
"ansible_host":"192.168.8.102",
"ansible_port":22,
"ansible_user":"sun",
"ansible_password":"qweasd",
'ansible_become':'true',
'ansible_become_method':'su',
'ansible_become_user':'root',
'ansible_become_pass':'qweasd'
}
}
j = json.dumps(hosts[ip],indent=4)
print(j)
def main():
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
group()
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
host(sys.argv[2])
else:
print("Usage: %s --list or --host <hostname>" % sys.argv[0])
if __name__ == '__main__':
main()
转载于:https://blog.51cto.com/5766902/2402580