Create An AWS S3 Bucket With Terraform

In this AWS and Terraform blog post I will show you how to create an S3 bucket using Terraform. I will also name the bucket with today’s name using Terraform built-in functions.

In the previous articles, we learned how to create a credentials file and install AWS CLI tools. For Terraform to work with AWS, you will need both; however, running the aws configure command will be enough to get the authentication working to AWS.

Configuration

In the following configuration, I am using a few built-in Terraform function to create a variable with today’s date and name the bucket with it. If you don’t want the bucket name to be today’s date simply change the bucket name value (line 23).

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.47.0"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

locals {

 timest = timestamp()
 fulldate = formatdate( "DDMMMYYYYhhmmZZZ", local.timest )
 time = lower(local.fulldate)

}

resource "aws_s3_bucket" "b" {
  bucket = local.time
  acl    = "private"

}

To run the code and create the bucket run the following comamnds.

terraform init
terrafrom plan
terraform apply

To delete the bucket run the following command.

terraform destroy

Posted

in

,

by