Terraform S3 Having Problem with Leading Slash

Tags: May 28, 2020 12:32 PM
0 comments

Problem with S3 Leading Slash in Terraform

S3 accept leading slash "/" and automatically strip them off. When we use it in Terraform as a S3 key it may looks fine until we use it in another object. See example below.

# This bucket is used to store Lambda function and layer
resource "aws_s3_bucket" "deno" {
  bucket = var.default_bucket
  acl = "private"
  tags = var.default_tags
}

# Upload the layer to S3
resource "aws_s3_bucket_object" "deno_func" {
  bucket = aws_s3_bucket.deno.id
  tags = var.default_tags
  # / in front "deno-custom-runtime/function.zip" below creating problem
  key = "/deno-custom-runtime/function.zip"
  source = "${path.module}/../build/function.zip"
  etag = filemd5("${path.module}/../build/function.zip")
}

# Deno Layer
resource "aws_lambda_layer_version" "deno" {
  layer_name = "TeknocerdasDenoRuntime"
  s3_bucket = aws_s3_bucket.deno.id
  s3_key = aws_s3_bucket_object.deno_layer.key
  s3_object_version = aws_s3_bucket_object.deno_layer.version_id
  compatible_runtimes = ["provided"]
  description = "Custom Deno runtime by TeknoCerdas.com"
  source_code_hash = filebase64sha256("${path.module}/../build/layer.zip")
}
When applying the resources we should get error below.
Error: Error creating lambda layer: InvalidParameterValueException: Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist.
{
  RespMetadata: {
    StatusCode: 400,
    RequestID: "888bed7e-5345-4d5e-ab0e-0d8c683f49b2"
  },
  Message_: "Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist.",
  Type: "User"
}

Solution to S3 Leading Slash in Terraform

The solution is simply remove the leading slash from the key or filename. So instead of writing /deno-custom-runtime/function.zip use deno-custom-runtime/function.zip.

Problem solved. Simple and stupid.

References

Share on Facebook Twitter