Skip to main content

Command Palette

Search for a command to run...

How to create a EC2 instance via terraform

Published
5 min read
P

👋 Hello, and welcome to my DevOps journey! 🚀 I am Priyanka Varshney,🛠️ As an aspiring DevOps engineer, I'm all about bridging the gap between development and operations, making software delivery seamless and efficient. 💻🔧 On this Hashnode blog, I'll be sharing my learnings, experiences and adventures as I dive deep into the world of continuous integration, automation, and cloud technologies. ☁️⚙️ Let's connect, learn, and grow as a vibrant DevOps community. Follow my Hashnode blog, and let's embrace the DevOps adventure together! 🤝🔗

Create Amazon EC2 using Terraform – My Devops Journal

If you’re looking to set up an EC2 instance for local development using VS Code, this guide will walk you through the process step by step. We’ll cover how to install VS Code, set up Chocolatey (for Windows users), and install Terraform to manage infrastructure efficiently.

Step 1: Install VS Code

Before we begin, ensure you have VS Code installed on your system. You can download it based on your operating system from the official site:

https://code.visualstudio.com/download

Step 2: Install Chocolatey (Windows Users Only)

If you are using Windows, you’ll need Chocolatey, a package manager that simplifies software installation.

Installing Chocolatey

  1. Open PowerShell as an administrator.

  2. You can also enable the sudo option in laptop. Settings» system» developer» sudo enable

  3. Run the following command to install Chocolatey:

     Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
    
  4. After installation, restart PowerShell to apply changes.

Verifying Chocolatey Installation

To confirm that Chocolatey is installed, run the following command in PowerShell:

choco -v

If installed correctly, it will display the version number.

Step 3: Install Terraform

Terraform is a powerful tool used for infrastructure automation. Once Chocolatey is set up, you can install Terraform with:

choco install terraform --pre

After the installation is complete, verify that Terraform is installed by running:

terraform --version

This should return the installed Terraform version.

Step 4: Open VS Code and Set Up Terminal

Now that Terraform is installed, you can start using VS Code to manage your infrastructure.

How to Open the Integrated Terminal in VS Code

  1. Open VS Code

  2. Navigate to View → Terminal

  3. This will open the terminal at the bottom of your VS Code window

You’re now ready to create and manage your EC2 instance using Terraform and VS Code!

Understanding Terraform File Extensions & AWS Configuration

When working with Terraform, it's essential to understand the file extensions used for configuration.

Terraform File Types

  • .tf files – These define your infrastructure as code, specifying resources, providers, and configurations.

  • .tfvars files – These store variable values separately, making it easier to manage environment-specific configurations.

Setting Up Your Terraform Project

  1. Create a Folder
    Begin by creating a folder named Terraform where you will store your Terraform configuration files.

  2. Configure AWS CLI

First need to install AWS CLI :

C:\> msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
  1. To interact with AWS services, you need to configure the AWS CLI using:
aws configure

During this setup, you'll be prompted to enter your AWS Access Key ID and Secret Access Key.

Obtaining AWS Access Credentials

To generate the required Access Key ID and Secret Access Key, follow these steps:

  1. Log in to the AWS Management Console

  2. Navigate to the IAM (Identity and Access Management) service

  3. Create a new IAM user and assign necessary permissions

  4. Generate and save the Access Key ID and Secret Access Key

    1. Go to the IAM service and click on users from the Dashboard.

  1. Create a user named Terra-admin and give the permission AmazonS3FullAccess by clicking on attach policies directly.

    1. Click on next and then create user.

Now Terra-admin user is created successfully.

  1. To obtain the access key, navigate to the user profile, select "Security Credentials," create a security key, and then choose the "Command Line Interface (CLI)" option. After that, confirm your action and proceed by clicking "Next."

6. Now you will get two access key ID

  1. You can now enter the keys into VS Code by copying and pasting them

  1. You can now create a terraform.tf file to define the AWS provider

     terraform {
       required_providers {
         aws = {
           source = "hashicorp/aws"
           version = "5.92.0"
         }
       }
     }
    
  2. You can also create a provider.tf file to specify the AWS region.

     provider "aws" {
               region = "eu-west-1"
     }
    
  3. You will now need a public key for the EC2 instance and should assign a name to the key.

     ssh-keygen
    

    1. Next, create an ec2.tf file, where you'll define the key pair, VPC, and security group for your EC2 instance

      # key pair 
      resource "aws_key_pair" "my-key" {
        key_name   = "terra-key"
        public_key = file("terra-key.pub")
      }
      

      # VPC
      resource awc_default_vpc default {
      }
      

      ```plaintext

      Security group

      resource "aws_security_group" my_security{ name = "Automate" description = "This is for security group" vpc_id = "awc_default_vpc.default.id" #interpolation

      #inbound rules

      ingress { from_port = 22 to_port = 22 protocol = TCP cidr_blocks = ["0.0.0.0/0"] description = "SSH open" }

ingress { from_port = 80 to_port = 80 protocol = TCP cidr_blocks = ["0.0.0.0/0"] description = "http" }

ingress { from_port = 8000 to_port = 8000 protocol = TCP cidr_blocks = ["0.0.0.0/0"] description = "flask-app" }

#outbound rules

egress { from_port = 0 to_port = 0 protocol = -1 cidr_blocks = ["0.0.0.0/0"] description = "flask-app" } }


        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1743050008987/bfb71076-b6c7-4c95-9ce0-2d5e4f7e8d25.png align="center")

        10. ```plaintext
            resource "aws_instance" "my_insta" {

                key_name = aws_key_pair.my-key.key_name
                security_groups = [aws_security_group.my_security.name]
                instance_type = "t2.micro"
                ami = "ami-0df368112825f8d8f"  #ubuntu


                root_block_device {
                  volume_size = 15
                  volume_type = "gp3"
                }
                tags = {
                    Name: "Terraform-AWS-EC2-Automate"
                }
            }

Note: Ensure that a boundary is added to Administrator Access in the IAM service for the user.

Next, you can validate and plan your Terraform configuration using the following commands:

    terraform validate
    terraform plan

Now you are ready to apply the configuration using:

    terraform apply

Finally, you can see the instance in the AWS EC2

Summary

This guide walks you through setting up an EC2 instance using Terraform and VS Code:

1️⃣ Set Up – Configure AWS CLI, create an IAM user, and obtain access keys.
2️⃣ Define Terraform Files – Use terraform.tf for the AWS provider and ec2.tf for key pairs, VPC, and security groups.
3️⃣ Deploy – Validate, plan, and apply Terraform to launch the EC2 instance.
4️⃣ Verify – Check your instance in the AWS EC2 Dashboard.

With Terraform, EC2 deployment becomes automated and efficient!

Thank you for reading :-)