Search code examples
amazon-web-servicesterraformterraform-provider-awshcl

Use S3 Object tag from terraform


I have a split code deploy / infrastructure deploy that I'm working with. I currently have it working by uploading a separate file containing the codes' sha256 code_hash like so:

data "archive_file" "source" {
  type        = "zip"
  source_file = "../../code/lambda.py"
  output_path = "../../code/lambda.zip"
}

resource "local_file" "source_hash" {
  content  = data.archive_file.source.output_base64sha256
  filename = "../../code/source_code_hash"
}

resource "aws_s3_object" "file_upload" {
  bucket = "deployment_bucket"
  key    = "deployment_folder/lambda.zip"
  source = data.archive_file.source.output_path
  tags   = { sha256 = "${data.archive_file.source.output_base64sha256}" }
}

resource "aws_s3_object" "source_hash_upload" {
  bucket = "deployment_bucket"
  key    = "deployment_folder/source_code_hash"
  source = resource.local_file.source_hash.filename
}

This is fine but I feel like I can use the tag I've attached to the s3 bucket to skip the local file creation, uploading and later downloading.

I can't find anything about reading tags from s3 objects from terraform, is it possible to implement something like the following?

data "aws_s3_object" "source_code" {
  bucket = "deployment_bucket"
  key    = "deployment_folder/lambda.zip"
}

resource "aws_lambda_function" "relaysecret" {
  function_name = "lambda-function"

  s3_bucket        = "deployment_bucket"
  s3_key           = "deployment_folder/lambda.zip"
  source_code_hash = chomp(data.aws_s3_object.source_code.tag.sha256)
}

Solution

  • aws_s3_object has tags attribute (not tag as you have), so you can get the sha256 as follows:

    source_code_hash = chomp(data.aws_s3_object.source_code.tags["sha256"])