3
votes

I have following AWS Terraform config:

# S3 bucket for Lambda code upload
resource "aws_s3_bucket" "ada-upload" {
    bucket = "ada-upload"
    acl    = "private"
}

# uploading zipped lambda code to S3
resource "aws_s3_bucket_object" "lambda_code_upload" {
  bucket = aws_s3_bucket.ada-upload.bucket
  key    = "dist.zip"
  source = "dist.zip" 
  etag = filemd5("dist.zip")
}

# creating lambda function
resource "aws_lambda_function" "ada-lambda-function" {
  function_name = "ada-lambda-function"
  s3_bucket   = aws_s3_bucket.ada-upload.bucket
  s3_key      = "dist.zip" 
  memory_size = 1024
  timeout     = 900
  runtime          = "provided"
  source_code_hash = base64sha256("dist.zip")
}

Basically it creates an S3 bucket, uploads code there and then creates a Lambda from that code. Code is self-contained .NET 3.1 app, it brings its own runtime, so the Zip is quite large, it takes some time to upload. Lambda will wait for S3 bucket creation, but will not wait for code to finish uploading. So when I run the script initially I will get S3 key "dist.zip" doesn't exist error. When I rerun the script - since the zip is already there - function created successfully.

Is there a way to ensure Lambda to start creating only when code finishes uploading?

1
Use s3_key = aws_s3_bucket_object.lambda_code_upload.keyydaetskcoR
@ydaetskcoR in the hindsight this should've been obvious, dammit! ;-) Thanks, could you please add this as the answer so I can accept it?Yuriy Galanter

1 Answers

0
votes

Disclaimer: @ydaetskcoR answer is correct and you should accept it. However, another approach would be to modify the lambda function as follows:

resource "aws_lambda_function" "ada-lambda-function" {
  function_name = "ada-lambda-function"
  s3_bucket   = aws_s3_bucket.ada-upload.bucket
  s3_key      = "dist.zip" 
  memory_size = 1024
  timeout     = 900
  runtime          = "provided"
  source_code_hash = base64sha256("dist.zip")

 depends_on = [
    aws_s3_bucket_object.lambda_code_upload,
  ]
}

This will force terraform to first wait for the object to be uploaded into the bucket before launching the lambda.