TerraWeek day 2:

TerraWeek day 2:

·

7 min read

Task 1: Familiarize yourself with the HCL syntax used in Terraform

Learn about HCL blocks, parameters, and arguments

  • HCL (HashiCorp Configuration Language) is a domain-specific language used for defining infrastructure as code (IaC) in various HashiCorp tools such as Terraform, Packer, and Consul.

    It lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share.

    In HCL, you work with blocks, parameters, and arguments to define and configure resources and their properties.

    • Blocks:

      • Blocks are fundamental structures in HCL and are used to define resources, data sources, providers, and modules. Each block has a specific type associated with it, which determines its purpose and how it's used.

      • Blocks are enclosed within curly braces {} and consist of a block type, an optional label, and a set of parameters and their corresponding values.

      • Example of a block:

          resource "aws_instance" "example" {
            ami           = "ami-0c55b159cbfafe1f0"
            instance_type = "t2.micro"
          }
        
      • In this example, resource is the block type, "aws_instance" is the label (resource type), example is the name of the resource, and the block contains two parameters (ami and instance_type) with their respective values.

    • Parameters:

      • Parameters are key-value pairs used to configure the behavior and characteristics of a resource or other HCL constructs. They define how a resource should be created and what properties it should have.

      • Parameters are specified within blocks and are set with an equal sign = between the parameter name and its value.

      • Different resource types have specific parameters associated with them, which can vary widely depending on the type and purpose of the resource.

      • Example of parameters within a block:

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

        In this example, ami and instance_type are parameters for the AWS EC2 instance resource.

    • Arguments:

      • Arguments are specific values provided to parameters within a block. They are used to specify the actual data or values associated with the parameters.

      • Arguments can be literals (like strings or numbers), references to other resources or data sources, or complex expressions.

      • In the previous example, "ami-0c55b159cbfafe1f0" and "t2.micro" are arguments provided for the ami and instance_type parameters, respectively.

Explore the different types of resources and data sources available in Terraform

Resources are the most important element in the Terraform language. Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records.

Each resource is associated with a single resource type, which determines the kind of infrastructure object it manages and what arguments and other attributes the resource supports.

Each resource type is implemented by a provider, which is a plugin for Terraform that offers a collection of resource types. A provider usually provides resources to manage a single cloud or on-premises infrastructure platform. Providers are distributed separately from Terraform itself, but Terraform can automatically install most providers when initializing a working directory.

Below are some common types of resources in Terraform:

  • Compute Resources:

    • aws_instance: Represents an EC2 instance in AWS.

    • google_compute_instance: Represents a Google Cloud Compute Engine instance.

    • azurerm_virtual_machine: Represents an Azure Virtual Machine.

  • Networking Resources:

    • aws_vpc: Defines a Virtual Private Cloud (VPC) in AWS.

    • google_compute_network: Defines a network in Google Cloud.

    • azurerm_virtual_network: Defines a virtual network in Azure.

  • Database Resources:

    • aws_db_instance: Represents a database instance in AWS RDS.

    • google_sql_database_instance: Represents a Google Cloud SQL database instance.

    • azurerm_sql_server: Represents an Azure SQL Database server.

  • Storage Resources:

    • aws_s3_bucket: Defines an S3 bucket in AWS.

    • google_storage_bucket: Defines a Google Cloud Storage bucket.

    • azurerm_storage_container: Defines a storage container in Azure.

  • Load Balancer Resources:

    • aws_lb: Represents a load balancer in AWS.

    • google_compute_http_health_check: Defines an HTTP health check in Google Cloud.

    • azurerm_lb: Represents a load balancer in Azure.

  • Security Resources:

    • aws_security_group: Defines a security group in AWS.

    • google_compute_firewall: Defines a firewall rule in Google Cloud.

    • azurerm_network_security_group: Defines a network security group in Azure.

  • Infrastructure Resources:

    • terraform_remote_state: Allows you to reference outputs from other Terraform states.

    • random_password: Generates a random password.

