Day 1 - Introduction to Terraform and Terraform Basics

Day 1 - Introduction to Terraform and Terraform Basics

Day 1 of TerraWeek

Wouldn't it be exciting if you could automate the entire infrastructure by writing just one code? Well, the good news is that you can!

As the saying goes, "Necessity is the mother of invention." So, what's the necessity I'm referring to? Imagine you're working on a cloud computing platform like AWS, GCP, or Microsoft Azure, and you need to build an infrastructure. How much time would it take to create the entire plan? How long would it take to evolve the existing infrastructure? Is it possible to build the plan from scratch to a complete setup all at once? The answer is yes, thanks to Terraform combined with a cloud computing service (IaaS).

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

Terraform is the infrastructure as a code offering from HashiCorp. It is a tool for building, changing and managing infrastructure in a safe, repeatable way. Operators and Infrastructure teams can use Terraform to manage environments with a configuration language called the HashiCorp Configuration Language (HCL) for human-readable, automated deployments.

Terraform works with over 160 different providers for a broad set of common infrastructure. Provider SDK makes it simple to create new and custom providers. Providers leverage infrastructure-specific APIs to preserve unique capabilities for each provider.

Advantages of Terraform

  • Infrastructure as Code: Define and manage infrastructure using code.

  • Multi-Cloud and Hybrid Cloud Support: Works across various cloud providers.

  • Infrastructure Consistency and Standardization: Ensures consistent configurations across environments.

  • Automation and Efficiency: Automates infrastructure provisioning and management tasks.

  • Dependency Management and Resource Graph: Handles complex resource dependencies intelligently.

  • State Management: Tracks and manages infrastructure state for accurate updates.

  • Modularity and Reusability: Encourages code reuse through modular components.

  • Auditing and Compliance: Provides visibility and tracking of infrastructure changes.

Infrastructure as a Code

Infrastructure as code (IaC) tools allow you to manage infrastructure with configuration files rather than through a graphical user interface. IaC allows you to build, change, and manage your infrastructure in a safe, consistent, and repeatable way by defining resource configurations that you can version, reuse, and share.

Terraform is HashiCorp's infrastructure as a code tool. It lets you define resources and infrastructure in human-readable, declarative configuration files and manages your infrastructure's lifecycle.

Using Terraform has several advantages over manually managing your infrastructure:

  • Terraform can manage infrastructure on multiple cloud platforms.

  • The human-readable configuration language helps you write infrastructure code quickly.

  • Terraform's state allows you to track resource changes throughout your deployments.

  • You can commit your configurations to version control to safely collaborate on infrastructure.

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

Terraform simplifies infrastructure provisioning by automating tasks, leveraging code-based configurations, supporting multi-cloud environments, providing consistency, managing infrastructure state, handling dependencies, and offering preview capabilities for change validation.

Here are the reasons why we need Terraform and how it simplifies infrastructure provisioning:

  • Automation: Enables automated infrastructure provisioning, reducing manual effort.

  • Infrastructure as Code: Defines and manages infrastructure using code, facilitating versioning and collaboration.

  • Multi-Cloud Support: Works with various cloud providers, simplifying management in multi-cloud or hybrid cloud environments.

  • Consistent Workflow: Provides a consistent approach to provisioning infrastructure across different environments.

  • Infrastructure State Management: Keeps track of the infrastructure state, making it easier to update and modify resources.

  • Dependency Management: Automatically manages resource dependencies, ensuring the correct order of operations.

  • Plan and Preview: Generates execution plans for changes, allowing review before applying them.

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

To install Terraform and set up the environment for AWS, follow the below steps:

Install Terraform

  • Visit the official Terraform website

  • Run these commands to install Terraform on your local system. For Ubuntu, we can use these commands or if you are using any other OS then visit this link

       wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
       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
       sudo apt update && sudo apt install terraform
    
  • To verify the installation, run the following command in the terminal.

       terraform version
    

Set up AWS Credentials

  • Navigate to the IAM console, and click on "Users".

  • Click on the "Add user" button to create a new IAM user.

  • Enter name and click on next.

  • On the "Set permissions" page, we can assign policies to the user. Select the appropriate policies.

  • Review the user's configuration details. If everything looks correct, click on "Create user" to create the IAM user.

  • After the user is created click on the security credentials tab of the user.

  • Click on create an access key.

  • Select CLI and click on next.

  • Access keys and secrets are generated, copy from here and download as well.

Configure AWS Credentials for Terraform

  • Open a terminal or command prompt.

  • Run the following command to configure the AWS credentials.

      aws configure
    
  • Enter the access key and secret access key generated in the previous step.

  • Specify the default region (e.g., us-east-1)

Create a Terraform Configuration File

  • Create a new directory for your Terraform project.

  • Inside the project directory, create a file named main.tf (or any other name with a .tf extension).

  • In the main.tf file, write Terraform configurations.

Initialize and Apply Terraform Configuration

  • Open a terminal or command prompt in the project directory.

  • Run the following command to initialize Terraform and download the necessary provider plugins.

      terraform init
    

  • After initialization, run the following command to preview the changes Terraform will make to your infrastructure.

      terraform plan
    

  • If the plan looks good, apply the changes by running the following command.

      terraform apply
    
  • Confirm the changes by typing yes, when prompted.

  • Terraform will provision the specified AWS resources based on the configuration.

  • To destroy the structure use the below commands.

      terraform destroy
    

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

These crucial terminologies in Terraform provide the foundation for defining, provisioning, and managing infrastructure as code. Understanding these terms is essential for effectively using Terraform to automate and manage your infrastructure.

  1. Provider: A provider is responsible for managing and interacting with a specific infrastructure platform, such as AWS, Azure, or Google Cloud Platform. It allows Terraform to create, update, and delete resources within that platform.

     provider "aws" {
       region = "us-west-2"
     }
    
  2. Resource: A resource represents a single infrastructure object, such as a virtual machine, network, or database, that Terraform manages within a provider. Each resource has a specific type and configuration settings.

     resource "aws_instance" "example" {
       ami           = "ami-0c94855ba95c71c99"
       instance_type = "t2.micro"
     }
    
  3. Module: A module is a reusable set of Terraform configurations that encapsulates a specific piece of infrastructure. It allows you to abstract complex configurations into a single component that can be used across projects or shared with others.

     module "vpc" {
       source  = "terraform-aws-modules/vpc/aws"
       version = "3.0.0"
    
       name = "my-vpc"
       cidr = "10.0.0.0/16"
     }
    
  4. Variable: A variable allows you to parameterize your Terraform configurations, making them flexible and reusable. Variables can be assigned values from various sources and passed into modules or used within configurations.

     variable "instance_count" {
       type    = number
       default = 1
     }
    
     resource "aws_instance" "example" {
       count          = var.instance_count
       instance_type  = "t2.micro"
       ami            = "ami-0c94855ba95c71c99"
     }
    
  5. Output: An output allows you to expose information about your infrastructure after it has been provisioned. Outputs can be used to provide values like IP addresses, resource IDs, or any other information that you want to make accessible to other systems or users.

     output "instance_ip" {
       value = aws_instance.example.private_ip
     }
    

Thank you for reading!!
~Shreya Gupta

Great initiative by the #trainwithshubham community. Thank you Shubham Londhe

#devops #terraweek #terraform #terraformcommands #terraformbasics