Skip to main content

Command Palette

Search for a command to run...

Day 48: Terraform with AWS

Updated
2 min read
Day 48: Terraform with AWS
P

Hi, I am an AWS-certified cloud engineer and I write about my progress and learnings of DevOps.

Hola!

In the last article, we have learned about variables in Terraform. Today we will deploy our first instance on AWS using Terraform. Let's get started!

Prerequisites

1) AWS CLI installed

In order to connect your AWS account to Terraform, you need to have AWS CLI installed on your workstation (either PC or server). From AWS CLI you will provide access keys that would establish a connection between AWS and Terraform. You can install CLI by going to the AWS website.

2) AWS IAM user

After installing CLI you need to provide AWS access keys from IAM user > create access key.

Run AWS configure in cmd and provide access keys that you have generated. It should show like that once configured.

Create a provider.tf file. Add the region where you want your instances to be

provider "aws" {
  region     = "us-east-1"
}

You can add more configurations according to requirements.

Task) Provision an AWS EC2 instance using Terraform

resource "aws_instance" "ec2-demo" {
  count = 2
  ami = "ami-03a6eaae9938c858c"
  instance_type = "t2.micro"
  tags = {
    Name= "terraform-test-instance"
  }
}

The resource block has a resource type of “aws_instance” and a resource name of “aws_ec2_demo”. The count parameter is set to 2, which means that two instances will be created.

The ami parameter specifies the Amazon Machine Image (AMI) to use for the instances. In this case, the AMI ID is “ami-0f8ca728008ff5af4”.

The instance_type parameter specifies the type of instance to create. In this case, the instance type is “t2.micro”.

The tags parameter specifies metadata to attach to the instance, in this case, a tag named “Name” with the value “TerraformTestInstance”

First, initialize the working directory with the necessary plugins and modules by executing terraform init

It will create an execution plan by analyzing the changes required to achieve the desired state of your infrastructure with terraform plan

Finally, it will apply the changes to create or update resources as needed with terraform apply

Let’s check in our AWS, whether these ec2 instances are created or not

Yay!! We have created 2 instances through Terraform!


Thanks for reading ;)