Day2:  Understand and Practice HCL syntax used in Terraform

Day2: Understand and Practice HCL syntax used in Terraform

Mastering HCL: The Key to Successful Terraform Infrastructure as Code

ยท

6 min read

๐Ÿ”ถ TerraWeek Day 2

HCL or HashiCorp Configuration Language, is a domain-specific language (DSL) developed by HashiCorp for writing configurations. It is designed to be human-readable and easy to understand, making it well-suited for defining infrastructure as code (IaC) in tools like Terraform.

๐Ÿ”ถ Task 1: Familiarize yourself with the HCL syntax used in Terraform

  • Learn about HCL blocks, parameters, and arguments.
    Blocks: Blocks are the top-level constructs in HCL. They define the main sections of a configuration. For example, in a Terraform configuration, you'll typically have blocks for resources, providers, and variables. Blocks are identified by their type, enclosed in curly braces {}. Example:

      resource "aws_instance" "example" {
        ami           = "ami-0c55b159cbfafe1f0"
        instance_type = "t2.micro"
      }
      #In this code, the resource block creates an AWS EC2 instance, and "aws_instance" is the block type.
    

    Parameters: Parameters are attributes that are defined within a block. They allow you to set specific configurations for that block type. Parameters are represented as key-value pairs within a block. In the example above, ami and instance_type are parameters of the aws_instance resource block.

    Arguments: Arguments are the values assigned to parameters within a block. They provide specific values or references to other resources or variables. In the previous example, "ami-0c55b159cbfafe1f0" and "t2.micro" are arguments assigned to the ami and instance_type parameters, respectively.

  • Explore the different types of resources and data sources available in Terraform.
    Terraform provides two key components for infrastructure management: Resources and Data Sources.

    Resources:

    • Resources are used to declare and manage infrastructure elements like virtual machines, databases, networks, and more.

    • Example:

        resource "aws_instance" "example" {
          ami           = "ami-0c55b159cbfafe1f0"
          instance_type = "t2.micro"
        }
      
    • Resources are specific to the infrastructure provider (e.g., AWS, Azure) and can be created, updated, or deleted.

  • Data Sources:

    • Data Sources are used to fetch information about existing infrastructure elements without modifying them.

    • Example:

        data "aws_vpc" "example" {
          default = true
        }
      
    • Data Sources provide read-only access to data that can be used elsewhere in the Terraform configuration.


๐Ÿ”ถ Task 2: Understand variables, data types, and expressions in HCL

  • Create a variable.tf file and define a variable.
    To define a variable in Terraform, you can create a variable.tf file in the Terraform project directory and declare the variable using the variable block.

    Here's an example of how to define a variable:

    1. Create a file named variable.tf in your Terraform project directory.

    2. Inside variable.tf, define a variable.
      For example, let's create a variable to specify the number of instances to launch:

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

      In the example above:

      • variable declares a new variable named instance_count.

      • description describes what the variable is used for.

      • type specifies the data type of the variable (in this case, number).

      • default sets a default value for the variable. If we don't provide a value when running Terraform, it will use this default value.

  • Use the variable in a main.tf file to create a "local_file" resource.
    Now, we can use this variable in your Terraform configuration files (e.g., main.tf) to parameterize your infrastructure.
    For example:

      resource "aws_instance" "example" {
        ami           = "ami-0c55b159cbfafe1f0"
        instance_type = "t2.micro"
        count         = var.instance_count  # Using the variable here
      }
    

๐Ÿ”ถ Task 3: Practice writing Terraform configurations using HCL syntax

Prequistis makes an EC2 instance and connects it.

#First of all update the system
sudo apt update -y
#Install docker 
sudo apt install docker.io -y
#check docker version
docker -v
#Docker version 24.0.5, build 24.0.5-0ubuntu1~22.04.1

To install Terraform, perform a Google search for 'Terraform install' and then select 'Linux -> Ubuntu' Use this link.

#step 1
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
#step 2
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
#step 3
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint
#step 4
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
#now update your system
sudo apt update
#Install terraform
sudo apt-get install terraform
#To check terraform version
terraform -v

  • Add required_providers to your configuration, such as Docker or AWS.

Make a main.tf file

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "3.0.2"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name = "nginx:latest"
}

resource "docker_container" "nginx_container" {
  name  = "nginx_container"
  image = docker_image.nginx.name

  ports {
    internal = 80
    external = 8080
  }
}

  • Test your configuration using the Terraform CLI and make any necessary adjustments.

Terraform init :
The command "terraform init" is used to initialize a Terraform configuration directory. When you run this command in a directory containing Terraform configuration files, it initializes the working directory and downloads any required provider plugins or modules specified in the configuration. This command is typically one of the first steps when working with Terraform to set up your infrastructure

terraform init

Terraform validate:
The command "terraform validate" is used to check the syntax and validity of your Terraform configuration files without actually creating any infrastructure. It scans your configuration files (typically with the extension .tf) and ensures that they are correctly formatted and that all references to resources and variables are valid. If there are any syntax errors or other issues in your configuration, this command will report them. It's a useful step to catch errors before attempting to apply your Terraform configuration to create or modify resources.

terraform validate

Terraform plan:
The "terraform plan" command is used to create an execution plan for your Terraform configuration. It examines the current state of your infrastructure, as recorded in your Terraform state file, and compares it to the desired state described in your configuration files.

terraform plan

Terraform apply:
terraform apply is the Terraform command used to execute the changes defined in your Terraform configuration and apply them to your infrastructure. It creates, modifies, or deletes resources according to your configuration. Use it carefully, especially in production environments, after reviewing the execution plan.

terraform apply

Add inbound rule 8080 in the security group.

Use your public IP to access the Nginx welcome page.

In conclusion, understanding and practicing HashiCorp Configuration Language (HCL) syntax in Terraform is essential for effectively defining and managing infrastructure as code. HCL provides a clear and concise way to express infrastructure configurations, making it easier to collaborate, version, and automate infrastructure provisioning. By mastering HCL, we can harness the full power of Terraform to efficiently create and manage your cloud resources, bringing scalability, repeatability, and consistency to your infrastructure operations.

#Terraweek Repo: https://github.com/Chandreshpatle28/TerraWeek.git


Happy Learning :)

Stay in the loop with my latest insights and articles on cloud โ˜๏ธ and DevOps โ™พ๏ธ by following me on Hashnode, LinkedIn (https://www.linkedin.com/in/chandreshpatle28/), and GitHub (https://github.com/Chandreshpatle28).

Thank you for reading! Your support means the world to me. Let's keep learning, growing, and making a positive impact in the tech world together.

#Git #Linux Devops #Devopscommunity #90daysofdevopschallenge #python #docker #Jenkins #Kubernetes #Terraform

Did you find this article valuable?

Support Chandresh Patle's Blog by becoming a sponsor. Any amount is appreciated!

ย