⚙Day 1: Introduction to Terraform and Terraform Basics

⚙Day 1: Introduction to Terraform and Terraform Basics

🎇What is Terraform and how can it help you manage infrastructure as code?

-> Terraform is an open-source infrastructure as code (IaC) tool created by HashiCorp. It allows users to define and provision infrastructure resources using a declarative configuration language also know as Hashicorp Configuration Language(HCL).With Terraform, you can manage various cloud services, as well as on-premises infrastructure, in a consistent and reproducible manner.

Here's how Terraform helps manage infrastructure as code:

  1. Declarative Configuration: Terraform uses a declarative syntax to describe the desired state of your infrastructure. You define the resources, their configurations, and dependencies in a Terraform configuration file (usually with a .tf extension).

  2. Provisioning Infrastructure: Terraform supports multiple cloud providers (such as AWS, Azure, Google Cloud Platform), as well as other services like Kubernetes, Docker, and more. This allows you to manage heterogeneous environments using a single tool.

  3. Plan and Apply Workflow: Terraform follows a plan and apply workflow. When you make changes to your configuration, Terraform generates an execution plan showing what will be changed. You can review this plan before applying it to make sure it aligns with your expectations. Once confirmed, Terraform applies the changes to create, update, or delete resources as necessary.

  4. State Management: Terraform keeps track of the state of your infrastructure in a state file. This state file maps the resources defined in your configuration to the actual resources provisioned in your cloud provider. This enables Terraform to understand the current state of your infrastructure and make only the necessary changes when you update your configuration.

  5. Infrastructure as Code: With Terraform, your infrastructure is defined in code, which can be version-controlled, shared, and reused like any other codebase. This makes it easier to collaborate with team members, track changes, and apply software engineering best practices to infrastructure management.

🎇Why do we need Terraform and how does it simplify infrastructure provisioning?

-> We need Terraform for several reasons, and it simplifies infrastructure provisioning in various ways:

  1. Automation: Terraform automates the provisioning and management of infrastructure resources. Instead of manually setting up each resource, Terraform enables you to define your infrastructure in code and then automatically handles the provisioning process. This automation saves time and reduces the potential for human error.

  2. Consistency: Terraform ensures consistency in infrastructure deployments across different environments. By defining infrastructure as code, you establish a single source of truth for your infrastructure configuration. This helps to eliminate configuration drift and ensures that all environments (development, staging, production) are provisioned identically.

  3. Scalability: With Terraform, you can easily scale your infrastructure up or down to meet changing demands. Whether you need to provision additional resources to handle increased traffic or scale down during periods of low activity, Terraform allows you to modify your infrastructure configuration and apply the changes with minimal effort.

  4. Version Control: Infrastructure as code enables version control, allowing you to track changes to your infrastructure configuration over time. By storing your Terraform configuration files in a version control system (such as Git), you can review changes, revert to previous versions if necessary, and collaborate with team members more effectively.

  5. Modularity and Reusability: Terraform promotes modularity and reusability through the use of modules. Modules are self-contained units of configuration that encapsulate specific functionality or resources. By creating reusable modules, you can abstract away common infrastructure patterns, promote consistency, and simplify the management of complex deployments.

🎇Explain the important terminologies of Terraform with the example at least (5 crucial terminologies)

