day-03-Terraform

Day-03

Terraform Settings, Providers & Resource Blocks

Step-01: Introduction

Step-02: In c1-versions.tf - Create Terraform Providers Block

Create an Directory with any name and place all the files in it. like, the first file will be c1-versions.tf

-> Understand about Terraform Settings Block and create it

# c1-versions.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "4.67.0"
    }
  }
}

Step-03: In c1-providers.tf - Create Terraform Providers Block

-> Understand about Terraform Providers
-> Configure AWS Credentials in the AWS CLI if not configured

# verify AWS credentials cat $HOME/.aws/credentials

-> Create AWS Providers Block

# Provider Block; c1-providers.tf

provider "aws" {
  region = "ap-northeast-1"
  profile = "default"
}

Step-04: In c2-ec2instance.tf - Create Resource Block

resource "aws_instance" "myec2vm" {
  ami = "ami-03dceaabddff8067e"
  instance_type = "t3.micro"
  user_data = file("${path.module}/script.sh")
  tags = {
    "name" = "ec2-demo"
 }
}
# give the below content into the "script.sh" file

#!/bin/bash
sudo yum update -y
sudo yum install nginx -y
sudo systemctl start nginx

Step-05: Execute the Terraform Commands

-> terraform init -> terraform validate -> terraform plan -> terraform apply (or) terraform apply --auto-approve

Step-06: Access Application

  • important Note: Verify if default VPC security group has a rule to allow port 80

http://<PUBLIC-IP>

successfully you will the nginx index page ...

Step-07: Clean-Up

terraform destroy # destroys the created server
rm -rf .terraform*
rm -rf terraform.tfstate*