Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
trying to make a useable jss to ansible inventory based off groups of last reported ip's from the jss api.
#!/usr/bin/python
"""
JSS + Ansible inventory
A dictionary of lists of computers by group name.
Heavily influenced by https://gist.github.com/BadStreff/0af3f881de162182eaaff406ce7a7f0d
with help from https://gist.github.com/chilcote/fb670103b8e90aaea67dee0ffc6cc983
I'd really like to avoid caching, as any sort of timeout won't be appropriate since I
use Ansible for the Mac very rarely.
"""
import requests
import argparse
from ConfigParser import SafeConfigParser
'''Load in our auth settings'''
config = SafeConfigParser()
config.read("./jss.ini")
jss_url = config.get('jss', 'url')
jss_user = config.get('jss', 'user')
jss_pass = config.get('jss', 'password')
'''Parse CLI args for Ansible (only need --list)'''
parser = argparse.ArgumentParser()
parser.add_argument('--list', action='store_true')
parser.add_argument('--host', action='store')
args = parser.parse_args()
'''Define a wrapper for our API calls to the JSS'''
s = requests.Session()
s.auth = (jss_user, jss_pass)
s.headers.update({'Accept': 'application/json'})
def requests_json(jss_user, jss_pass, jss_url, category):
'''return json data from jss'''
try:
r = s.get(jss_url + '/JSSResource' + category)
return r.status_code, r.json()
except TypeError as err:
print 'Cannot connect to JSS.'
print err
exit(1)
'''
eid = API endpoint.
oid = object id.
'''
def get_all_objects(eid=None):
r_code, d = requests_json(jss_user, jss_pass, jss_url, '/' + eid)
if r_code == 200:
return d
return None
def get_object(eid=None, oid=None):
r_code, d = requests_json(jss_user, jss_pass, jss_url, '/' + eid + '/id/' + str(oid))
if r_code == 200:
return d
return None
'''Empty inventory for testing and for throwing alt args at'''
def empty_inventory():
return {'_meta': {'hostvars': {}}}
def jss_inventory():
all = get_all_objects(eid='computers')
computer_ip_addresses = [
str(get_object(eid='computers', oid=x['id'])
['computer']['general']['last_reported_ip'])
for x in all['computers']
]
inventory = {'all': computer_ip_addresses,
'_meta': {'hostvars': {}}}
for group in get_all_objects(eid='computergroups')['computer_groups']:
group = get_object(eid='computergroups', oid=group['id'])
group_name = str(group['computer_group']['name'].replace(' ', '_'))
inventory[group_name] = []
for computer in group['computer_group']['computers']:
inventory[group_name].append(
str(get_object(eid='computers', oid=computer['id'])
['computer']['general']['last_reported_ip'])
)
return inventory
def main():
if args.list:
print jss_inventory()
elif args.host:
print empty_inventory()
else:
print empty_inventory()
if __name__ == "__main__":
main()
[jss]
url = https://your.jss.com:8443
user = an_api_user
password = super_secret_mess_of_random_characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment