Fail safe reading s3_bucket_object with terraform when object doesn't exist

Viewed 747

I would like to safely load data from an s3_bucket_object. Meaning if s3 object doesn't exist provide a default value instead. Is there a way to do that ?

If I specify the non existing key, I get a failure

data "aws_s3_bucket_object" "deployed_builds_s3" {
  bucket = my_bucket_name
  key    = "path/to/file.txt"
}

error:

Error: Failed getting S3 object: NotFound: Not Found

I know it's possible to do with local files like this for example:

locals {
  file_content = fileexists("file.txt") ? file("file.txt") : ""
}

Is there something similar with s3 objects ?

1 Answers

Yes, you can do this with the help of aws_s3_bucket_objects. Specifically, first you will call it with the object key of interest:

data "aws_s3_bucket_objects" "my_object" {
  bucket = my_bucket_name
  prefix = "path/to/file.txt"
}

If the object exists, they keys attribute will have 1 element. Subsequently, you can conditionally execute aws_s3_bucket_object as follows:

data "aws_s3_bucket_object" "deployed_builds_s3" {

  count  = length(data.aws_s3_bucket_objects.my_object.keys)

  bucket = data.aws_s3_bucket_objects.my_object.keys[0]
  key    = data.aws_s3_bucket_objects.my_object.bucket
}

The about will execute if the number of keys found is greater than 0. This is enabled through count meta-argument.

Related