-> Here are five important terminologies in Terraform along with examples:

  1. Provider: Providers are plugins in Terraform that interface with different infrastructure platforms, such as cloud providers (AWS, Azure, GCP), on-premises systems, or SaaS services. Providers define the resources that Terraform can manage within that platform.

    Example:

     provider "aws"{
        region = "us-east-2"
     }
    

    In this example, the aws provider is specified, and the region is set to us-east-2. This configuration tells Terraform to interact with AWS resources in the specified region.

  2. Resource: They represent the various components of your infrastructure, such as virtual machines, databases, networks, etc. Resources are declared within Terraform configuration files using a specific syntax provided by each provider.

    Example:

     resource "aws_instance" "example"{
        ami    = "ami-0c55b159cbfafe1f0"
        instance_type = "t2.micro"
     }
    

    This example defines an AWS EC2 instance with the specified Amazon Machine Image (AMI) and instance type.

  3. Variable: Variables in Terraform allow you to parameterize your configurations and make them more flexible. Variables can be defined at various levels (e.g., global, module, resource) and can be passed values either through explicit assignment or through input variables files.

    Example:

     variable "instance_count"{
        description = "The number of instances to create"
        type = number
        default = 2
     }
    

    This example defines a variable named instance_count with a default value of This variable can be used to control the number of instances created in the Terraform configuration.

  4. Module: Modules in Terraform are self-contained packages of Terraform configurations that are managed as a group. Modules enable you to encapsulate and reuse pieces of infrastructure configuration, promoting modularity and reducing duplication.

     module "vpc" {
       source  = "terraform-aws-modules/vpc/aws"
       version = "2.0.0"
       # Specify input variables here
     }
    

    In this example, a module named vpc is used to provision a Virtual Private Cloud (VPC) in AWS. The source attribute specifies the location of the module, and versioning ensures consistency.

  5. Output: Outputs in Terraform allow you to extract and display information from your infrastructure after it has been provisioned. Outputs are useful for providing information such as IP addresses, DNS names, or any other relevant data that you may need to access or reference externally.

     output "public_ip" {
       value = aws_instance.example.public_ip
     }
    

    In this example, an output named public_ip is defined to display the public IP address of an AWS EC2 instance named example

🎇How can you install Terraform and set up the environment for AWS, Azure, or GCP?

-> To install Terraform we will go to the official document of terraform and perform the command which are under linux section Ubuntu/Debian

📍 Ensure that your system is up to date and you have installed the gnupg, software-properties-common, and curl packages installed. You will use these packages to verify HashiCorp's GPG signature and install HashiCorp's Debian package repository.

sudo apt-get update && sudo apt-get install -y gnupg software-properties-common

📍 Install the HashiCorp GPG key.

wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null

📍 Verify the key's fingerprint.

gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint

he gpg command will report the key fingerprint:

📍 Add the official HashiCorp repository to your system. The lsb_release -cs command finds the distribution release codename for your current system, such as buster, groovy, or sid.

echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list

📍 Download the package information from HashiCorp.

sudo apt update

📍 Install Terraform from the new repository.

sudo apt-get install terraform

We want to Create AWS EC2 instance infrastructure as a code.

💮Setup the Environment for AWS.

For connecting our AWS to our machine we will need AWS CLI V2 to be install then only we can able to communicate through CLI.

To install the AWS CLI, run the following commands.

$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

✔For giving access to the machine go to IAM Service and create a user.

✔ Select Attach Policies Directly and give Administrator Acess to the user and save.

✔Now, go to users select terra-server then security and create Access key

✔Configure AWS CLI with the IAM user credentials.

aws configure

Enter the Access Key ID, Secret Access Key, default region name, and default output format when prompted.

✔Create terraform file name asmain.tf

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

provider "aws" {
region = "us-east-2"        #Name of the region
}

resource "aws_instance" "launch-instance" {
        count = 1     #How much EC2 instance you want to create.
        ami = "ami-05fb0b8c1424f266b"    #AMI ID

        instance_type = "t2.micro"
        tags = {
     Name = "Terra-1"     #Name of the Instance
  }
}

This is terraform registry we get aws provider code and will use this in our file.

✔Initialize the Terraform configuration

terraform init

✔Creates an Execution plan

terraform plan

✔Apply the Terraform configuration

terraform apply

✔Check in the Region, the EC2 instances is running

Happy learning:)

Did you find this article valuable?

Support Vivek Ashok Moudekar by becoming a sponsor. Any amount is appreciated!