DEV Community

Udoh Deborah
Udoh Deborah

Posted on

Day 64 - Terraform with AWS

Step-by-step guide to provision an AWS EC2 instance using Terraform:

Step 1: Install AWS CLI

  • Download and install AWS CLI from here.
  • Configure your AWS profile:
  aws configure
Enter fullscreen mode Exit fullscreen mode
  • Enter your AWS Access Key ID, Secret Access Key, default region, and output format when prompted.

Step 2: Export AWS Credentials

  • If you prefer to set environment variables manually, run:
  export AWS_ACCESS_KEY_ID=<your_access_key>
  export AWS_SECRET_ACCESS_KEY=<your_secret_key>
Enter fullscreen mode Exit fullscreen mode
  • Replace <your_access_key> and <your_secret_key> with your actual AWS credentials.

Step 3: Install Terraform

  • Download Terraform from here and install it according to your OS instructions.
  • Verify installation:
  terraform -version
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Terraform Configuration File

  • Open your favorite text editor and create a new file named main.tf.
  • Copy and paste the following code into main.tf:
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }
  required_version = ">= 1.2.0"
}

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

resource "aws_instance" "aws_ec2_test" {
  count          = 4
  ami            = "ami-08c40ec9ead489470"
  instance_type  = "t2.micro"
  tags = {
    Name = "TerraformTestServerInstance"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Initialize Terraform

  • Open your terminal, navigate to the directory containing main.tf, and run:
  terraform init
Enter fullscreen mode Exit fullscreen mode
  • This installs necessary provider plugins.

Step 6: Review the Terraform Plan

  • To see what Terraform will do before actually creating resources, run:
  terraform plan
Enter fullscreen mode Exit fullscreen mode

Step 7: Apply the Configuration

  • To create the EC2 instances, run:
  terraform apply
Enter fullscreen mode Exit fullscreen mode
  • You will see a plan; confirm by typing yes.

Step 8: Wait for Resources to be Created

  • Terraform will now create 4 EC2 instances based on your configuration.

Step 9: Managing and Destroying Resources

  • To delete the created resources later, run:
  terraform destroy
Enter fullscreen mode Exit fullscreen mode
  • Confirm with yes

Top comments (0)