Home Creating a folder in S3 with Terraform
Post
Cancel

Creating a folder in S3 with Terraform

How to create an S3 folder with Terraform that is OS independent, and can be ran across Windows, or Unix based systems.

Recently I had the need to create an S3 folder using terraform and all I could find was the reference to passing /dev/null as a source for content, however I always strive to have my developments as OS agnostic as possible.

For instance, in my case I’m currently using Windows as my terraform host platform, so passing dev/null is definitely not an option.

So how may you create a folder in S3 with Terraform without using /dev/null as source?

Here is the code using Terraform’s s3_bucket_object resource:

1
2
3
4
5
6
7
8
9
resource "aws_s3_bucket_object" "s3_folder" {
    provider = aws
    bucket   = "${module.s3_bucket.bucket_id}"
    acl      = "private"
    key      =  "${var.folder_name}/"
    content_type = "application/x-directory"
    //  (Optional) Specifies the AWS KMS Key ARN to use for object encryption. This value is a fully qualified ARN of the KMS Key. 
    kms_key_id = "${var.kms_key_arn}"
}

As you may see the key part is both passing:

1
content_type = "application/x-directory"

And also not forgetting the trailing slash for the key value.

If your S3 bucket requires encryption, you also must pass the value for kms_key_id so it uses it for encrypting the value when making the request.

And that’s it.

This post is licensed under CC BY 4.0 by the author.