In this post, we will learn the basics of Terraform. We will launch an AWS EC2 instance using Terraform.
HashiCorp Terraform is an open source infrastructure as code (IaC) software tool that allows DevOps engineers to programmatically provision the physical resources an application requires to run.
Read more here: Terraform Introduction
Prerequisites
For this tutorial, you will need:
- AWS account
- Terraform installed
Let's Start
Log in to AWS and create an IAM role which we will use with Terraform. Get the access key and secret key required for authentication.
Create a new project directory. Inside the directory, create a file named ec2.tf and paste the following code:
provider "aws" {
region = "us-west-2"
access_key = "<YOUR_ACCESS_KEY>"
secret_key = "<YOUR_SECRET_KEY>"
}
resource "aws_instance" "myec2" {
ami = "ami-0ca285d4c2cda3300"
instance_type = "t2.micro"
tags = {
Name = "terraform"
}
}
Now let’s understand the code. We have two blocks here: the provider block and the resource block.
Provider
Providers are a logical abstraction of an upstream API. They are responsible for understanding API interactions and exposing resources.
Check the available providers from: Terraform Registry — Providers
Here in the code, we are using AWS as the provider. Terraform needs to authenticate with AWS in order to create the EC2 instance. For authentication, we are providing the AWS access key and secret key.
Resource
In short, resources are the services offered by the provider. For example, AWS provides resources such as aws_instance, aws_alb, etc.
You can see the list of resources for AWS from: Terraform Registry — AWS Provider
Since we want to deploy an EC2 instance, we are using the aws_instance resource.
Creating the Resource
Now let’s start creating an AWS EC2 instance.
Open the terminal, go to the project directory, and run the following command:
terraform init
This should successfully initialize Terraform.
Next, let’s see how Terraform will create the EC2 instance. Go ahead and run:
terraform plan
Terraform will print out the plan of how it is going to provision the resources.
Have a look at the plan and, if you are okay with it, let’s create the resource.
terraform apply
This should create the AWS EC2 instance. You can verify this by going to the AWS Console and opening the Instances page.
Destroying the Resource
Let’s destroy the AWS EC2 instance we created.
terraform destroy
This will destroy the resources created earlier.
Verify this by going to the AWS Console and opening the Instances page.
In the subsequent article, we will explore more of Terraform.
Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.
Happy Coding!!!