Terraform - Create AWS S3 bucket

Learn how to create aws s3 bucket and set s3 lifecycle policy using terraform script with an example.

Terraform - Create AWS S3 bucket

AWS offers Simple Storage Service a.k.a s3, it is used to store large amount of data like static assets (images, videos, html, javascript, ets) in highly scalable and secure way.

What you will learn

  • Create s3 bucket using Terraform
  • Enable s3 versioning using terraform
  • Set s3 lifecycle policy using terraform
  • Destroy s3 using terraform

Create s3 bucket using Terraform

We need to define our terraform provider as AWS first to get started

provider "aws" {
	profile = "default"
	region = "ap-south-1"
}
Terraform - set provider as AWS

Let's define terraform resource to create s3 bucket

resource "aws_s3_bucket" "mobilelabs" {
	bucket = "mobilelabs-static"
    acl = "private"
    
    tags = {
    	Name = "mobilelabs static"
        Environment = "Development"
    }
}
Terraform - Define s3 bucket resource
Note: I set ACL to private so this bucket is not accessible from the internet. If you need your bucket to public accessible set acl = "public-read".

Enable s3 versioning using terraform

When we enable versioning in s3 bucket, when ever the file is updated it will have move the current version as the noncurrent version.

resource "aws_s3_bucket" "mobilelabs" {
	bucket = "mobilelabs-static"
    acl = "private"
    
    tags = {
    	Name = "mobilelabs static"
        Environment = "Development"
    }
    
    versioning {
    	enabled = true
  	}
}
Terraform - Enable s3 versioning

Set s3 lifecycle policy using terraform

When you have files which is not accessed after 15 days, it can be either moved to low cost storage or it can be removed from the storage. This can be done with the help of lifecycle policy.

Set s3 expiration to 15 days

resource "aws_s3_bucket" "mobilelabs" {
	bucket = "mobilelabs-static"
    acl = "private"
    
    tags = {
    	Name = "mobilelabs static"
        Environment = "Development"
    }

	lifecycle_rule {
    	id = "reports"
        prefix = "reports/"
        enabled = true
        noncurrent_version_expiration {
          days = 15
        }
    }
}
Terraform - Define s3 expiration lifecycle policy to 15 days
Note: To learn more about lifecycle configuration, visit terraform aws docs

This will remove all the non current files from the storage after 15 days from it's creation date.

Note: for complex rules you can visit AWS s3 docs

Destroy s3 using terraform

This will remove all the created resource

terraform destroy

Conclusion

We have learned how to setup s3 bucket with terraform and enabling versioning with lifecycle management.

Learn how to manage terraform state with s3

How to setup terraform with remote state s3
Terraform stores the state locally by default in the local project directory but we can also store this state remotely using the terraform backend.