forked from antonbabenko/modules.tf-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
executable file
·180 lines (147 loc) · 5.88 KB
/
handler.py
File metadata and controls
executable file
·180 lines (147 loc) · 5.88 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
#!/usr/bin/env python3
import json
import os
import shutil
from pprint import pformat, pprint
import requests
from modulestf.cloudcraft.graph import populate_graph
from modulestf.const import FINAL_DIR
from modulestf.convert import convert_graph_to_modulestf_config
from modulestf.logger import setup_logging
from modulestf.render import prepare_render_dirs, render_from_modulestf_config
from modulestf.upload import upload_file_to_s3
logger = setup_logging()
def load_data(event):
body = event.get("body")
logger.info("body = %s" % body)
qs = event.get("queryStringParameters")
logger.info("queryStringParameters = %s" % qs)
if body is None and qs is None:
raise ValueError("Some query string parameters should be defined or use HTTP POST method", 400)
if qs is None:
blueprint_url = localfile = None
else:
blueprint_url = qs.get("cloudcraft")
localfile = qs.get("localfile")
if body:
data = json.loads(body)
elif blueprint_url:
r = requests.get(blueprint_url)
data = r.json()
logger.info("Blueprint url: %s, response code: %s" % (blueprint_url, r.status_code))
if 403 == r.status_code:
raise ValueError("Sharing has been disabled for this blueprint." +
" You have to enable it by clicking 'Export' -> 'Get shareable link'" +
" on https://cloudcraft.co/app/", 403)
elif r.status_code >= 500:
raise ValueError("Something went wrong on cloudcraft side. Can't fetch specified blueprint." +
" Check URL and try again later.", 404)
elif localfile:
file = open(localfile, 'r')
data = json.load(file)
else:
raise ValueError("'cloudcraft' or 'localfile' query string parameter should be defined", 400)
print("event = %s" % json.dumps(event))
return data
def validation_result(config):
return True
def handler(event, context):
link = ""
# ALB response is different:
# https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#respond-to-load-balancer
request_from_lb = bool(event.get("requestContext", {}).get("elb"))
http_method = event.get("httpMethod")
is_validate_action = event.get("path") == "/validate"
if http_method == "OPTIONS":
return {
"isBase64Encoded": False,
"statusCode": 200,
"statusDescription": "200 OK",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
# "Access-Control-Allow-Credentials": True # this header is not allowed by ALB
},
}
if request_from_lb and event.get("path") == "/healthz":
return {
"isBase64Encoded": False,
"statusCode": 200,
"statusDescription": "200 OK",
"headers": {
"Content-Type": "text/html"
},
"body": "Health OK"
}
try:
data = load_data(event)
except ValueError as error:
logger.error(error)
if request_from_lb:
return {
"isBase64Encoded": False,
"statusCode": error.args[1],
"statusDescription": str(error.args[1]) + " Server Error",
"headers": {
"Content-Type": "text/html",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
},
"body": error.args[0],
}
else:
return {
"body": error.args[0],
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": True
},
"statusCode": error.args[1],
}
# logger.info(pformat(data, indent=2))
graph = populate_graph(data)
config = convert_graph_to_modulestf_config(graph)
if is_validate_action:
return {
"isBase64Encoded": False,
"statusCode": 200,
"statusDescription": "200 OK",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
},
"body": json.dumps(validation_result(config))
}
prepare_render_dirs()
render_from_modulestf_config(config, source=graph.source, regions=graph.regions)
# Do not upload to S3 when working locally
if not os.environ.get("IS_LOCAL"):
shutil.make_archive("archive", "zip", FINAL_DIR)
link = upload_file_to_s3(filename="archive.zip")
if request_from_lb:
return {
"isBase64Encoded": False,
"headers": {
"Location": link,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
},
"statusCode": 302,
"statusDescription": "302 Found",
}
else:
return {
"body": "",
"headers": {
"Location": link,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": True
},
"statusCode": 302,
}