Terraform - IAC

 


    HashiCorp Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.

How does Terraform work?

Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API.



HashiCorp and the Terraform community have already written thousands of providers to manage many different types of resources and services. You can find all publicly available providers on the Terraform Registry, including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more.

The core Terraform workflow consists of three stages:

  • Write: You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer.
  • Plan: Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration.
  • Apply: On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines.

Why Terraform?

Manage any infrastructure

Find providers for many of the platforms and services you already use in the Terraform Registry. You can also write your own. Terraform takes an immutable approach to infrastructure, reducing the complexity of upgrading or modifying your services and infrastructure.

Track your infrastructure

Terraform generates a plan and prompts you for your approval before modifying your infrastructure. It also keeps track of your real infrastructure in a state file, which acts as a source of truth for your environment. Terraform uses the state file to determine the changes to make to your infrastructure so that it will match your configuration.

automate changes 

Terraform configuration files are declarative, meaning that they describe the end state of your infrastructure. You do not need to write step-by-step instructions to create resources because Terraform handles the underlying logic. Terraform builds a resource graph to determine resource dependencies and creates or modifies non-dependent resources in parallel. This allows Terraform to provision resources efficiently.

standardize configurations 

Terraform supports reusable configuration components called modules that define configurable collections of infrastructure, saving time and encouraging best practices. You can use publicly available modules from the Terraform Registry, or write your own.

Collaborate 

Since your configuration is written in a file, you can commit it to a Version Control System (VCS) and use Terraform Cloud to efficiently manage Terraform workflows across teams. Terraform Cloud runs Terraform in a consistent, reliable environment and provides secure access to shared state and secret data, role-based access controls, a private registry for sharing both modules and providers, and more.

Terraform Core concepts

Below are the core concepts/terminologies used in Terraform:

  • Variables: Also used as input-variables, it is key-value pair used by Terraform modules to allow customization.
  • Provider: It is a plugin to interact with APIs of service and access its related resources.
  • Module: It is a folder with Terraform templates where all the configurations are defined
  • State: It consists of cached information about the infrastructure managed by Terraform and the related configurations.
  • Resources: It refers to a block of one or more infrastructure objects (compute instances, virtual networks, etc.), which are used in configuring and managing the infrastructure.
  • Data Source: It is implemented by providers to return information on external objects to terraform.
  • Output Values: These are return values of a terraform module that can be used by other configurations.
  • Plan: It is one of the stages where it determines what needs to be created, updated, or destroyed to move from real/current state of the infrastructure to the desired state.
  • Apply: It is one of the stages where it applies the changes real/current state of the infrastructure in order to move to the desired state.

erraform Lifecycle

Terraform lifecycle consists of – initplanapply, and destroy.



  • Terraform init initializes the working directory which consists of all the configuration files
  • Terraform plan is used to create an execution plan to reach a desired state of the infrastructure. Changes in the configuration files are done in order to achieve the desired state.
  • Terraform apply then makes the changes in the infrastructure as defined in the plan, and the infrastructure comes to the desired state.
  • Terraform destroy is used to delete all the old infrastructure resources, which are marked tainted after the apply phase.

How Terraform Works?

Terraform has two main components that make up its architecture:

  • Terraform Core
  • Providers

Terraform Core

Terraform core uses two input sources to do its job.

The first input source is a Terraform configuration that you, as a user, configure. Here, you define what needs to be created or provisioned. And the second input source is a state where terraform keeps the up-to-date state of how the current set up of the infrastructure looks like.

So, what terraform core does is it takes the input, and it figures out the plan of what needs to be done. It compares the state, what is the current state, and what is the configuration that you desire in the end result. It figures out what needs to be done to get to that desired state in the configuration file. It figures what needs to be created, what needs to be updated, what needs to be deleted to create and provision the infrastructure.

Providers

The second component of the architecture are providers for specific technologies. This could be cloud providers like AWS, Azure, GCP, or other infrastructure as a service platform. It is also a provider for more high-level components like Kubernetes or other platform-as-a-service tools, even some software as a self-service tool.

Install Terraform

