Thursday, December 1, 2022

How To Create An EC2 Instance With Terraform

In this document we are going to create an EC2 Instance using Terrform Scripting file.

Only below Resources Will covered:

  1. EC2 Instance (with Enable Termination Protection)
  2. EIP
  3. Security Groups
  4. Key File

Pre-requiestes:

  • Create IAM USER
  • And Get ACCESS_KEY & SECRET_KEY

Create main.tf file and Paste following code.

############################_AWS_Provider_###################################

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

provider "aws" {
  region     = "write-your-region-name"
  access_key = "paste-your-access-key"
  secret_key = "paste-your-secret-key"
}

############################_Creating Instance_###################################

resource "aws_instance" "Instance1" {
  ami           = "ami-074dc0a6f6c764218"
  instance_type = "t2.micro"
  disable_api_termination = "true"
  key_name = "Instance1-key" #Change the name as per your Instance
  security_groups = ["sg_for_terraform_instance"]

  tags = {
    Name = "Terraform-Instance"
  }
}

############################_Assigne_Pem_file_###################################



resource "aws_key_pair" "keyfile" {
  key_name   = "Instance1-key"
  public_key = file("~/.ssh/id_rsa.pub")
}

############################_Assigne_EIP_To_Instance__###################################

resource "aws_eip" "lb" {
  vpc      = true
}

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.Instance1.id
  allocation_id = aws_eip.lb.id
}


############################_Security_Group_For_Instance__###################################

resource "aws_security_group" "Instance_SG" {
  name = "sg_for_ierraform_instance"

  #Incoming traffic for HTTP
  ingress {
    from_port = 80
    to_port = 80
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"] #replace it with your ip address
  }

  #Incoming traffic for SSH
  ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["122.160.66.86/32"] #replace it with your ip address
  }

  #Outgoing traffic
  egress {
    from_port = 0
    protocol = "-1"
    to_port = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}
 

No comments:

Post a Comment

testing