This repository has been archived by the owner on Oct 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ansible-coupler.py
299 lines (252 loc) · 9.26 KB
/
ansible-coupler.py
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""
PoC Execute Ansible in docker containers via K8s Batch Jobs.
Triggered from a kafka topic queue from lucygw.
kubeless function deploy ansible-coupler \
--from-file ansible-coupler.py \
--handler ansible-coupler.handler \
--runtime python3.7 \
--dependencies requirements.txt
kubeless function update ansible-coupler \
--from-file ansible-coupler.py
kubeless function delete ansible-coupler
kubeless trigger kafka create ansible-coupler \
--function-selector created-by=kubeless,function=ansible-coupler \
--trigger-topic automation_v1_request
curl -sS \
'http://127.0.0.1:3303/automation/v1/play?group=goethite%2fgostint-ansible%3a2.7.5&name=dump.yml' \
-X POST \
-H "Content-type: application/json" \
--data '{}' | jq .data.log -r
Returns:
PLAY [all] *********************************************************************
TASK [Gathering Facts] *********************************************************
ok: [127.0.0.1]
TASK [debug] *******************************************************************
ok: [127.0.0.1] => {
"ansible_password": "VARIABLE IS NOT DEFINED!"
}
TASK [debug] *******************************************************************
ok: [127.0.0.1] => {
"ansible_connection": "local"
}
TASK [shell] *******************************************************************
changed: [127.0.0.1]
PLAY RECAP *********************************************************************
127.0.0.1 : ok=4 changed=1 unreachable=0 failed=0
"""
import sys
import traceback
import time
import json
import base64
import tempfile
from kubernetes import client, config
from kafka import KafkaProducer
config.load_incluster_config()
v1 = client.CoreV1Api()
def get_job_status(batchApi, namespace, job_name):
batchApi_resp = {}
try:
batchApi_resp = batchApi.read_namespaced_job(
namespace=namespace,
name=job_name
)
except client.rest.ApiException as e:
print("Error calling k8s batch api: %s\n" % e)
except Exception as err:
print(str(err))
print(traceback.format_exc())
return
# print("read batchApi_resp:", batchApi_resp)
return batchApi_resp.status
def handler(event, context):
print("event:", event)
# Establish the producer for each function call, cannot be global...
producer = KafkaProducer(
bootstrap_servers=['kafka.kubeless.svc.cluster.local:9092'])
try:
wrapped(event, context, producer)
except Exception as err:
try:
response = {
"event_uuid": event["data"]["event_uuid"],
"code": 500,
"error": str(err),
"stacktrace": traceback.format_exc()
}
new_event = bytearray(json.dumps(response), encoding='utf-8')
producer.send('automation_v1_response', key=b'event',
value=new_event).get(timeout=30)
producer.flush(timeout=5)
except Exception as err:
print(str(err))
print(traceback.format_exc())
def sendError(event, code, err, producer):
try:
response = {
"event_uuid": event["data"]["event_uuid"],
"code": code,
"error": err,
"stacktrace": ""
}
new_event = bytearray(json.dumps(response), encoding='utf-8')
producer.send('automation_v1_response', key=b'event',
value=new_event).get(timeout=30)
producer.flush(timeout=5)
except Exception as err:
print(str(err))
print(traceback.format_exc())
def wrapped(event, context, producer):
body = {}
if event["data"]["body"] is not None and event["data"]["body"] != "":
body = json.loads(
base64.b64decode(event["data"]["body"])
)
path = event["data"]["path"]
form = event["data"]["form"]
method = event["data"]["method"]
headers = event["data"]["headers"]
print("%s: %s form: %s, body: %s" % (method, path, form, body))
namespace = "default"
# Routing
if path == "/ping":
body = {
"api_version": "batch/v1",
"kind": "Job",
"metadata": {"name": "myjob"},
"spec": {
"template": {
"spec": {
"containers": [
{
"name": "myjob",
# "image": "jmal98/ansiblecm:2.5.5",
"image": "goethite/gostint-ansible:2.7.5",
"imagePullPolicy": "Always",
"command": ["ansible"],
"args": ["-m", "ping", "127.0.0.1"]
}
],
"restartPolicy": "Never"
}
}
}
}
send(event, namespace, body, producer)
elif path == "/play":
# TODO: demo loose coupling here
group = form.get("group")[0]
name = form.get("name")[0]
if group is None or group == "":
sendError(event, 501, "param group is missing", producer)
return
if name is None or name == "":
sendError(event, 501, "param name is missing", producer)
return
body = {
"api_version": "batch/v1",
"kind": "Job",
"metadata": {"name": "myjob"}, # TODO:
"spec": {
"backoffLimit": 0,
"template": {
"spec": {
"initContainers": [
{
"name": "init-inventory",
"image": "busybox",
"command": [
"sh",
"-c",
"echo '127.0.0.1 ansible_connection=local' > /tmp/inv/hosts"
],
"volumeMounts": [
{
"mountPath": "/tmp/inv",
"name": "inventory"
}
]
}
],
"containers": [
{
"name": "myjob", # TODO:
# "image": "jmal98/ansiblecm:2.5.5",
# "image": "goethite/gostint-ansible:2.7.5",
"image": group,
"imagePullPolicy": "Always",
# "command": ["ansible"],
"args": [
"-i", "/tmp/inv/hosts",
# "dump.yml"
name
],
"volumeMounts": [
{
"mountPath": "/tmp/inv",
"name": "inventory"
}
]
}
],
"volumes": [
{
"name": "inventory",
"medium": "Memory",
"emptyDir": {}
}
],
"restartPolicy": "Never"
}
}
}
}
send(event, namespace, body, producer)
else:
sendError(event, 501, "Path %s not implemented" % path, producer)
def send(event, namespace, body, producer):
batchApi = client.BatchV1Api()
batchApi_resp = batchApi.create_namespaced_job(
namespace=namespace,
body=body
)
# print("create batchApi_resp:", batchApi_resp)
job_status = {}
while True:
time.sleep(1)
job_status = get_job_status(batchApi, namespace, "myjob") # TODO:
if job_status.active is None:
break
pods = v1.list_namespaced_pod(
namespace, label_selector="job-name=myjob") # TODO:
pod = pods.items[0]
pod_name = pod.metadata.name
# Get log from job pod
pod_log = v1.read_namespaced_pod_log(
pod_name,
namespace,
# timestamps=True
tail_lines=100 # limit to last n lines
)
# print("pod_log:", pod_log)
batchApi.delete_namespaced_job(
namespace=namespace,
name="myjob",
body={}
)
v1.delete_namespaced_pod(pod_name, namespace, body={})
response = {
"event_uuid": event["data"]["event_uuid"],
"data": {
"status": {
"active": job_status.active,
"failed": job_status.failed,
"succeeded": job_status.succeeded
},
"log": pod_log
}
}
new_event = bytearray(json.dumps(response), encoding='utf-8')
producer.send('automation_v1_response', key=b'event',
value=new_event).get(timeout=30)
producer.flush(timeout=5)