DEV Community

Cover image for Create s3 Bucket with Terraform
Ashraf Minhaj
Ashraf Minhaj

Posted on

Create s3 Bucket with Terraform

Introduction

Welcome to the world of Infrastructure as Code. In this tutorial we will learn how to create an s3 bucket with terraform following just 3 Steps (2 actually)!

Step1: Setup AWS cli (ignore if already installed)

Whether it's your local machine or CI/CD platform, you will need to setup AWS-CLI there.

  1. Install - Assuming you have python installed you can just run this command on your terminal/cmd -
pip install awscli
Enter fullscreen mode Exit fullscreen mode

Or pip3 if you have multiple python version installed.

Else you can just follow official aws cli installation doc.

  1. Configure CLI Run this command on terminal -
aws configure
Enter fullscreen mode Exit fullscreen mode

And paste your access key, secrete access key and region and default output format as prompted -

AWS Access Key ID: MYACCESSKEY
AWS Secret Access Key: MYSECRETKEY
Default region name [us-west-2]: my-aws-region
Default output format [None]: json
Enter fullscreen mode Exit fullscreen mode

That's it. Now you can start running terraform code and start making magics.

Step2: Create s3 bucket

This is the simplest way to create an s3 bucket with terraform -

# declare cloud provider first
provider "aws" {
    region      = "your-aws-region"
}

# to interact with aws resources
terraform {
    required_providers {
      aws = {
        source  = "hashicorp/aws"
        version = "~> 4.30"
      }
    }
}

# create s3 bucket named my-lovely-bucket
resource "aws_s3_bucket" "demos3" {
    bucket = "my-lovely-bucket"   
}
Enter fullscreen mode Exit fullscreen mode

You can download the code from here.

Step3: Apply

That's it. Now go inside the terraform directory, start a terminal in that folder and run -

terraform init

It will download necessary things along with a '.tstate' file. After than you can just apply. But it's good practice to see the possible changes first using plan then apply. So, run -

terraform plan 
Enter fullscreen mode Exit fullscreen mode

It will output possible changes list, make sure you go through and if you are ok just run -

terraform apply
Enter fullscreen mode Exit fullscreen mode

That's it!! Your changes (creating a bucket) will be applied on aws! Go to aws console and check it for yourself.

Remember: While learning, to avoid unexpected bill please destroy resources after playing around.

To Destroy

terraform destroy

Conclusion

I hope you had fun. Best wishes for your cloudy journey ahead!

Top comments (0)