Deploying an AWS S3 Bucket with Terraform
Amazon S3 (Simple Storage Service) is a popular object storage service provided by Amazon Web Services (AWS) that allows you to store and retrieve data from the internet. In this article, we will explore how to deploy an S3 bucket in the AWS cloud using Terraform.
Prerequisites:
Before getting started, you will need the following:
An AWS account
Terraform installed on your local machine
AWS CLI (Command Line Interface) installed on your local machine
Setting up the Terraform Script
First, let's create a new directory for our Terraform project and create a new file named main.tf
. This file will contain our Terraform code to create the S3 bucket.
In the main.tf
file, we start by defining the provider block for AWS:
provider "aws" {
region = "us-west-2"
}
This block specifies the AWS region where we want to create the S3 bucket. In this example, we are using the us-west-2
region.
Next, we define the resource block for the S3 bucket:
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-teraf-test-bucket"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
This block creates an S3 bucket with the name my-teraf-test-bucket
. We also add some tags to the bucket to help with organization and management.
Next, we define a resource block to configure public access to the S3 bucket:
resource "aws_s3_bucket_public_access_block" "my_bucket_access_block" {
bucket = aws_s3_bucket.my_bucket.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
This block configures the S3 bucket to block public access to the bucket and its contents.
Next, we define a resource block to create a policy that allows a specific IAM user to access the S3 bucket:
resource "aws_s3_bucket_policy" "my_bucket_policy" {
bucket = aws_s3_bucket.my_bucket.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
AWS = "arn:aws:iam::131122418053:user/terra"
}
Action = "s3:GetObject"
Resource = "${aws_s3_bucket.my_bucket.arn}/*"
}
]
})
}
This block creates an S3 bucket policy that grants the IAM user with the ARN arn:aws:iam::131122418053:user/terra
permission to perform the s3:GetObject
action on objects within the S3 bucket.
Finally, we define a resource block to enable versioning for the S3 bucket:
resource "aws_s3_bucket_versioning" "my_bucket_versioning" {
bucket = aws_s3_bucket.my_bucket.id
versioning_configuration {
status = "Enabled"
}
}
This block enables versioning for the S3 bucket, which means that multiple versions of objects can be stored in the bucket.
Subscribe to my newsletter
Read articles from Sushrut Netkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by