forked from terraform-aws-modules/terraform-aws-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.tf
458 lines (368 loc) · 18.5 KB
/
main.tf
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
data "aws_partition" "current" {}
data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
locals {
create = var.create && var.putin_khuylo
archive_filename = try(data.external.archive_prepare[0].result.filename, null)
archive_filename_string = local.archive_filename != null ? local.archive_filename : ""
archive_was_missing = try(data.external.archive_prepare[0].result.was_missing, false)
# Use a generated filename to determine when the source code has changed.
# filename - to get package from local
filename = var.local_existing_package != null ? var.local_existing_package : (var.store_on_s3 ? null : local.archive_filename)
was_missing = var.local_existing_package != null ? !fileexists(var.local_existing_package) : local.archive_was_missing
# s3_* - to get package from S3
s3_bucket = var.s3_existing_package != null ? try(var.s3_existing_package.bucket, null) : (var.store_on_s3 ? var.s3_bucket : null)
s3_key = var.s3_existing_package != null ? try(var.s3_existing_package.key, null) : (var.store_on_s3 ? var.s3_prefix != null ? format("%s%s", var.s3_prefix, replace(local.archive_filename_string, "/^.*//", "")) : replace(local.archive_filename_string, "/^\\.//", "") : null)
s3_object_version = var.s3_existing_package != null ? try(var.s3_existing_package.version_id, null) : (var.store_on_s3 ? try(aws_s3_object.lambda_package[0].version_id, null) : null)
}
resource "aws_lambda_function" "this" {
count = local.create && var.create_function && !var.create_layer ? 1 : 0
function_name = var.function_name
description = var.description
role = var.create_role ? aws_iam_role.lambda[0].arn : var.lambda_role
handler = var.package_type != "Zip" ? null : var.handler
memory_size = var.memory_size
reserved_concurrent_executions = var.reserved_concurrent_executions
runtime = var.package_type != "Zip" ? null : var.runtime
layers = var.layers
timeout = var.lambda_at_edge ? min(var.timeout, 30) : var.timeout
publish = (var.lambda_at_edge || var.snap_start) ? true : var.publish
kms_key_arn = var.kms_key_arn
image_uri = var.image_uri
package_type = var.package_type
architectures = var.architectures
code_signing_config_arn = var.code_signing_config_arn
replace_security_groups_on_destroy = var.replace_security_groups_on_destroy
replacement_security_group_ids = var.replacement_security_group_ids
/* ephemeral_storage is not supported in gov-cloud region, so it should be set to `null` */
dynamic "ephemeral_storage" {
for_each = var.ephemeral_storage_size == null ? [] : [true]
content {
size = var.ephemeral_storage_size
}
}
filename = local.filename
source_code_hash = var.ignore_source_code_hash ? null : (local.filename == null ? false : fileexists(local.filename)) && !local.was_missing ? filebase64sha256(local.filename) : null
s3_bucket = local.s3_bucket
s3_key = local.s3_key
s3_object_version = local.s3_object_version
dynamic "image_config" {
for_each = length(var.image_config_entry_point) > 0 || length(var.image_config_command) > 0 || var.image_config_working_directory != null ? [true] : []
content {
entry_point = var.image_config_entry_point
command = var.image_config_command
working_directory = var.image_config_working_directory
}
}
dynamic "environment" {
for_each = length(keys(var.environment_variables)) == 0 ? [] : [true]
content {
variables = var.environment_variables
}
}
dynamic "dead_letter_config" {
for_each = var.dead_letter_target_arn == null ? [] : [true]
content {
target_arn = var.dead_letter_target_arn
}
}
dynamic "tracing_config" {
for_each = var.tracing_mode == null ? [] : [true]
content {
mode = var.tracing_mode
}
}
dynamic "vpc_config" {
for_each = var.vpc_subnet_ids != null && var.vpc_security_group_ids != null ? [true] : []
content {
security_group_ids = var.vpc_security_group_ids
subnet_ids = var.vpc_subnet_ids
}
}
dynamic "file_system_config" {
for_each = var.file_system_arn != null && var.file_system_local_mount_path != null ? [true] : []
content {
local_mount_path = var.file_system_local_mount_path
arn = var.file_system_arn
}
}
dynamic "snap_start" {
for_each = var.snap_start ? [true] : []
content {
apply_on = "PublishedVersions"
}
}
dynamic "logging_config" {
# Dont create logging config on gov cloud as it is not avaible.
# See https://github.com/hashicorp/terraform-provider-aws/issues/34810
for_each = data.aws_partition.current.partition == "aws" ? [true] : []
content {
log_group = var.logging_log_group
log_format = var.logging_log_format
application_log_level = var.logging_application_log_level
system_log_level = var.logging_system_log_level
}
}
dynamic "timeouts" {
for_each = length(var.timeouts) > 0 ? [true] : []
content {
create = try(var.timeouts.create, null)
update = try(var.timeouts.update, null)
delete = try(var.timeouts.delete, null)
}
}
tags = merge(var.tags, var.function_tags)
depends_on = [
null_resource.archive,
aws_s3_object.lambda_package,
# Depending on the log group is necessary to allow Terraform to create the log group before AWS can.
# When a lambda function is invoked, AWS creates the log group automatically if it doesn't exist yet.
# Without the dependency, this can result in a race condition if the lambda function is invoked before
# Terraform can create the log group.
aws_cloudwatch_log_group.lambda,
# Before the lambda is created the execution role with all its policies should be ready
aws_iam_role_policy_attachment.additional_inline,
aws_iam_role_policy_attachment.additional_json,
aws_iam_role_policy_attachment.additional_jsons,
aws_iam_role_policy_attachment.additional_many,
aws_iam_role_policy_attachment.additional_one,
aws_iam_role_policy_attachment.async,
aws_iam_role_policy_attachment.logs,
aws_iam_role_policy_attachment.dead_letter,
aws_iam_role_policy_attachment.vpc,
aws_iam_role_policy_attachment.tracing,
]
}
resource "aws_lambda_layer_version" "this" {
count = local.create && var.create_layer ? 1 : 0
layer_name = var.layer_name
description = var.description
license_info = var.license_info
compatible_runtimes = length(var.compatible_runtimes) > 0 ? var.compatible_runtimes : (var.runtime == "" ? null : [var.runtime])
compatible_architectures = var.compatible_architectures
skip_destroy = var.layer_skip_destroy
filename = local.filename
source_code_hash = var.ignore_source_code_hash ? null : (local.filename == null ? false : fileexists(local.filename)) && !local.was_missing ? filebase64sha256(local.filename) : null
s3_bucket = local.s3_bucket
s3_key = local.s3_key
s3_object_version = local.s3_object_version
depends_on = [null_resource.archive, aws_s3_object.lambda_package]
}
resource "aws_s3_object" "lambda_package" {
count = local.create && var.store_on_s3 && var.create_package ? 1 : 0
bucket = var.s3_bucket
acl = var.s3_acl
key = local.s3_key
source = data.external.archive_prepare[0].result.filename
storage_class = var.s3_object_storage_class
server_side_encryption = var.s3_server_side_encryption
kms_key_id = var.s3_kms_key_id
tags = var.s3_object_tags_only ? var.s3_object_tags : merge(var.tags, var.s3_object_tags)
dynamic "override_provider" {
for_each = var.s3_object_override_default_tags ? [true] : []
content {
default_tags {
tags = {}
}
}
}
depends_on = [null_resource.archive]
}
data "aws_cloudwatch_log_group" "lambda" {
count = local.create && var.create_function && !var.create_layer && var.use_existing_cloudwatch_log_group ? 1 : 0
name = coalesce(var.logging_log_group, "/aws/lambda/${var.lambda_at_edge ? "us-east-1." : ""}${var.function_name}")
}
resource "aws_cloudwatch_log_group" "lambda" {
count = local.create && var.create_function && !var.create_layer && !var.use_existing_cloudwatch_log_group ? 1 : 0
name = coalesce(var.logging_log_group, "/aws/lambda/${var.lambda_at_edge ? "us-east-1." : ""}${var.function_name}")
retention_in_days = var.cloudwatch_logs_retention_in_days
kms_key_id = var.cloudwatch_logs_kms_key_id
tags = merge(var.tags, var.cloudwatch_logs_tags)
}
resource "aws_lambda_provisioned_concurrency_config" "current_version" {
count = local.create && var.create_function && !var.create_layer && var.provisioned_concurrent_executions > -1 ? 1 : 0
function_name = aws_lambda_function.this[0].function_name
qualifier = aws_lambda_function.this[0].version
provisioned_concurrent_executions = var.provisioned_concurrent_executions
}
locals {
qualifiers = zipmap(["current_version", "unqualified_alias"], [var.create_current_version_async_event_config ? true : null, var.create_unqualified_alias_async_event_config ? true : null])
}
resource "aws_lambda_function_event_invoke_config" "this" {
for_each = { for k, v in local.qualifiers : k => v if v != null && local.create && var.create_function && !var.create_layer && var.create_async_event_config }
function_name = aws_lambda_function.this[0].function_name
qualifier = each.key == "current_version" ? aws_lambda_function.this[0].version : null
maximum_event_age_in_seconds = var.maximum_event_age_in_seconds
maximum_retry_attempts = var.maximum_retry_attempts
dynamic "destination_config" {
for_each = var.destination_on_failure != null || var.destination_on_success != null ? [true] : []
content {
dynamic "on_failure" {
for_each = var.destination_on_failure != null ? [true] : []
content {
destination = var.destination_on_failure
}
}
dynamic "on_success" {
for_each = var.destination_on_success != null ? [true] : []
content {
destination = var.destination_on_success
}
}
}
}
}
resource "aws_lambda_permission" "current_version_triggers" {
for_each = { for k, v in var.allowed_triggers : k => v if local.create && var.create_function && !var.create_layer && var.create_current_version_allowed_triggers }
function_name = aws_lambda_function.this[0].function_name
qualifier = aws_lambda_function.this[0].version
statement_id = try(each.value.statement_id, each.key)
action = try(each.value.action, "lambda:InvokeFunction")
principal = try(each.value.principal, format("%s.amazonaws.com", try(each.value.service, "")))
principal_org_id = try(each.value.principal_org_id, null)
source_arn = try(each.value.source_arn, null)
source_account = try(each.value.source_account, null)
event_source_token = try(each.value.event_source_token, null)
}
# Error: Error adding new Lambda Permission for lambda: InvalidParameterValueException: We currently do not support adding policies for $LATEST.
resource "aws_lambda_permission" "unqualified_alias_triggers" {
for_each = { for k, v in var.allowed_triggers : k => v if local.create && var.create_function && !var.create_layer && var.create_unqualified_alias_allowed_triggers }
function_name = aws_lambda_function.this[0].function_name
statement_id = try(each.value.statement_id, each.key)
action = try(each.value.action, "lambda:InvokeFunction")
principal = try(each.value.principal, format("%s.amazonaws.com", try(each.value.service, "")))
principal_org_id = try(each.value.principal_org_id, null)
source_arn = try(each.value.source_arn, null)
source_account = try(each.value.source_account, null)
event_source_token = try(each.value.event_source_token, null)
}
resource "aws_lambda_event_source_mapping" "this" {
for_each = { for k, v in var.event_source_mapping : k => v if local.create && var.create_function && !var.create_layer && var.create_unqualified_alias_allowed_triggers }
function_name = aws_lambda_function.this[0].arn
event_source_arn = try(each.value.event_source_arn, null)
batch_size = try(each.value.batch_size, null)
maximum_batching_window_in_seconds = try(each.value.maximum_batching_window_in_seconds, null)
enabled = try(each.value.enabled, true)
starting_position = try(each.value.starting_position, null)
starting_position_timestamp = try(each.value.starting_position_timestamp, null)
parallelization_factor = try(each.value.parallelization_factor, null)
maximum_retry_attempts = try(each.value.maximum_retry_attempts, null)
maximum_record_age_in_seconds = try(each.value.maximum_record_age_in_seconds, null)
bisect_batch_on_function_error = try(each.value.bisect_batch_on_function_error, null)
topics = try(each.value.topics, null)
queues = try(each.value.queues, null)
function_response_types = try(each.value.function_response_types, null)
dynamic "destination_config" {
for_each = try(each.value.destination_arn_on_failure, null) != null ? [true] : []
content {
on_failure {
destination_arn = each.value["destination_arn_on_failure"]
}
}
}
dynamic "scaling_config" {
for_each = try([each.value.scaling_config], [])
content {
maximum_concurrency = try(scaling_config.value.maximum_concurrency, null)
}
}
dynamic "self_managed_event_source" {
for_each = try(each.value.self_managed_event_source, [])
content {
endpoints = self_managed_event_source.value.endpoints
}
}
dynamic "self_managed_kafka_event_source_config" {
for_each = try(each.value.self_managed_kafka_event_source_config, [])
content {
consumer_group_id = self_managed_kafka_event_source_config.value.consumer_group_id
}
}
dynamic "amazon_managed_kafka_event_source_config" {
for_each = try(each.value.amazon_managed_kafka_event_source_config, [])
content {
consumer_group_id = amazon_managed_kafka_event_source_config.value.consumer_group_id
}
}
dynamic "source_access_configuration" {
for_each = try(each.value.source_access_configuration, [])
content {
type = source_access_configuration.value["type"]
uri = source_access_configuration.value["uri"]
}
}
dynamic "filter_criteria" {
for_each = try(each.value.filter_criteria, null) != null ? [true] : []
content {
dynamic "filter" {
for_each = try(flatten([each.value.filter_criteria]), [])
content {
pattern = try(filter.value.pattern, null)
}
}
}
}
}
resource "aws_lambda_function_url" "this" {
count = local.create && var.create_function && !var.create_layer && var.create_lambda_function_url ? 1 : 0
function_name = aws_lambda_function.this[0].function_name
# Error: error creating Lambda Function URL: ValidationException
qualifier = var.create_unqualified_alias_lambda_function_url ? null : aws_lambda_function.this[0].version
authorization_type = var.authorization_type
invoke_mode = var.invoke_mode
dynamic "cors" {
for_each = length(keys(var.cors)) == 0 ? [] : [var.cors]
content {
allow_credentials = try(cors.value.allow_credentials, null)
allow_headers = try(cors.value.allow_headers, null)
allow_methods = try(cors.value.allow_methods, null)
allow_origins = try(cors.value.allow_origins, null)
expose_headers = try(cors.value.expose_headers, null)
max_age = try(cors.value.max_age, null)
}
}
}
# This resource contains the extra information required by SAM CLI to provide the testing capabilities
# to the TF application. The required data is where SAM CLI can find the Lambda function source code
# and what are the resources that contain the building logic.
resource "null_resource" "sam_metadata_aws_lambda_function" {
count = local.create && var.create_sam_metadata && var.create_package && var.create_function && !var.create_layer ? 1 : 0
triggers = {
# This is a way to let SAM CLI correlates between the Lambda function resource, and this metadata
# resource
resource_name = "aws_lambda_function.this[0]"
resource_type = "ZIP_LAMBDA_FUNCTION"
# The Lambda function source code.
original_source_code = jsonencode(var.source_path)
# a property to let SAM CLI knows where to find the Lambda function source code if the provided
# value for original_source_code attribute is map.
source_code_property = "path"
# A property to let SAM CLI knows where to find the Lambda function built output
built_output_path = data.external.archive_prepare[0].result.filename
}
# SAM CLI can run terraform apply -target metadata resource, and this will apply the building
# resources as well
depends_on = [data.external.archive_prepare, null_resource.archive]
}
# This resource contains the extra information required by SAM CLI to provide the testing capabilities
# to the TF application. The required data is where SAM CLI can find the Lambda layer source code
# and what are the resources that contain the building logic.
resource "null_resource" "sam_metadata_aws_lambda_layer_version" {
count = local.create && var.create_sam_metadata && var.create_package && var.create_layer ? 1 : 0
triggers = {
# This is a way to let SAM CLI correlates between the Lambda layer resource, and this metadata
# resource
resource_name = "aws_lambda_layer_version.this[0]"
resource_type = "LAMBDA_LAYER"
# The Lambda layer source code.
original_source_code = jsonencode(var.source_path)
# a property to let SAM CLI knows where to find the Lambda layer source code if the provided
# value for original_source_code attribute is map.
source_code_property = "path"
# A property to let SAM CLI knows where to find the Lambda layer built output
built_output_path = data.external.archive_prepare[0].result.filename
}
# SAM CLI can run terraform apply -target metadata resource, and this will apply the building
# resources as well
depends_on = [data.external.archive_prepare, null_resource.archive]
}