Day 64- 90DaysOfDevOps

Amit PawarAmit Pawar
2 min read

Hey Learners! Welcome back. We worked with Docker and provision resources locally with Terraform in some previous challenges. Moving forward, in this challenge we provision infrastructure using resources on AWS with Terraform. We can define declarative configuration files to provision our infrastructure on AWS. Let's start...

Prerequisite:-

AWS CLI:-

The AWS Command Line Interface (CLI) is a unified tool to manage your AWS services. To configure AWS CLI click here DAY42

I already configured AWS CLI on my running Instance.

Install Required Providers:-

We have to define Terraform Block to install required providers with specified versions.

Create a terraform.tf file (you can include the same code in main.tf as well)

terraform {
    required_providers {
        aws = {
            source = "hashicorp/aws"
            version = "5.19.0"
        }
    }
}

Define Provider Block. Create provider.tf as shown.

No need to specify Access and Secret Access Keys in the provider block (Not recommended) as we already configure AWS CLI (should be configured).

provider "aws" {
    region = "ap-south-1"
}

Task 1- Provision an EC2 instance

As we already created terraform and provider block we can create main.tf for defining AWS resources to provision EC2 instance.

resource "aws_instance" "Test_Instance" {
    ami = "ami-0287a05f0ef0e9d9a"
    instance_type = "t2.micro"
    tags = {
        Name = "TestEC2ByTerraform"
    }
}

OR

You can create only main.tf with all the blocks(terraform, provider, resource etc)

In main.tf file we define aws_instance resource and provide an ami ID for that. make sure the ami ID specified must be from the region specified.

Step 1- Initialize Terraform

We have to first initialize Terraform using terraform init command.

Step 2- Plan and Apply the configuration

Once you verify the plan given by the terraform plan command use terraform apply command and confirm by entering yes or you can use terraform apply -auto-approve to avoid entering yes every time.

Step 3- Verify Changes on the AWS Console

Go to the AWS console select EC2 service and verify that the new instance is created as per configuration. In our case Instance is named TestEC2ByTerraform.

Step 4- Destroy the changes

Destroy the created resources using the terraform destroy command.

6- Verify the changes on the AWS console.

Thank you so much for taking the time to read till the end! Hope you found this blog informative.

Feel free to explore more of my content, and don't hesitate to reach out if need any assistance from me or in case of you have any questions.

Find me on:- Hashnode LinkedIn Github

Happy Learning!

0
Subscribe to my newsletter

Read articles from Amit Pawar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amit Pawar
Amit Pawar