-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi_creator.py
229 lines (168 loc) · 7.11 KB
/
api_creator.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
#!/usr/bin/env python
"""
api_creator.py:
Cloudformation custom resource lambda handler which performs the following tasks:
* injects lambda functions arns (created during CDK deployment) into the
OpenAPI 3 spec file (api_definition.yaml)
* deploys or updates the API Gateway stage using the OpenAPI 3 spec file (api_definition.yaml)
* deletes the API Gateway stage (if the Cloudformation operation is delete)
"""
import json
import logging
import os
import boto3
import yaml
# set logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# environment variables
aws_region = os.environ['AWS_REGION']
# boto3 clients
apigateway_client = boto3.client('apigatewayv2')
s3_client = boto3.client('s3')
def replace_placeholders(template_file: str, substitutions: dict) -> str:
import re
def from_dict(dct):
def lookup(match):
key = match.group(1)
return dct.get(key, f'<{key} not found>')
return lookup
with open (template_file, "r") as template_file:
template_data = template_file.read()
# perform the subsitutions, looking for placeholders @@PLACEHOLDER@@
api_template = re.sub('@@(.*?)@@', from_dict(substitutions), template_data)
return api_template
def get_api_by_name(api_name: str) -> str:
get_apis = apigateway_client.get_apis()
for api in get_apis['Items']:
if api['Name'] == api_name:
return api['ApiId']
return None
def create_api(api_template: str) -> str:
api_response = apigateway_client.import_api(
Body=api_template,
FailOnWarnings=True
)
return api_response['ApiEndpoint'], api_response['ApiId']
def update_api(api_template: str, api_name: str) -> str:
api_id = get_api_by_name(api_name)
if api_id is not None:
api_response = apigateway_client.reimport_api(
ApiId=api_id,
Body=api_template,
FailOnWarnings=True
)
return api_response['ApiEndpoint'], api_response['ApiId']
def delete_api(api_name: str) -> None:
if get_api_by_name(api_name) is not None:
apigateway_client.delete_api(
ApiId=get_api_by_name(api_name)
)
def deploy_api(
api_id: str,
api_stage_name: str,
api_access_logs_arn: str,
throttling_burst_limit: int,
throttling_rate_limit: int
) -> None:
apigateway_client.create_stage(
AccessLogSettings={
'DestinationArn': api_access_logs_arn,
'Format': '$context.identity.sourceIp - - [$context.requestTime] "$context.httpMethod $context.routeKey $context.protocol" $context.status $context.responseLength $context.requestId $context.integrationErrorMessage'
},
ApiId=api_id,
StageName=api_stage_name,
AutoDeploy=True,
DefaultRouteSettings={
'DetailedMetricsEnabled': True,
'ThrottlingBurstLimit':throttling_burst_limit,
'ThrottlingRateLimit': throttling_rate_limit
}
)
def delete_api_deployment(api_id: str, api_stage_name: str) -> None:
try:
apigateway_client.get_stage(
ApiId=api_id,
StageName=api_stage_name
)
apigateway_client.delete_stage(
ApiId=api_id,
StageName=api_stage_name
)
except apigateway_client.exceptions.NotFoundException as e:
logger.error(f"Stage name: {api_stage_name} for api id: {api_id} was not found during stage deletion. This is an expected error condition and is handled in code.")
except Exception as e:
raise ValueError(f"Unexpected error encountered during api deployment deletion: {str(e)}")
def publish_api_documentation(bucket_name: str, api_definition: str) -> None:
api_definition_json=json.dumps(yaml.safe_load(api_definition))
with open("/tmp/swagger.json", "w") as swagger_file:
swagger_file.write(api_definition_json)
# Upload the file
try:
s3_client.upload_file("/tmp/swagger.json", bucket_name, "swagger.json")
except Exception as e:
logging.error(str(e))
raise ValueError(str(e))
def lambda_handler(event, context):
# print the event details
logger.debug(json.dumps(event, indent=2))
props = event['ResourceProperties']
api_gateway_access_log_group_arn = props['ApiGatewayAccessLogsLogGroupArn']
api_integration_ping_lambda = props['ApiIntegrationPingLambda']
api_integration_greetings_lambda = props['ApiIntegrationGreetingLambda']
api_name = props['ApiName']
api_stage_name = props['ApiStageName']
api_documentation_bucket_name = props['ApiDocumentationBucketName']
throttling_burst_limit = int(props['ThrottlingBurstLimit'])
throttling_rate_limit = int(props['ThrottlingRateLimit'])
lambda_substitutions = {
"API_NAME": api_name,
"API_INTEGRATION_PING_LAMBDA": f"arn:aws:apigateway:{aws_region}:lambda:path/2015-03-31/functions/{api_integration_ping_lambda}/invocations",
"API_INTEGRATION_GREETING_LAMBDA": f"arn:aws:apigateway:{aws_region}:lambda:path/2015-03-31/functions/{api_integration_greetings_lambda}/invocations"
}
api_template = replace_placeholders("api_definition.yaml", lambda_substitutions)
if event['RequestType'] != 'Delete':
if get_api_by_name(api_name) is None:
logger.debug("Creating API")
api_endpoint, api_id = create_api(api_template)
deploy_api(api_id, api_stage_name, api_gateway_access_log_group_arn, throttling_burst_limit, throttling_rate_limit)
publish_api_documentation(api_documentation_bucket_name, api_template)
output = {
'PhysicalResourceId': f"generated-api",
'Data': {
'ApiEndpoint': api_endpoint,
'ApiId': api_id,
'ApiStageName': api_stage_name
}
}
return output
else:
logger.debug("Updating API")
api_endpoint, api_id = update_api(api_template, api_name)
# delete and redeploy the stage after updating the api definition
delete_api_deployment(api_id, api_stage_name)
deploy_api(api_id, api_stage_name, api_gateway_access_log_group_arn, throttling_burst_limit, throttling_rate_limit)
publish_api_documentation(api_documentation_bucket_name, api_template)
output = {
'PhysicalResourceId': f"generated-api",
'Data': {
'ApiEndpoint': api_endpoint,
'ApiId': api_id,
'ApiStageName': api_stage_name
}
}
return output
if event['RequestType'] == 'Delete':
logger.debug("Deleting API")
if get_api_by_name(api_name) is not None:
delete_api(api_name)
output = {
'PhysicalResourceId': f"generated-api",
'Data': {
'ApiEndpoint': "Deleted",
'ApiId': "Deleted",
'ApiStageName': "Deleted"
}
}
logger.info(output)
return output