-
Notifications
You must be signed in to change notification settings - Fork 16
/
run_create_lambda_sqs.py
executable file
·216 lines (170 loc) · 7.91 KB
/
run_create_lambda_sqs.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
#!/usr/bin/env python3
import os
import re
import subprocess
import time
from env import env
from run_common import AWSCli
from run_common import print_message
from run_common import print_session
from run_common import re_sub_lines
from run_common import read_file
from run_common import write_file
from run_create_lambda_iam import create_iam_for_lambda
def run_create_lambda_sqs(function_name, settings, options):
aws_cli = AWSCli(settings['AWS_REGION'])
description = settings['DESCRIPTION']
folder_name = settings.get('FOLDER_NAME', function_name)
git_url = settings['GIT_URL']
phase = env['common']['PHASE']
sqs_name = settings['SQS_NAME']
mm = re.match(r'^.+/(.+)\.git$', git_url)
if not mm:
raise Exception()
git_folder_name = mm.group(1)
################################################################################
print_session(f'create {function_name}')
################################################################################
print_message(f'download template: {git_folder_name}')
subprocess.Popen(['mkdir', '-p', './template']).communicate()
if not os.path.exists(f'template/{git_folder_name}'):
branch = options.get('branch', 'master' if phase == 'dv' else phase)
print(f'branch: {branch}')
git_command = ['git', 'clone', '--depth=1', '-b', branch, git_url]
subprocess.Popen(git_command, cwd='template').communicate()
if not os.path.exists(f'template/{git_folder_name}'):
raise Exception()
deploy_folder = f'template/{git_folder_name}/lambda/{folder_name}'
################################################################################
print_message(f'create iam: {function_name}')
role_created = create_iam_for_lambda(git_folder_name, folder_name, function_name)
if role_created:
print_message('wait 10 seconds to let iam role and policy propagated to all regions...')
time.sleep(10)
################################################################################
cmd = ['sqs', 'get-queue-url']
cmd += ['--queue-name', sqs_name]
queue_url = aws_cli.run(cmd)['QueueUrl']
cmd = ['sqs', 'get-queue-attributes']
cmd += ['--queue-url', queue_url]
cmd += ['--attribute-names', 'QueueArn']
queue_arn = aws_cli.run(cmd)['Attributes']['QueueArn']
################################################################################
print_message(f'packaging lambda: {function_name}')
print_message('cleanup generated files')
subprocess.Popen(['git', 'clean', '-d', '-f', '-x'], cwd=deploy_folder).communicate()
requirements_path = f'{deploy_folder}/requirements.txt'
if os.path.exists(requirements_path):
print_message('install dependencies')
cmd = ['pip3', 'install', '-r', requirements_path, '-t', deploy_folder]
subprocess.Popen(cmd).communicate()
settings_path = f'{deploy_folder}/settings_local_sample.py'
if os.path.exists(settings_path):
print_message('create environment values')
lines = read_file(settings_path)
option_list = list()
option_list.append(['PHASE', phase])
for key in settings:
value = settings[key]
option_list.append([key, value])
for oo in option_list:
lines = re_sub_lines(lines, f'^({oo[0]}) .*', f'\\1 = \'{oo[1]}\'')
write_file(f'{deploy_folder}/settings_local.py', lines)
print_message('zip files')
cmd = ['zip', '-r', 'deploy.zip', '.']
subprocess.Popen(cmd, cwd=deploy_folder).communicate()
print_message('create lambda function')
replaced_function_name = function_name.replace('_', '-')
role_arn = aws_cli.get_role_arn(f'lambda-{replaced_function_name}-role')
git_hash_johanna = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE).communicate()[0]
git_hash_template = subprocess.Popen(['git', 'rev-parse', 'HEAD'],
stdout=subprocess.PIPE,
cwd=f'template/{git_folder_name}').communicate()[0]
tags = list()
# noinspection PyUnresolvedReferences
tags.append(f"git_hash_johanna={git_hash_johanna.decode('utf-8').strip()}")
# noinspection PyUnresolvedReferences
tags.append(f"git_hash_{git_folder_name}={git_hash_template.decode('utf-8').strip()}")
################################################################################
print_message('check previous version')
need_update = False
cmd = ['lambda', 'list-functions']
result = aws_cli.run(cmd)
for ff in result['Functions']:
if function_name == ff['FunctionName']:
need_update = True
break
################################################################################
if need_update:
print_session(f'update lambda: {function_name}')
cmd = ['lambda', 'update-function-code',
'--function-name', function_name,
'--zip-file', 'fileb://deploy.zip']
result = aws_cli.run(cmd, cwd=deploy_folder)
print_message('wait few seconds until function is updated')
time.sleep(10)
function_arn = result['FunctionArn']
cmd = ['lambda', 'update-function-configuration',
'--function-name', function_name,
'--description', description,
'--role', role_arn,
'--handler', 'lambda.handler',
'--runtime', 'python3.12',
'--timeout', settings.get('TIMEOUT', '180')]
if settings.get('MEMORY_SIZE'):
cmd += ['--memory-size', settings['MEMORY_SIZE']]
aws_cli.run(cmd, cwd=deploy_folder)
print_message('update lambda tags')
cmd = ['lambda', 'tag-resource',
'--resource', function_arn,
'--tags', ','.join(tags)]
aws_cli.run(cmd, cwd=deploy_folder)
print_message(f'update sqs event source for {function_name}')
cmd = ['lambda', 'list-event-source-mappings',
'--function-name', function_name]
mappings = aws_cli.run(cmd)['EventSourceMappings']
for mapping in mappings:
cmd = ['lambda', 'delete-event-source-mapping',
'--uuid', mapping['UUID']]
aws_cli.run(cmd)
print_message('wait 120 seconds until deletion is complete')
time.sleep(120)
cmd = ['lambda', 'create-event-source-mapping',
'--event-source-arn', queue_arn,
'--function-name', function_name]
if settings.get('BATCH_SIZE'):
cmd += ['--batch-size', settings['BATCH_SIZE']]
aws_cli.run(cmd)
return
################################################################################
print_session(f'create lambda: {function_name}')
cmd = [
'lambda', 'create-function',
'--function-name', function_name,
'--description', description,
'--zip-file', 'fileb://deploy.zip',
'--role', role_arn,
'--handler', 'lambda.handler',
'--runtime', 'python3.12',
'--tags', ','.join(tags),
'--timeout', settings.get('TIMEOUT', '180'),
'--architectures', 'arm64',
]
if settings.get('MEMORY_SIZE'):
cmd += ['--memory-size', settings['MEMORY_SIZE']]
aws_cli.run(cmd, cwd=deploy_folder)
print_message('give event permission')
cmd = ['lambda', 'add-permission',
'--function-name', function_name,
'--statement-id', function_name + 'StatementId',
'--action', 'lambda:InvokeFunction',
'--principal', 'events.amazonaws.com',
'--source-arn', queue_arn]
aws_cli.run(cmd)
print_message(f'create sqs event source for {function_name}')
cmd = ['lambda', 'create-event-source-mapping',
'--event-source-arn', queue_arn,
'--function-name', function_name]
if settings.get('BATCH_SIZE'):
cmd += ['--batch-size', settings['BATCH_SIZE']]
aws_cli.run(cmd)