Getting Started With Terraform on AWS In Right Way

Getting Started With Terraform on AWS In Right Way

Getting Started With Terraform on AWS In Right Way

Over the last few years, Cloud Computing has revolutionized the IT industry. On top of that Infrastructure as Code tools like CloudFormation, Ansible, Terraform etc. has helped to automate the infra to a great extent.

If you are in IT industry, I am sure you agree that terraform is the hot topic, when it comes to infrastructure automations now a days.

In this beginner friendly post, I will help you get started with terraform on AWS. We’ll go step by step and create a simple S3 bucket on AWS using Terraform.

Alright?

Okay, before starting with the actual steps, let’s get to know terraform a bit and why should you use it to deploy your infrastructure on AWS.

What is Terraform?

Terraform is an open source Infrastructure as Code(IaC) tool by HashiCorp. In another words If I say, terraform is a resource provisioning tool just like CloudFormation(AWS’s in house IaC tool).

You can declare all your resources in what is called as a configuration file. You’ll be using HashiCorp Configuration Language(HCL) or JSON while declaring your resources.

Here are set of 4 commands that you will use the most in your terraform journey. Don’t worry, we will get into details of each command.

$ terraform init
$ terraform plan
$ terraform apply
$ terraform destroy

Why Should You Use It?

  • Terraform can manage the entire lifecycle of your infrastructure using code
  • You can version control your configuration files using your favorite version control system like GitHub or CodeCommit.
  • It is cloud agnostic. That means, it enables multi cloud deployment by supporting wide range of providers.
  • Terraform is open source and is supported by a strong community of enthusiastic people.
  • Helps you reduce your time to market by providing error free reusable infrastructure in nick of time.

Prerequisites

To follow this tutorial you will need:

Steps to Getting Started With Terraform on AWS In Right Way

  1. Install Terraform On Your System
  2. Create an IAM User for Terraform
  3. Authenticate with AWS
    • Configure AWS CLI
  4. Download and Prepare VS Code IDE
  5. Create a New Project/Folder and Import Into VS Code
  6. Create a Simple Terraform Configuration File
  7. Terraform Init
  8. Terraform Plan
  9. Terraform Apply
  10. Terraform Destroy
  11. Updating the Created Resource

1. Install Terraform On Your System

Unlike CloudFormation, before you can use terraform to deploy a resource on AWS, you need to install it in your system.

Use official installation page to install it in your system. In case you are using windows system, I have a detailed tutorial prepared for you.

2. Create an IAM User for Terraform

Although, you can use your own credentials(AWS access keys/secret keys) to authenticate to AWS. I like to keep a separate user for terraform with just programming access.

PS: I like to name this user as terraform . However, you can choose anything you like.

Navigate to IAM service in AWS and click on Users -> Add users

Provide User name as terraform or anything you like.

terraform user initial

Click on Next: Permissions

Add Administrator policy or any other policy as per your need to your user and Click next.

Download the Access Key/Secret Key when you are prompted to do so. Keep it handy as we’ll need it in this tutorial.

In case, you need more help on creating a user, here is a detailed post : How to Create an IAM User on AWS Step by Step

3. Authenticate with AWS

We have installed terraform and also created an IAM user for terraform. That way, we have Access Key/Secret Key ready that we can use to authenticate to AWS.

You might ask- why is that needed?

Well, terraform needs to authenticate to AWS so that it can interact with AWS API’s to create resources in your behalf.

There are many ways to do it and you can read about them here.

However, simplest one seems to be using access and secret key in your template like this-

provider "aws" {
    access_key = "Your Access Key"
    secret_key = "Your Secret Key"
    region = "region"
}

No matter, how tempted you are to use this due to simplicity. But please don’t. This is not a secure way to authenticate. Imagine, you commit your configuration file into github repo with your credentials. It can wreck havoc in your account.

Hackers are constantly on lookout for exposed credential and they can cause damage into your account.

You might ask me, what do I do?

Well, here is a good way-

Configure AWS CLI in your system. And terraform will use that credential to authenticate to AWS. That way, you no longer store your credentials in your configuration files.

3.1 Configure AWS CLI

Use aws configure command to configure CLI in your local system.

aws configure

Once you hit enter, CLI will prompt you for below information one by one-

  • Access Key ID
  • Secret Access Key
  • Default region name
  • Default output format

Enter these information one by one and you are done. You can validate it by firing a simple aws command like aws s3 ls

aws s3 ls

In case you want to learnt it in details, here is a post : How to Install and Configure AWS CLI on Windows System

Once you have CLI configured, Ideally you are ready to create and deploy your first AWS resource. However, I will suggest you to download VS Code IDE and terraform extension on it. It will make you a lot more productive and will help you in your Terraform journey.

4. Download and Prepare VS Code IDE

Navigate to VS Code Official Page and click on your relevant download link to download it on your system.

Getting Started With Terraform on AWS 1

Once downloaded, install it in your system.

After the installation finishes, open VS Code, Click on Extensions icon. This how it looks like-

Search for HashiCorp Terraform and install the extension. In case you would like to validate, here is the link for the extension- https://marketplace.visualstudio.com/items?itemName=HashiCorp.terraform

5. Create a New Project/Folder and Import Into VS Code

Every Terraform configuration file needs to be in it’s own folder.

Create a folder in your system with name like- terraform-getting-started

Open VS Code. Click on File -> Open Folder

