In my previous article, I did give an overview of Terraform. This article will help us to understand how to spin up instances in AWS using the Infrastructure as a Code tool Terraform. Although it's beyond the scope to discuss all the commands, I will try to cover the basic commands, and other resources can be researched and tried from the Terraform website against the provider of your choice.

Amazon Web Services (AWS) is a secure cloud services platform provided by Amazon. There are millions of customers who use AWS for their daily computing needs. AWS offers:

Compute capacity,

Storage,

DB,

And much more.

Big organizations who use AWS or any other cloud service provider do need to use some IaaC tool to spin up EC2 instances for their applications. It would be tedious to spin up EC2 instances manually.

Terraform's purpose is to deploy the server itself, CHEF would configure items in your server once you have the infrastructure. Let's learn in brief how to manage infrastructure as code using Terraform.

You have to download Terraform or use Brew command to install Terraform if using MAC. Also, you need to have an AWS account and need to add the AWS credentials (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) as environment variables to start using the TF with AWS.

Terraform State

Terraform supports many cloud providers and has resources for each cloud provider:

terraform destroy
aws_instance.example: Refreshing state... (ID: i-07fcaa5435207dac7)
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
- aws_instance.example
Plan: 0 to add, 0 to change, 1 to destroy.

The State of Terraform

You must be wondering, how does TF know what needs to be changed or destroyed when we issue the plan/apply command? Usually, Terraform records the state of everything it has done, so it stores the state locally as .tfstate files.

Use count.index to modify each iteration. The above code creates three EC2 instances, each with a different name. Using count is like using for loop in other languages.

Layout of Files

We use three main files while using TF:

main.tf -> This is used to declare resources needed for your configuration.

vars.tf -> This will hold variables to be used in main.tf.

outputs.tf -> This file will hold any output variables.

Best Practices

It's good to use GitHub when working as a team with TF. Use pull requests, merge the code, and deploy.

Use the DEV environment and test your TF configuration code before moving to production. Always run a plan and be extremely careful with deletes. There is no rollback once the configuration is applied.

Manage your secrets as environment variables and deploy to your shared environments from one master branch.

If you plan to use Terraform for setting up your infrastructure, this article will surely serve as a starting point.