Skip to main content

Using Terraform to Create a RandomID and S3 Buckets

Hands-On Lab

 

Photo of Travis Thomsen

Travis Thomsen

Course Development Director in Content

Length

01:00:00

Difficulty

Intermediate

Our team is responsible for maintaining an application that is dependent on cloud storage. During a routine cleanup by one of the system administrators, the S3 Bucket for our development environment was destroyed. We have been tasked with going and setting up a new S3 Bucket. But rather than manually creating the bucket, we’ve decided to use Terraform. This way if the bucket gets destroyed again, we can quickly recreate it.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Terraform 0.11: RandomID and S3 Buckets

The Scenario

Our team is responsible for maintaining an application that is dependent on cloud storage. During a routine cleanup by one of the system administrators, the S3 Bucket for our development environment was destroyed. We have been tasked with going and setting up a new S3 Bucket. But rather than manually creating the bucket, we’ve decided to use Terraform. This way if the bucket gets destroyed again, we can quickly recreate it.

Logging In

Use the IP address and credentials provided on the hands-on lab overview page, and log in with SSH to the server.

There's a fair bit of creating and editing files in this lab. All of the examples here involve using Vim, but use whichever text editor is most comfortable.

Create the Terraform Files

Create main.tf:

vi main.tf

main.tf contents:

provider "aws" {
  region = "${var.aws_region}"
}

resource "random_id" "tf_bucket_id" {
  byte_length = 2
}

resource "aws_s3_bucket" "tf_code" {
    bucket        = "${var.project_name}-${random_id.tf_bucket_id.dec}"
    acl           = "private"

    force_destroy =  true

    tags {
      Name = "tf_bucket"
    }
}

Create variables.tf:

vi variables.tf

variables.tf contents:

variable "aws_region" {
  default = "us-east-1"
}

variable "project_name" {
  default = "la-terraform"
}

Create outputs.tf:

vi outputs.tf

outputs.tf contents:

output "bucketname" {
  value = "${aws_s3_bucket.tf_code.id}"
}

Deploy the S3 Bucket

Initialize Terraform:

terraform init

Validate the files:

terraform validate

Deploy the S3 bucket:

terraform apply -auto-approve

Conclusion

The last line of output from our approve command shows us a bucketname, which should match what we were trying to create: la-terraform-[RANDOM_NUMBER]. We can check by logging into our AWS Console, in the S3 section, and verifying that a bucket with the same name is sitting there. Congratulations!