Create an AWS EC2 Linux Instance with Terraform

In this blog post, I will show you how to create an AWS EC2 instance using Terraform in a few simple steps.

The EC2 instance in this post will be a Linux CentOS VM.

Before You Start

Before you start, make sure you have the following:

Install Terraform on Windows 10 or Linux

Setup AWS CLI with AWS configure on the machine you are running the code.

Terraform will use the credentials of the AWS configure user.

Create Key Pair

You will need to create a key pair that will enable you to log in to the instance.

Without this step, you can’t log in to the VM.

Make sure you note down the name of the key you create, in my case the name is linuxec2

Terraform code

Below is the code you will need to deploy the VM.

Save the file in a folder and name it with .tf at the end.

# Provider configuration
provider "aws" {
region = "ap-southeast-2"
}
# Resource configuration
resource "aws_instance" "CentOSEC2" {
ami = "ami-000a59677875221a3"
instance_type = "t2.micro"
key_name = "linuxec2"
}

Run

To run the code, I will first urn the init command to get all Terraform to start.

terraform init

Next, I will run the plan command below, to check what will be created and if the code is OK.

terrafrom plan

Apply

To apply the code and deploy the VM, I will run the apply command below.

terraform apply

After running the command , I can check the results using the show command or from the portal.

terraform.exe show

Clean up

To clean up and delete the VM and all related resources run the following command

terraform destroy

Processing…
Success! You're on the list.

Posted

in

by