我需要从某些url获取主机列表,该URL向我返回主机和变量的列表,并且它会经常更新。因此,我尝试使用python脚本生成动态广告资源json。我已经验证了多种模式,但始终会返回以下错误:
sai @ test [〜] $ ansible -i fetch_hosts.py -m ping全部
[警告]:提供的主机列表为空,只有localhost可用。请注意,隐式本地主机与“ all”不匹配
我觉得我的脚本正在返回Ansible期望的值,但仍然失败。如果我必须设置和配置值或进行任何设置才能使它工作,有人可以帮我吗?
可用版本: [〜] ansible --version 安思2.8.1 配置文件= /etc/ansible/ansible.cfg 配置的模块搜索路径= [u'/ home / user / summigari02 / .ansible / plugins / modules',u'/ usr / share / ansible / plugins / modules'] ansible python模块位置= /usr/lib/python2.7/site-packages/ansible 可执行位置= / bin / ansible python版本= 2.7.5(默认值,2018年9月12日,05:31:16)[GCC 4.8.5 20150623(Red Hat 4.8.5-36)]
#!/usr/bin/python
import requests
import json
import sys
URL = "http://something.com/api/hosts.json"
env = 'Dev'
if len(sys.argv) > 1:
env = str(sys.argv[1])
responses = requests.get(URL)
info = json.loads(responses.content)
groups = {}
groups = {'_meta': {'hostvars': {}}}
for resp in info:
if resp['site']['name'] == env:
value = str(resp['internal_category']['name'])
if not value in groups:
groups[value] = {}
groups[value]['hosts'] = []
groups[value]['hosts'].append(str(resp['name']))
groups['all']={}
groups['all']["children"] = []
for group in groups.keys():
if group != 'all':
groups['all']["children"].append(group)
print (json.dumps(groups, indent=4, sort_keys=True))
输出:
{
"DatafeedWeb": {
"hosts": [
"mdsbuilddeva01",
"unixbuilddeva01",
"unixbuilddeva02"
]
},
"Content": {
"hosts": [
"tpdeva13",
"qalertdeva01",
"siacdeva01"
},
"Storage": {
"hosts": [
"qtdeva03",
"qtdeva04",
"qtdeva05",
"qtdeva01",
"qtdeva06"
]
},
"TS": {
"hosts": [
"tsdeva04",
"tsdeva05",
]
},
"Web": {
"hosts": [
"qtwebdeva01"
]
},
"_meta": {
"hostvars": {}
},
"all": {
"children": [
"Web",
"DatafeedWeb",
"Storage",
"Hadoop",
"TS"
]
}
}