Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
181 lines (157 loc) · 6.01 KB
/
Copy pathapp.py
File metadata and controls
181 lines (157 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import ansible_runner
import ast
from flask import Flask, request
import json
import os
import sys
import yaml
app = Flask(__name__)
KEYS_DIR = "/keys"
WORK_DIR = "/var/tmp"
ROLES_DIR = os.environ.get("ROLES_DIR", "{}/roles".format(WORK_DIR))
CONSTRUCTS = {}
def generate_setup(spec):
with open("{dir}/{id}.yaml".format(dir=WORK_DIR, id=spec['id']), 'w') as f:
for role in spec['setup']:
d = [{
"name": "Deploy {role} roles".format(role=role['type']),
"hosts": role['type'],
"roles" : [{
"role": "{dir}/{url}".format(dir=ROLES_DIR, url=role['url']),
"vars": role['properties']
}]
}]
yaml.dump(d, f, default_flow_style=False)
return { 'message': "{id} setup completed successfully.".format(id=spec['id']) }
def generate_inventory(spec):
with open("{dir}/inventory-{id}.yaml".format(dir=WORK_DIR, id=spec['id']), 'w') as f:
i = {"all": {
"hosts": {},
"children": {}
}}
for host in spec['inventory']:
i['all']['hosts'][host['name']] = {
"ansible_host": host['address'],
"ansible_user": host['user']
}
for role in host['roles']:
if not i['all']['children'].get(role):
i['all']['children'][role] = { "hosts": { host['name']: {}} }
else:
i['all']['children'][role]['hosts'][host['name']] = {}
yaml.dump(i, f, default_flow_style=False)
return { 'message': "{id} inventory generation completed successfully.".format(id=spec['id']) }
def load_construct_file(cid):
data = {}
with open("{dir}/{id}.yaml".format(dir=WORK_DIR, id=cid)) as file:
data = yaml.safe_load(file)
return data
def update_constructs_datastore(construct):
CONSTRUCTS[construct['id']] = construct['setup']
@app.route("/v1/key", methods=['POST'])
def key():
if 'ssh' in request.files:
file = request.files['ssh']
path = "{}/{}".format(KEYS_DIR, file.filename)
if not os.path.exists(KEYS_DIR):
os.makedirs(KEYS_DIR)
file.save(path)
os.chmod(path, 0o600)
return { 'message': "SSH key, {key}, successfully uploaded.".format(key=file.filename) }
return { 'message': "No SSH key was provided for upload." }
@app.route("/v1/view/<cid>", methods=['GET'])
def view(cid):
if request.method == 'GET':
cmd_args = [
'--inventory',
"{dir}/inventory-{id}.yaml".format(dir=WORK_DIR, id=cid),
'--module-name',
'setup'
]
if 'ssh_key' in request.args and os.path.exists("{}/{}".format(KEYS_DIR, request.args['ssh_key'])):
cmd_args.extend(["--private-key", "{}/{}".format(KEYS_DIR, request.args['ssh_key'])])
else:
cmd_args.append("--ask-pass")
if 'target' in request.args:
cmd_args.append(request.args['target'])
else:
cmd_args.append('all')
if 'hosts' in request.args:
cmd_args.extend(['--limit', request.args['hosts']])
if 'filter' in request.args:
cmd_args.extend(['-a', "filter='{}'".format(request.args['filter'])])
out, err, rc = ansible_runner.run_command(
executable_cmd='ansible',
cmdline_args=cmd_args,
input_fd=sys.stdin
)
if rc == 0:
trim_start = out.find('{')
out = out[trim_start:]+'}'
return {
'id': cid,
'message': "{id} successfully viewed.".format(id=cid),
'view': json.loads(out.replace("\n", "").replace(" ", "")),
}
else:
return {
'id': cid,
'message': err,
'rc': rc
}
@app.route("/v1/construct", methods=['GET', 'POST'])
def construct():
if request.method == 'POST':
data = request.get_json(force=True)
generate_inventory(data)
generate_setup(data)
cmd_args = [
'{dir}/{id}.yaml'.format(dir=WORK_DIR, id=data['id']),
'-i',
'{dir}/inventory-{id}.yaml'.format(dir=WORK_DIR, id=data['id']),
'-v'
]
if 'ssh_key' in request.args and os.path.exists("/{}/{}".format(KEYS_DIR, request.args['ssh_key'])):
cmd_args.extend(["--private-key", "/{}/{}".format(KEYS_DIR, request.args['ssh_key'])])
else:
cmd_args.append("--ask-pass")
_, err, rc = ansible_runner.run_command(
executable_cmd='ansible-playbook',
cmdline_args=cmd_args,
input_fd=sys.stdin,
output_fd=sys.stdout,
error_fd=sys.stderr,
)
if rc == 0:
update_constructs_datastore(data)
return {
'id': data['id'],
'message': "{id}, successfully constructed.".format(id=data['id']),
'construct': load_construct_file(data['id']),
}
else:
return {
'id': data['id'],
'message': err,
'rc': rc
}
elif request.method == 'GET':
if 'id' in request.args and request.args['id'] in CONSTRUCTS:
return {
'id': request.args['id'],
'message': "{id} successfully retrieved.".format(id=request.args['id']),
'construct': load_construct_file(request.args['id'])
}
elif 'id' in request.args and request.args['id'] not in CONSTRUCTS:
return {
'id': request.args['id'],
'message': "Retrieval failed - construct does not exist.".format(id=request.args['id'])
}
else:
ret = {
'message': "Constructs successfully retrieved",
'constructs': []
}
for k in CONSTRUCTS.keys():
ret['constructs'].append({ k: load_construct_file(k) })
return ret