Introduction To Terraform
Tags: terraform, devops, kubernetes, aws
Published: 2021-04-04 07:27:36

I recently came across Terraform and was amazed by all that it has to offer. This post is going to be about what Terraform does, why you might need it, and a quick demo where we use Terraform with AWS. So let's begin!

## What Is Terraform?

Terraform's [official website](https://www.terraform.io) says that 

> Terraform is an open-source infrastructure as code software tool that provides a consistent CLI workflow to manage hundreds of cloud services. 

The first question you might have is what exactly is infrastructure as code?

Well, whenever you use a cloud provider service to set up the infrastructure for your project, you typically create all the required resources using the web UI or the CLI for that particular service. Infrastructure as code is the process of defining all your infrastructure in a machine-readable format, that is, as code! 

Terraform is simply a tool that takes the infrastructure you have defined *as* code and brings it to life! 

To simplify it, let's say you want to create a S3 bucket in AWS. So you'll write this instruction as code (which I'll show you how later) and then Terraform will simply *execute* this code which means it will create that bucket for you.

Pretty cool right?

## Why Terraform?

So now you might wonder why you would want to use Terraform or this whole infrastructure as code approach over what you have been doing traditionally. Well, there are a couple of advantages:

### Bye Bye Errors! 

When creating your infrastructure manually there are a lot of screens and wizards you have to go through to configure it and so many settings you need to take care of. And when there is so much to configure it is quite easy to set something incorrectly by accident. With Terraform you'll be writing all this as code, which means it'll all be in one place for you to see and so the chances of you making a mistake while setting all this up would be lesser.

### Reproducibility

When doing things the traditional way it is quite difficult to create multiple identical environments. These environments could be completely similar or might have slight variations. Now if you're doing this the traditional way that means going through all those configuration screens again and remembering what slight changes you want to make.
 
But with Terraform it's as simple as `Ctrl + C`, `Ctrl + V` of your code (which defines your infrastructure). This also makes it easy to make all the slight changes you want in each environment easily! This way it is also more convenient to keep these environments identical to each other in the long run.

### See The Big Picture

When using Terraform you'll have your entire infrastructure written out in front of you as code. This makes it very easy to get an idea of what all components are present and make changes as you see fit.



These are some of the key reasons why you might want to use Terraform over the traditional method of creating infrastructure.

There are solutions like AWS CloudFormation available which also do the same for you. But still, I personally feel it is better to use Terraform instead of some cloud provider-specific solution. You might want to learn a tool that will come in handy regardless of the cloud provider you're working with, no?


## Getting our hands dirty!

Now that you have an idea of what Terraform does let us see it in action. I'm going to keep it very simple for this one and show you how to create a S3 bucket in AWS using Terraform. But remember you can create your entire infrastructure regardless of the cloud provider with Terraform. I will cover more complex use cases in further articles.

Sign in to AWS and [create a programmatic user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console) that Terraform can use to talk to AWS. Make sure to give this user enough access to create the S3 bucket. Once you finish creating this user make sure to take a note of the Access key ID and the Secret access key.


Once you're done with this go [install Terraform](https://www.terraform.io/downloads.html) for your OS. Run 
```
terraform -version
```
to make sure you've installed it correctly.


Now we need to set up the environment variables to give Terraform access to our AWS account. To do this simply run the following commands in your terminal:
```
export AWS_ACCESS_KEY_ID=YOURACTUALKEYID

export AWS_SECRET_ACCESS_KEY=YOURACTUALACCESSKEY
```


And that's it! Now terraform has access to talk to your AWS account. Do note that these two variables only exist for the lifetime of the current terminal window, that is, if you close the window you'll have to type the above commands again.


Now let's get to writing our infrastructure as code!
> If you're using VSCode you might wanna grab these extensions: [HashiCorp Terraform](https://marketplace.visualstudio.com/items?itemName=HashiCorp.terraform) and [Terraform Autocomplete](https://marketplace.visualstudio.com/items?itemName=erd0s.terraform-autocomplete).


Create a `main.tf` file and open it with your favorite code editor. Note that it is not necessary to call this file `main.tf` but it is considered a best practice. Copy the following contents in the file and I'll explain what we have done.

```
provider "aws" {
    region = "eu-west-1"
}

resource "aws_s3_bucket" "my_bucket" {
    bucket = "my-first-bucket" 
}
```

The first thing we did was specify our provider, which is AWS in our case. Terraform has a large number of [providers](https://registry.terraform.io/browse/providers) which give Terraform access to provider-specific resources. When we chose the provider we also specify the region we want to use for this project in AWS.

The next thing we did was set up our S3 bucket. For this, we defined a *resource*. 

A resource is simply something that maps to an item in the real world, that is, maps to something in our cloud provider in this case. 

In the first set of quotes, we specified which resource we want to use, an AWS S3 bucket. And in the second set of quotes, we gave this bucket an identifier. An identifier is only for use inside Terraform projects and has nothing to do with what will get created in AWS by Terraform. 

After this, we provided the configuration for this resource. Resources may have any number of parameters for you to configure. This configuration will be used to set the resource up just like you want in AWS. In this example, we just set the bucket name.


Now go back to your command line where you set up your AWS keys. You should see these keys when you run something like:

```
printenv | grep AWS
```

From this terminal navigate to the folder which has the `main.tf` file and run
 
```
terraform init
```

This will configure Terraform to run with your project and will initialize a state file (more on that in coming articles). Next run
 
```
terraform apply
```

This will take your `main.tf` file and *apply* that to AWS. When you run that command you will see a plan which Terraform creates first before actually making changes to AWS. 

This is so that you can see what all Terraform will be creating in your cloud provider. After showing you the plan Terraform will ask for your permission to apply the plan. Type `yes` to continue and you should see a success message. 


Now go to your Amazon S3 console and you'll see your bucket created by Terraform. Amazing right?!


You know what's even cooler?

Run `terraform apply` again and nothing will happen. This is because you asked Terraform to ensure that there is one particular S3 bucket and if that is already created it will do nothing. I had to mention this so that you don't think that running `terraform apply` again will create a new bucket.


Delete the bucket from the AWS console and then run `terraform apply` again and you'll see the plan screen again where Terraform is asking you to confirm the creation of the S3 bucket. Say `yes` and you'll see your bucket again in the AWS console. 


One final command I want to show you before ending this article. Run

```
terraform destroy
```

You will now see another plan which shows all the things Terraform will delete in order to destroy everything that was created by the `main.tf` file. Enter `yes` and go to your console and you should see the bucket gone!


And this was it, folks! I wanted to show you how cool and powerful Terraform is in this article and I'm sure by now you're somewhat impressed by Terraform. I will be writing more about Terraform in the following articles and going into depth about how Terraform is working behind the scenes and what all complicated things we can do with it. If that sounds interesting to you then make sure to keep an eye out for the coming articles :)

Thanks for reading! You can connect with me on [Twitter](https://twitter.com/RinkiyaKeDad) if you'd like to have a chat :D