Use Terraform to create folder and subfolder in s3 bucket

Viewed 4311

How can I create folder and subfolder in S3 bucket using Terraform?

This is how my current code look like.

resource "aws_s3_bucket_object" "Fruits" {
  bucket = "${aws_s3_bucket.s3_bucket_name.id}"
  key    = "${var.folder_fruits}/"
  content_type = "application/x-directory"
}

variable "folder_fruits" {
  type = string
}

I would need a folder structure like fruits/apples

2 Answers

Folders in S3 are simply objects that end with a / character. You should be able to create the fruits/apples/ folder with the following Terraform code:

variable "folder_fruits" {
  type = string
}

resource "aws_s3_bucket_object" "fruits" {
  bucket       = "${aws_s3_bucket.s3_bucket_name.id}"
  key          = "${var.folder_fruits}/"
  content_type = "application/x-directory"
}

resource "aws_s3_bucket_object" "apples" {
  bucket       = "${aws_s3_bucket.s3_bucket_name.id}"
  key          = "${var.folder_fruits}/apples/"
  content_type = "application/x-directory"
}

It is likely that this would also work without the fruits folder.

For more information, see https://docs.aws.amazon.com/AmazonS3/latest/user-guide/using-folders.html

You can create a null object with a prefix that ends with '/'. All objects in a bucket are at the same hierarchy level but AWS displays it like folders using '/' as the separator.

    resource "aws_s3_bucket_object" "fruits" {
    bucket = "your-bucket"
    key    = "fruits/"
    source = "/dev/null"

    resource "aws_s3_bucket_object" "apples" {
    bucket = "your-bucket"
    key    = "fruits/apples/"
    source = "/dev/null"
}

It creates the following folder like structure:

s3://your-bucket/fruits/
s3://your-bucket/fruits/apples/
Related