Home > Net >  Why do I get "contents of zip are not valid UTF-8;" when using filebase64sha256 in Terrafo
Why do I get "contents of zip are not valid UTF-8;" when using filebase64sha256 in Terrafo

Time:10-26

I am trying to create an AWS lambda function using Terraform, as specified here:

resource "aws_lambda_function" "dev" {
  role             = aws_iam_role.dev.arn
  handler          = var.handler
  runtime          = var.runtime
  filename         = "lambda.zip"
  function_name    = var.function_name
  source_code_hash = filebase64sha256(file("lambda.zip"))
}

But it throws an error:

Call to function "file" failed: contents of lambda.zip are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file
│ functions (e.g. filemd5, filesha256) to obtain file hashing results instead.

I've also tried "${base64sha256(file("lambda.zip"))}" but I still get the same error.

CodePudding user response:

All functions in Terraform starting with file take in the file path, not the contents.

There are 2 issues here:

  1. You're using file to read a binary file - it only accepts UTF-8 text

  2. You're using file when that is already handled by filebase64sha256 (the file prefix is the hint that this accepts a file path)

The documentation highlights both aspects:

This is similar to base64sha256(file(filename)), but because file accepts only UTF-8 text it cannot be used to create hashes for binary files.

Remove the call to file(...) and it should work:

resource "aws_lambda_function" "dev" {
  role             = aws_iam_role.dev.arn
  handler          = var.handler
  runtime          = var.runtime
  filename         = "lambda.zip"
  function_name    = var.function_name
  source_code_hash = filebase64sha256("lambda.zip")
}
  • Related