A Guide to Terraform deployment with EC2 instances.

Joseph Peter
6 min readJan 2, 2023

--

Beginners intro into Terraform deployment of multiple AWS ec2 instances.

What is Terraform?

Terraform is a open source infrastructure as a code tool that lets you build, modify and version your code efficiently and effectively. Its similar to CloudFormation of AWS but terraform gives you access to most of the cloud platforms to create, update and maintain the infrastructure just using code. So terraform is platform independent. Also the code can be saved on any of remote repository like GitHub, GitLab etc. This gives you easy of access as well as versioning of your code.

How Terraform works?

Terraform uses HCL(Hashicorp Configuration Language) which is a declarative code language. Terraform uses hcl to describe the desired state of the infrastructure. This desired state is achieved by using API call to the respective cloud platform providers. After creation terraform maintains a terraform state file which contains the current state of the infrastructure. This state files helps terraform to track its change through out its life-cycle.

prerequisites:-

  1. On your local system, installed Terraform CLI. If not click here for AWS CLI and Terraform CLI.
  2. vscode or use cloud9 IDE.
  3. Install aws cli and do aws configure.
  4. Installed and configured GitHub.

Note: To get zero AWS billing, I will be using my own Ubuntu 22.04 with vscode and ACG AWS sandbox account to deploy aws ec2 instances and other systems. which means I will be building needed code and then push it to GitHub account. then repeat till its done. If you are using Cloud9 IDE or vscode, Git helper command helps you out with git repository setup.

Git helper command when token used for authentication.

Advantage of using a GitHub personal token over SSH is that, its very simple to use for the current session. if you prefer to use SSH for some reasons no worries, click here to see article about how to setup your SSH on your cloud server. Also git sometimes doesn’t let use this below feature. So it might be good to go with ssh. even if it takes some more time to setup.

git config --global credential.helper store
git push

if you follow git prompt after it through,now it will ask for git user name and for password, Go to GitHub and generate personal token(PAT) in GitHub developer sittings and paste the token as the password, it will be set for once for that current session, it will not ask for user login details again for pushing your code into GitHub repository.

Terraform File Structure

If you are doing it this first time, clone your repository.

  1. Create a folder before you start to do any terraform build up. This gives terraform a module. This folder becomes a root module.
  2. And on created folder, create a main.tf file, this is where you declare your resources and references other files. for more guidance click here.
  3. In the main.tf, we will be using AWS provider, to know more click here.
  4. The code we use here is hcl. I have declared terraform required provider as aws, configure aws in us-east-1 and given a ec2 instance to test out our setup.

Terraform commonly used commands:

terraform version — lets you know what version of terraform is installed.

terraform init — does all installation of terraform required files and initializes the project. This command is first performed whenever you create a module.

terraform fmt — does alignment of your code, fixes any misalignment.

terraform validate — validates the code for syntax and checks all the required references are provided.

terraform plan — gives you plan of action\execution that terraform going to do. this has an option to add -out to save the plan in file. so terraform can stick to the planned action.

terraform apply — to execute the plan, this applies all the action plan into creation of infrastructure. if used with terraform plan -out <your plane name>, then you have to use terraform apply <your same plane name here>.

terraform destroy — to delete all your created resources of the project.

In vscode, we have our code build as per our terraform documentation.

First code build out
terraform init

Once we run terraform init on the cli, terraform will create files and folders to facilitate building our infrastructure through code.

As you can read to see the files .terraform.lock.hcl

Now look at the file structure inside our project folder. If you have installed tree in your system, you see what are the files created by terraform init.

we can see all files and folder inside our project folder.

Don’t worry how it looks ,this is just to show you the terraform file structure. we not going deep here. it will need another article itself.

Task to be completed

Deploy 3 EC2 Instances in a single block of code.

Deploy 3 EC2 Instances.

Taking one task and split into smaller ones. First we are going to create 3 instances and then going to place each in different AZ’s of the same region. So on the existing code, under resources block. we are going to give a count of 3 ec2 instances and also changed instance type to t2.micro.

we can see the count of ec2 instances is 3 and also terraform commands
terraform plan
terraform plan is plan to add 3 instances

so up next, we go to apply our plan. lets find out whats next !

terraform apply

In automation, To avoid this we should not be using terraform plan without option -out to save the plan, as it waits for user confirmation. I will be using terraform plan -out “saved plan name”. This will make sure same action is performed, will retain the same version of the plan.

terraform plan -out <your plan name>
terraform apply <your plan name>
terraform plan -out save01
Now its ready to do terraform apply save01

An alternative solution, its to use -auto-approve but using this option means that some changes might happen to the plan.

terraform apply -auto-approve

Now we going to use terraform apply “save01” which is the saved plan name.

terraform apply save01
Looks like we got client.InternalError: Client error on launch

Problem faced :

Unable to create ec2 instance getting → Client error on launch.

Note: To resolve this issue, I researched a lot and didn’t find anything related to my issue which is not related to KMS encryption. Then I found out a easy way to resolve this client error on launch. If you get this error go to your AWS console → IAM → user → security credentials and then if you have more than one key generated for programmatic access. Delete the inactive keys and try to run the terraform command again and it should work.

It finally worked out.

Let me show the created ec2 instances.

Created ec2 instances from our terraform code
terraform state list
This list out the created resources.

here is the code from my GitHub repository. for your reference.

https://raw.githubusercontent.com/joey1089/Green_Terraform/main/sample_test-ec2/main.tf

Use terraform destroy to delete all ec2 instances.

terraform destroy
destroy command
3 instances are destroyed

you can also use terraform destroy -auto-approve to avoid user interaction. now we will verify, is our ec2 instances are terminated on AWS console.

Its all terminated, it works.

Summarize:-

What we learned here is how to use terraform to deploy three aws instances in the same block and destroy it after use. Main thing here is the troubleshooting of the client error on launch problem getting it resolved with a minor fix.

References:-

Terraform on AWS — https://registry.terraform.io/providers/hashicorp/aws/latest/docs

Terraform module — https://developer.hashicorp.com/terraform/language/modules/develop

--

--

Joseph Peter

AWS Community Builder and 2x AWS Certified, Terraform, Linux Certified and I want to implement cost effective solutions to the cloud.