Select above created terraform-getting-started folder in your machine and open it in VS Code. Now we have the project in the VS Code and we are ready to use VS Code for our terraform project.

6. Create a Simple Terraform Configuration File

When using terraform, you can declare your infrastructure in the form of code which is in human readable format. It is written using HashiCorp Configuration Language(HCL) and is easy to understand.

Terraform files ends with .tf or they have .tf extensions. Let’s try to create a simple terraform file main.tf with one resource s3 bucket.

Please note that, most recent way to declare that we are using aws provider is like below-

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}
  • First we add the required_providers section and then configure that provider with region and profile details
  • Here the source section says that we are using aws provider
  • Also in the provider aws section as you can see I have given profile as default, you can used any named profile as well if you have one
  • In the region provide the region in which you would like terraform to create your resource

That was all about declaring aws provider. Let’s see how do we declare an aws resource

An AWS resource looks like below-

resource <resource type> <logical-name>{
  ...
  ...
     Resource configurations
  ...
  ...
}

Let’s try creating a simple s3 bucket with name: ck-demo-bucket and a tag as well. This is how the final configuration file looks like-

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

resource "aws_s3_bucket" "demo-bucket"{
  bucket = "ck-demo-bucket"

  tags = {
    Name = "S3Bucket"
  }
}

Important Note: HashiCorp keeps it’s documentation up to date. Do keep a reference of aws resources while working with terraform.

7. Terraform Init

We have the config file ready, however we can’t run them as yet. We need to initialize our working directory with AWS provider.

Back in the past, HashiCorp used to have provider code as well, as part of the terraform binary. However, that used to slow down the overall deployment process. Later, provider code was removed from binary and is available for download as a software package.

So, we need to initialize our working directory with the required cloud provider in our case it is aws. Initializing will download the code for aws provider by looking at the required provider section.

Let’s see how we can do it.

Once you have opened the folder into VS Code, navigate inside folder on terminal and fire terraform init command.

terraform init

Once you hit enter, terraform installs the aws plugin so that it can interact with AWS API to create resources on your behalf.

Getting Started With Terraform on AWS 2

After the initialization is success, you will see that a .terraform folder is created and it contains all the required things.

8. Terraform Plan

We have our working directory initialized. Let’s run terraform plan to see actually what’s getting created.

terraform plan
Getting Started With Terraform on AWS 3

Once you hit enter, plan command shows you detailed view on what’s actually getting created, modified or deleted. Resources will be created, modified or deleted is indicated with (+,- or ~ sign)

This is what these sign indicates-

  • + : Created
  • – : Deleted
  • ~: Modified

9. Terraform Apply

Once you see the output of plan command and you are sure of this is what you want to create, you are ready to actually create it.

In terraform you use command terraform apply to apply the planned changes.

terraform apply

Once you hit enter, apply command runs plan command once more and shows you what is being creatied, modified or deleted by (+, ~ and -) respectively.

Getting Started With Terraform on AWS 4

By the end of the section, you will see that terraform will ask you whether you want to perform these actions?

Enter yes as shown in below screenshot-

Getting Started With Terraform on AWS 5

once you type yes, and hit enter, terraform will start creating your resource.

In my case the bucket was already existing so it failed like below.

Let me try to update name of the bucket in my configuration file and I will run apply again.

I updated the configuration and changed the name from ck-demo-bucket to cloudkatha-terraform-demo-bucket.

resource "aws_s3_bucket" "demo-bucket"{
  bucket = "ck-demo-bucket"

  tags = {
    Name = "S3Bucket"
  }
}

After saving the configuration file, I ran terraform apply again. And as expected, this time my bucket was created successfully.

Getting Started With Terraform on AWS 7

10. Terraform Destroy

We have successfully created our s3 bucket resource. There are times when you are creating a resource for learning purpose, and don’t want to be billed.

Therefore, once you are done with your learning session, you can go ahead and delete the created resources.

terraform destroy
Getting Started With Terraform on AWS 8

Once you hit enter, it will again show you the resources that are gonna be destroyed.

If you scroll, by the end of section you will see , terraform asks you whether you really want to destroy all the resources.

Type yes as shown below and hit enter

Getting Started With Terraform on AWS 9

Once you hit enter, terraform starts destroying the resource. Once successful, you get the message as destroy complete as shown below.

Getting Started With Terraform on AWS 10

11. Updating the Created Resource

By now I guess you might have guessed it how you can update an existing resource.

And you are absolutely right.

All you need is to update your configuration file and run terraform apply

That’s it.

Conclusion

In this post on “Getting Started With Terraform on AWS In Right Way”, we discussed the lifecycle of a resource using Terraform. We learnt to install terraform and configure AWS CLI to allow terraform to talk to AWS API on our behalf to create a resource.

We also saw that the below 4 commands basically on center of resource deployment using terraform-

$ terraform init
$ terraform plan
$ terraform apply
$ terraform destroy

Apart from that, we also leant that althogh we can create a resource on AWS using terraform using any simple editor like Notepad. However it makes sense to use VS Code with terraform plugin for auto complete and better productivity. I am sure this tip is going to make your life a lot more easier as a terraform developer.

Do let me know in comment section in case you have any questions.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

Suggested Read:

One thought on “Getting Started With Terraform on AWS In Right Way

Leave a Reply

Your email address will not be published. Required fields are marked *