0
0
TerraformHow-ToBeginner · 3 min read

How to Create an S3 Bucket with Terraform: Simple Guide

To create an S3 bucket with Terraform, define a resource block of type aws_s3_bucket with a unique bucket name. Then run terraform init, terraform plan, and terraform apply to deploy the bucket.
📐

Syntax

The basic syntax to create an S3 bucket in Terraform uses a resource block with the type aws_s3_bucket. You must provide a unique bucket name. Optionally, you can add settings like acl for access control.

  • resource: Declares a resource to create.
  • aws_s3_bucket: The resource type for S3 buckets.
  • bucket: The unique name of the bucket.
  • acl: Access control list, e.g., "private" or "public-read".
terraform
resource "aws_s3_bucket" "example" {
  bucket = "my-unique-bucket-name"
  acl    = "private"
}
💻

Example

This example creates a private S3 bucket named "my-unique-bucket-name". It shows the full Terraform configuration including the AWS provider setup.

terraform
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
  required_version = ">= 1.0"
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "example" {
  bucket = "my-unique-bucket-name"
  acl    = "private"
}
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs:
⚠️

Common Pitfalls

Common mistakes when creating S3 buckets with Terraform include:

  • Using a bucket name that is not globally unique, causing deployment errors.
  • Omitting the AWS provider configuration, so Terraform doesn't know which region to use.
  • Setting incorrect or missing permissions with acl, leading to access issues.
  • Not running terraform init before applying, which causes provider errors.
terraform
/* Wrong: bucket name not unique and missing provider */
resource "aws_s3_bucket" "bad_example" {
  bucket = "my-bucket"
}

/* Right: unique bucket name and provider configured */
provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "good_example" {
  bucket = "my-unique-bucket-name-12345"
  acl    = "private"
}
📊

Quick Reference

Remember these key points when creating an S3 bucket with Terraform:

  • Bucket names must be globally unique across AWS.
  • Always configure the AWS provider with a region.
  • Use acl to control access; default is private.
  • Run terraform init before terraform apply.

Key Takeaways

Define an aws_s3_bucket resource with a unique bucket name to create an S3 bucket.
Configure the AWS provider with the desired region before deploying.
Run terraform init to set up providers before applying changes.
Bucket names must be globally unique to avoid deployment errors.
Use acl to set bucket permissions, defaulting to private for safety.