Terraform - Create AWS S3 bucket
Learn how to create aws s3 bucket and set s3 lifecycle policy using terraform script with an example.

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"
}
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"
}
}
Note: I set ACL toprivate
so this bucket is not accessible from the internet. If you need your bucket to public accessible setacl = "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
}
}
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
}
}
}
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