Data sources allow Terraform to use information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions. They are normally read-only and are defined using the data block. Data sources allow you to fetch and reference existing data from your infrastructure or cloud provider without creating a new resource. Following is the format for defining a data source:

data "provider_type" "data_source_name" {
  # Configuration parameters for the data source
}
  • provider_type: Specifies the type of data source, such as "aws_subnet" to retrieve information about an AWS subnet.

  • data_source_name: An optional name for the data source, which allows you to reference it elsewhere in your configuration.

Data sources are frequently used to obtain properties or metadata from already-existing infrastructure components, which can subsequently be utilized in other sections of your Terraform setup. Examples of data sources are:

  • aws_subnet: Retrieves information about an AWS subnet.

  • google_compute_network: Retrieves details about a Google Cloud network.

  • azurerm_virtual_machine: Retrieves information about an Azure Virtual Machine.

Task 2: Understand variables, data types, and expressions in HCL

In HashiCorp Configuration Language (HCL), which is used in Terraform for writing configuration files, you can work with variables, data types, and expressions to customize and manipulate your infrastructure code.

Create a variables.tf file and define a variable

  • To create a variable.tf file in Terraform and define a variable, follow these steps:
  1. Create a new file in your Terraform-practice directory and name it as variables.tf.

Open the variables.tf file and define as variable block as follows:

 variable "demo-file" {
        type = string


}
~
  • Variable: Indicates that you are defining a variable.

  • "demo-file": The name of the variable. You can choose any name you like.

  • type: Specifies the data type of the variable. In this case, it's set to string, indicating that the variable will hold a string value.

  • Use the variable in a main.tf file to create a "local_file" resource.

    To use the variable defined in the variables.tf file in your main.tf file to create a "local_file" resource, you can follow these steps:

    you have already defined the "demo-file" variable in your variables.tf file as described earlier, here's how you can use it:

    1. Create the main.tf file in the same Terraform-practice directory.

    2. Define the "local_file" resource in your main.tf file, and use the "demo-file" variable as part of the resource's configuration. In this example, we'll create a local text file demo.txt.

       resource "local_file" "file1" {
               filename = "demo.txt"
               content = "var.demo-file"
       }
      

NOw, After defining variables and main.tf file we have to initialize the terraform by following command terraform init.

After initializing the terraform, will look for Plan by following command- terraform plan and after that to create the file execute the command- terraform apply as shown in snapshot.

As we can see that the file demo.txt has been created in the directory terraform-practice.

Task 3: Practice writing Terraform configurations using HCL syntax

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

    In terraform, we can specify required_providers in terraform.tf file by adding required_providers block inside required_providers block.

    Inside this block, specify the provider name and the version you want to use. For AWS, it would look like this:

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = ">= 3.0.0"
    }
  }
}
  • aws: The name of the provider you are specifying.

  • source: The source of the provider, which is in the format hashicorp/provider-name. For AWS, it's "hashicorp/aws."

  • version: The version constraint for the provider. In this case, we specify ">= 3.0.0," which means any version equal to or greater than 3.0.0 is acceptable.

  • Now, you can use AWS resources in your Terraform configuration, and Terraform will automatically download the specified provider version when you initialize your project using terraform init.

  • Create a resource block and give the resource type as "aws_instance" and resource_name as "example" with the required parameters.

      resource "aws_instance" "example" {
        ami           = "ami-0c55b159cbfafe1f0"
        instance_type = "t2.micro"
        # Additional configuration for your EC2 instance
      }
    
  • Test your configuration using the Terraform CLI and make any necessary adjustments

  • To test the configuration, execute the command terraform init to initialize the terraform.

  • After initialization, run the command terraform validate to check for the errors to validate the configuration.

  • Once successful validation is done, use terraform plan to view the plan for the configuration, It will show the plan for the resource.

  • To apply the plan, run the command terraform apply. After that confirm the plan by adding the value "yes".

  • Now we can see the configuration is run successfully and creates the resources as shown in Task 02