Background:
I have a Terraform configuration for allocating an AWS Lambda. I want it to automatically update the code when it detects a change. To do this, I'm using the source_code_hash property, as you can see below.
As part of my build process I zip all the source code and upload it to an S3 bucket.
I use the last modified time of the S3 object to trigger the build to redeploy changes.
Problem:
When I deploy the change, the source_code_hash
attribute is never updated. In the terraform plan it states that it will update the value to be b0IwKd/Fk38A+R20lGIWwCWP6p9UKmAmwns0it2J4qA=
, but it always gets set to b2+fXCsSQrxTJq5RonkDz8KhyOt8ICJYZGSsHkygrvY=
.
Similar questions:
- The following questions are similar to mine but they don't address my issue:
- [Terraform lambda source_code_hash update with same code](Terraform lambda source_code_hash update with same code)
- [Terraform lambda source_code_hash from S3 data doesn't stick in the state cache](Terraform lambda source_code_hash from S3 data doesn't stick in the state cache)
Terraform configuration:
data "aws_s3_object" "this" {
bucket = var.s3_bucket
key = var.s3_key
}
resource "aws_lambda_function" "this" {
s3_bucket = var.s3_bucket
s3_key = var.s3_key
source_code_hash = base64sha256(data.aws_s3_object.this.last_modified)
...
}
Terraform apply output first run:
# aws_lambda_function.this will be updated in-place
~ resource "aws_lambda_function" "this" {
~ source_code_hash = "b2+fXCsSQrxTJq5RonkDz8KhyOt8ICJYZGSsHkygrvY=" -> "b0IwKd/Fk38A+R20lGIWwCWP6p9UKmAmwns0it2J4qA="
...
}
Plan: 0 to add, 1 to change, 0 to destroy.
Terraform apply output second run:
# aws_lambda_function.this will be updated in-place
~ resource "aws_lambda_function" "this" {
~ source_code_hash = "b2+fXCsSQrxTJq5RonkDz8KhyOt8ICJYZGSsHkygrvY=" -> "b0IwKd/Fk38A+R20lGIWwCWP6p9UKmAmwns0it2J4qA="
...
}
Plan: 0 to add, 1 to change, 0 to destroy.
I tried to set source code hash to the following values:
source_code_hash = base64encode(sha256(data.aws_s3_object.this.last_modified))
source_code_hash = "${base64sha256(data.aws_s3_object.this.last_modified)}"
source_code_hash = base64sha256("${data.aws_s3_object.this.last_modified}")
source_code_hash = base64sha256("Wed, 15 Mar 2023 21:08:25 GMT")
I think the problem is how the source_code_hash
gets stored internally in the Terraform state.
I set base64sha256 to a default value and I'm experiencing the same issue.
Solution
I ended up uploading a sha256.txt file to the S3 bucket and used that instead.
I followed Naxest answer in Terraform lambda source_code_hash from S3 data doesn't stick in the state cache
Make sure you save your file with the .txt
extension or else data.aws_s3_object.this.body
will return null. See Note in https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/s3_object for more info on the body field.