Automating EC2 instance creation with Terraform

In this blog post, we will explore the popular Infrastructure as Code (IaC) tool, Terraform, and use it to provision and automate AWS infrastructure, specifically EC2 instances.

EC2 stands for Elastic Compute Cloud, which refers to a virtual computer or virtual server similar to a physical computer.

Prerequisites: Make sure you have AWS CLI, Terraform, and VS Code installed.

To install Terraform, you can follow the instructions provided here.

Step 1: Create an IAM user and download the credentials.

Step 2: Run the following command:

aws configure

This command will prompt you to enter your credentials. Once you enter the credentials, select your default region and output format.

Step 3: Open VS Code and create a new file named EC2.tf (you can choose a different name if you prefer). The ".tf" extension indicates that it is a Terraform file.

Step 4: Add the following script to the EC2.tf file and save it:

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

resource "aws_instance" "EC2_server" {
  ami               = "ami-06640050dc3f556bb"
  instance_type     = "t2.micro"
  availability_zone = "us-east-1a"

  tags = {
    Name = "EC2_server"
  }
}

Step 5: Open a new terminal in VS Code and run the following command:

terraform init

The first command to be executed is the initialization of the working directory, which includes the configuration files and installation of the required plugins for the providers, specifically the AWS.

Step 6: Now run the following command to review the execution plan of the infrastructure and verify if everything is correct:

terraform plan

This command will not create any infrastructure but will provide a preview of the changes.

Step 7: Run the command:

terraform apply

After executing the above command, it will prompt you to confirm by typing "yes," and then it will create the required infrastructure as defined in the EC2.tf file.

You can go to the AWS console to verify if the EC2 instance has been created.

Step 8: Final cleanup

Once you are finished, run the following command to delete/destroy all the infrastructure:

terraform destroy

It is always a good practice to clean up resources once you are done using them. This helps avoid unnecessary costs incurred by running services in the cloud when they are not needed.