Skip to content
This repository was archived by the owner on Sep 2, 2021. It is now read-only.

Commit 2723a56

Browse files
committed
Updated the drpmachines.py script
General pep8 cleanups Added debug logging Updated docs to reflect the new debug option Signed-off-by: Michael Rice <[email protected]>
1 parent 9a9b8fc commit 2723a56

File tree

2 files changed

+94
-35
lines changed

2 files changed

+94
-35
lines changed

doc/integrations/ansible.rst

+4-1
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,13 @@ Download the `drpmachines.py` inventory script to the local system to a convenie
6060

6161
::
6262

63-
curl -s https://raw.githubusercontent.com/digitalrebar/provision/master/integrations/ansible/drpmachines.py -o drpmachines.py
63+
curl -s https://raw.githubusercontent.com/digitalrebar/provision/v4/integrations/ansible/drpmachines.py -o drpmachines.py
6464
chmod +x drpmachines.py
6565
./drpmachines.py | jq
6666

67+
.. note:: If you run into problems using the drpmachines.py script try enabling the --debug flag for verbose logging.
68+
69+
6770
In order to test the Ansible integration, use the ping command. If everything is working, all the machines in the system should receive and respond to the ping command.
6871

6972
::

integrations/ansible/drpmachines.py

+90-34
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#! /usr/bin/env python
1+
#!/usr/bin/env python
22
# Copyright 2019, RackN
33
#
44
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,44 +14,81 @@
1414
# limitations under the License.
1515

1616
# pip install requests
17-
import requests, argparse, json, urllib3, os
17+
import argparse
18+
import json
19+
import logging
20+
import os
21+
22+
try:
23+
import requests
24+
import urllib3
25+
except ImportError:
26+
print("Missing requests. pip install requests")
27+
raise SystemExit
1828

1929
'''
20-
Usage: https://github.com/digitalrebar/provision/v4/tree/master/integration/ansible
30+
Usage: https://github.com/digitalrebar/provision/tree/v4/integrations/ansible
2131
2232
example: ansible -i drpmachines.py all -a "uname -a"
2333
'''
2434

25-
def main():
35+
urllib3.disable_warnings()
36+
37+
38+
def setup_logging():
39+
fmat = '%(asctime)-15s %(name)s %(message)s'
40+
logging.basicConfig(format=fmat, level=logging.DEBUG)
41+
42+
43+
def setup_parser():
44+
parser = argparse.ArgumentParser(
45+
description="Ansible dynamic inventory via DigitalRebar"
46+
)
47+
parser.add_argument(
48+
"--list",
49+
help="Ansible inventory of all of the deployments",
50+
action="store_true",
51+
dest="list_inventory"
52+
)
53+
parser.add_argument(
54+
"--host",
55+
help="Ansible inventory of a particular host",
56+
action="store",
57+
dest="ansible_host",
58+
type=str
59+
)
60+
parser.add_argument(
61+
"--debug",
62+
action="store_true",
63+
help="Enable debug logging."
64+
)
65+
return parser.parse_args()
2666

27-
inventory = { "_meta": { "hostvars": {} } }
2867

68+
def main():
69+
cli_args = setup_parser()
70+
if cli_args.debug:
71+
setup_logging()
72+
inventory = {"_meta": {"hostvars": {}}}
2973
# change these values to match your DigitalRebar installation
3074
addr = os.getenv('RS_ENDPOINT', "https://127.0.0.1:8092")
75+
logging.debug("RS_ENDPOINT: {0}".format(addr))
3176
ups = os.getenv('RS_KEY', "rocketskates:r0cketsk8ts")
77+
logging.debug("RS_KEY: {0}".format(ups))
3278
profile = os.getenv('RS_ANSIBLE', "all_machines")
79+
logging.debug("RS_ANSIBLE: {0}".format(profile))
3380
host_address = os.getenv('RS_HOST_ADDRESS', "internal")
81+
logging.debug("RS_HOST_ADDRESS: {0}".format(host_address))
3482
ansible_user = os.getenv('RS_ANSIBLE_USER', "root")
83+
logging.debug("RS_ANSIBLE_USER: {0}".format(ansible_user))
3584
parent_key = os.getenv('RS_ANSIBLE_PARENT', "ansible/children")
36-
arr = ups.split(":")
37-
user = arr[0]
38-
password = arr[1]
39-
40-
# Argument parsing
41-
parser = argparse.ArgumentParser(description="Ansible dynamic inventory via DigitalRebar")
42-
parser.add_argument("--list", help="Ansible inventory of all of the deployments",
43-
action="store_true", dest="list_inventory")
44-
parser.add_argument("--host",
45-
help="Ansible inventory of a particular host", action="store",
46-
dest="ansible_host", type=str)
47-
48-
cli_args = parser.parse_args()
85+
logging.debug("RS_ANSIBLE_PARENT: {0}".format(parent_key))
86+
user, password = ups.split(":")
87+
4988
list_inventory = cli_args.list_inventory
5089
ansible_host = cli_args.ansible_host
51-
52-
Headers = {'content-type': 'application/json'}
53-
urllib3.disable_warnings()
54-
inventory = {'all': { 'hosts': [] }, '_meta': { 'hostvars': {}} }
90+
headers = {'content-type': 'application/json'}
91+
inventory = {'all': {'hosts': []}, '_meta': {'hostvars': {}}}
5592
inventory["_meta"]["rebar_url"] = addr
5693
inventory["_meta"]["rebar_user"] = user
5794
inventory["_meta"]["rebar_profile"] = profile
@@ -61,21 +98,26 @@ def main():
6198
profiles_vars = {}
6299
hostvars = {}
63100

