Day 64 - Terraform with AWS   (Jan 29, 2024)

Day 64 - Terraform with AWS (Jan 29, 2024)

ยท

3 min read

๐Ÿ™ Introduction:

In this blog, we will learn how to integrate Terraform with AWS.

Provisioning on AWS is quite easy and straightforward with Terraform.

Prerequisites

AWS CLI installed

The AWS Command Line Interface (AWS CLI) is a unified tool to manage your AWS services. With just one tool to download and configure, you can control multiple AWS services from the command line and automate them through scripts.

  • Install AWS CLI on EC2 instance
sudo apt install awscli

  • Check the AWS CLI version
aws --version

AWS IAM user

IAM (Identity Access Management) AWS Identity and Access Management (IAM) is a web service that helps you securely control access to AWS resources. You use IAM to control who is authenticated (signed in) and authorized (has permissions) to use resources.

  • Create a IAM user

  • Create Access key for IAM user

  • In order to connect your AWS account and Terraform, you need the access keys and secret access keys exported to your machine.
export AWS_ACCESS_KEY_ID=<access key>
export AWS_SECRET_ACCESS_KEY=<secret access key>

Install required providers

terraform {
 required_providers {
        aws = {
        source  = "hashicorp/aws"
        version = "~> 4.16"
        }
    }
        required_version = ">= 1.2.0"
}
  • Terraform block defines the version of Terraform that is required to execute this configuration. In this case, it specifies that the Terraform version must be \>= 1.2.0.

  • required_providers block declares the AWS provider and its version that Terraform will use for the resources defined in this configuration. In this case, it declares the AWS provider with the source hashicorp/aws and specifies that the version of the provider should be ~> 4.16

  • Add the region where you want your instances to be

provider "aws" {
region = "us-west-2"
}

๐ŸŽฏTask: 1

  • Provision an AWS EC2 instance using Terraform

resource "aws_instance" "aws_ec2_test" {
        count = 2
        ami = "ami-008fe2fc65df48dac"
        instance_type = "t2.micro"
        tags = {
            Name = "TerraformTestServerInstance"
  }
}
  • The resource block has a resource type of aws_instance and a resource name of aws_ec2_test

  • count parameter is set to 2

  • ami parameter specifies the Amazon Machine Image (AMI) to use for the instances. In this case, the AMI ID is ami-008fe2fc65df48dac

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

  • tags parameter specifies metadata to attach to the instance, in this case, a tag named "Name" with the value "TerraformTestServerInstance".

terraform init

terraform plan

terraform apply

  • Check on EC2 console

ย