Download the latest terraform package.

  • Refer to the official download page to get the latest version for the respective OS.
  • Configure AWS-CLI  as cloud provider and setup authentication using IAM credentials .

Provision AWS EC2 Instance Using Terraform

ec2.tf 

#Provider is nothing but cloud provider 
#https://registry.terraform.io/providers/hashicorp/aws/latest/docs
#fallow above link to get detail info about provider 
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }

  backend "s3" {
    bucket = "my-terrafrom-backend"
    #dynamodb_table = "value"
  }
}

provider "aws" {
  region = var.region
}

resource "aws_instance" "sample" {
  ami           = "ami-08c40ec9ead489470" #AMI ID
  instance_type = "t2.micro" #instance type
  tags = {
    "Name" = "sample-tf-ec2  "
    "Environment" = "test" }
}

output "public_ip" {
  value = aws_instance.sample.public_ip #printing public ip
 
}
output "public_dns" {
  value = aws_instance.sample.public_dns  #printing public dns
}

Provision AWS Instance creation advanced level 

  • Here Iam creating infrastructure from referencing peace's of code for ec2 creation
  • For that Iam declaring blocks separately ..
  • You can find same peace of below code in
  • https://github.com/GudditiNaganjaneyulu/Terraform.git
  • the below code creates 2 Security Groups On top of default VPC , 1 Webserver With apache2 website hosted through Userdata

provider.tf

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

  backend "s3" {
    bucket = "my-terrafrom-backend"
    #dynamodb_table = "value"
  }


}

provider "aws" {
  region = var.region

}


variable.tf



variable "instance_type" {
  description = "AWS Instance default type is "
  default = "t2.micro"
  type = string

}


variable "region" {
  description = "AWS Region"
  default = "us-east-1"
  type = string
 
}
variable "key" {
  description = "aws ec2 instace key pair to access"
  default = "Laptop"
  type = string
 
}

variable "vpc" {
  description = "vpc id"
  default = "default"
  type = string
 
}


amidata.tf
data "aws_ami" "ubuntu" {
  most_recent      = true
  owners           = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/*"]
  }

  filter {
    name   = "root-device-type"
    values = ["ebs"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
  filter {
    name = "architecture"
    values = [ "x86_64" ]
  }
}

sg.tf

resource "aws_security_group" "ssh" {
  name        = "ssh"
  description = "Allow ssh traffic"


  ingress {
    description      = "ssh"
    from_port        = 22
    to_port          = 22
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
   
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }

  tags = {
    Name = "ssh"
  }
}

resource "aws_security_group" "http" {
  name        = "http"
  description = "Allow http traffic"


  ingress {
    description      = "http"
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
   
  }
 
  ingress {
    description      = "https"
    from_port        = 443
    to_port          = 443
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
   
  }
 
  ingress {
    description      = "http"
    from_port        = 8080
    to_port          = 8080
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
   
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }

  tags = {
    Name = "http"
  }
}

userdata.sh

#!/bin/bash

apt update -y
apt install apache2 git  -y
cd /home/ubuntu/
git clone https://github.com/GudditiNaganjaneyulu/MyResume.git
mv MyResume/* /var/www/html/
service start apache2


ec2.tf

resource "aws_instance" "sample" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
  vpc_security_group_ids = [aws_security_group.ssh.id, aws_security_group.http.id]
  key_name = var.key
  tags = {
    "Name" = "sample-tf-ec2  "
    "Environment" = "test" }
  user_data = file("${path.module}/userdata.sh")


}

output "public_ip" {
  value = aws_instance.sample.public_ip
 
}
output "public_dns" {
  value = aws_instance.sample.public_dns  
}

check above peace of code using below commands 

  • terraform init       #initilize the TF backend based on code 
  • terraform validate      it will validate code snippets and show any errors 
  • terraform plan # give blue print of infrastructure to be created 
  • terraform apply -auto-approve  #it will create the infrastructure after using command
  • terraform destroy  -auto-approve  #it will delete infrastructure previously created 




Comments

Popular posts from this blog

Remote Friendly Companies

Docker Image Vulnerabilities and Scanner Guide: A Quick Overview

Introduction to Istio, Kiali, Jaeger, Grafana, and Prometheus