64-
URL = addr + "/api/v3/machines"
101+
url = addr + "/api/v3/machines"
65102
if list_inventory:
66103
if profile != "all_machines":
67-
URL += "?ansible=Eq(" + profile + ")"
104+
url += "?ansible=Eq({0})".format(profile)
68105
else:
69106
if ansible_host:
70-
URL += "?Name=" + ansible_host
107+
url += "?Name={0}".format(ansible_host)
71108
else:
72109
if profile != "all_machines":
73-
URL += "?ansible=Eq(" + profile + ")"
110+
url += "?ansible=Eq({0})".format(profile)
74111

75-
raw = requests.get(URL,headers=Headers,auth=(user,password),verify=False)
112+
raw = requests.get(
113+
url,
114+
headers=headers,
115+
auth=(user, password),
116+
verify=False
117+
)
76118

77-
IGNORE_PARAMS = ["gohai-inventory","inventory/data","change-stage/map"]
78-
if raw.status_code == 200:
119+
ignore_params = ["gohai-inventory", "inventory/data", "change-stage/map"]
120+
if raw.status_code == 200:
79121
for machine in raw.json():
80122
name = machine[u'Name']
81123
inventory["all"]["hosts"].extend([name])
@@ -87,21 +129,27 @@ def main():
87129
myvars["ansible_user"] = ansible_user
88130
myvars["rebar_uuid"] = machine[u"Uuid"]
89131
for k in machine[u'Params']:
90-
if k not in IGNORE_PARAMS:
132+
if k not in ignore_params:
91133
myvars[k] = machine[u'Params'][k]
92134
inventory["_meta"]["hostvars"][name] = myvars
93135
else:
94136
raise IOError(raw.text)
95137

96138
if ansible_host is None:
97-
groups = requests.get(addr + "/api/v3/profiles",headers=Headers,auth=(user,password),verify=False)
139+
groups = requests.get(
140+
addr + "/api/v3/profiles",
141+
headers=headers,
142+
auth=(user, password),
143+
verify=False
144+
)
98145
if groups.status_code == 200:
99146
for group in groups.json():
100147
name = group[u'Name']
101148
if name != "global" and name != "rackn-license":
102-
inventory[name] = { "hosts": [], "vars": [] }
149+
inventory[name] = {"hosts": [], "vars": []}
103150
gvars = hostvars.copy()
104-
if 'Profiles' in group.keys() and len(group[u'Profiles'])>0:
151+
if 'Profiles' in group.keys() \
152+
and len(group[u'Profiles']) > 0:
105153
inventory[name]["children"] = group[u'Profiles']
106154
for k in group[u'Params']:
107155
v = group[u'Params'][k]
@@ -110,7 +158,14 @@ def main():
110158
else:
111159
gvars[k] = v
112160
inventory[name]["vars"] = gvars
113-
hosts = requests.get(addr + "/api/v3/machines?slim=Params&Profiles=In("+name+")",headers=Headers,auth=(user,password),verify=False)
161+
hosts = requests.get(
162+
"{0}/api/v3/machines?slim=Params&Profiles=In({1})".format(
163+
addr, name
164+
),
165+
headers=headers,
166+
auth=(user, password),
167+
verify=False
168+
)
114169
if hosts.status_code == 200:
115170
inventory[name]["hosts"] = []
116171
for host in hosts.json():
@@ -121,5 +176,6 @@ def main():
121176

122177
print(json.dumps(inventory))
123178

179+
124180
if __name__ == "__main__":
125181
main()

0 commit comments

Comments
 (0)