Terraform

Infrastructure as a Code.

Its Cloud agnostic - Open Source provisioning tool

It's written in the Go language.

  • Speed and Simplicity

  • Team Collaboration

  • Error Reduction

  • Disaster Recovery

  • Enhanced Security

Install Terraform CLI

Please make sure AWS Profile is created.

Create Public and Private Keys

Linux / Mac Users

// create private/public key

ssh-keygen -b 2048 -t rsa -f ec2_tf_demo

Windows Users

Open PuttyGen and create a Key

Terraform

  • mkdir tf-aws-ec2-sample

  • cd tf-aws-ec2-sample

  • Create main.tf

  • Copy the contents of main.tf

// main.tf
#https://registry.terraform.io/providers/hashicorp/aws/latest

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

  required_version = ">= 1.2.0"
}

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

resource "aws_key_pair" "my_key_pair" {
  key_name   = "my_key_pair"
  public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDA8Ez4AejUjTLhurpwanyxUKdCsrQXshtve4nXLX9/My47TqZ5NQXI7R8o+vzXKejDOHdjD4vzGA9l8nk7blJBlE4nihzN2aDRbRMZV/ttkn3zDGusDH6obKoyGgH+deZvzB06Jp229I5w/U18vd0UdwAqrArzq/o3GLq7wjnTatOaJIS/Ex1KsZJa9wv1sGs6RPBWxW4LIl9Kbu6j8I9ZXg0608R7cEqu0gur2nyJNLRG5mcqvg21BQ1ia3vOg0BRxo25SyPhFKB4TXl51mQuFxJnVDEakPxmrJjnUaxeaenJ0E8nc21+mWe3h8KeKKVfeHeREvOS7JqGYolxgGc7 ganesh.chandra@FK33CY9K9H"
  #public_key = file("file.pub")
}

resource "aws_instance" "app_server" {
  ami           = "ami-00874d747dde814fa"
  instance_type = "t2.micro"
  key_name = aws_key_pair.my_key_pair.key_name

  tags = {
    Name = "GC Ubuntu Via TF"
  }
}

resource "aws_security_group" "gc_ec2_linux_sg" {
  name = "gc_ec2_linux_sg"

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

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

goto terminal

  • terraform init

  • terraform fmt

  • terraform validate

  • terraform apply

  • terraform show

Finally

  • terraform destroy

Last updated