Skip to content

Syntax of HCL

HCL is the short version of “HashiCorp Configuration Language“, it is a toolkit for creating structured configuration languages that are both human- and machine-friendly, for use with command-line tools.

People may ask: why not JSON or YAML?

Whereas JSON and YAML are formats for serializing data structures, HCL is a syntax and API specifically designed for building structured configuration formats. HCL syntax is designed to be easily read and written by humans, and allows declarative logic to permit its use in more complex applications.

HCL is intended as a base syntax for configuration formats built around key-value pairs and hierarchical blocks whose structure is well-defined by the calling application, and this definition of the configuration structure allows for better error messages and more convenient definition within the calling application.

Attributes and Blocks

The Terraform language syntax is built around two key syntax constructs: attributes (also called arguments) and blocks.

location = "US"

The identifier before the equals sign is the attribute name, and the expression after the equals sign is the attribute’s value.

resource "google_storage_bucket" "static" {
 name          = "BUCKET_NAME"  # give your unique bucket name
 location      = "US"
 storage_class = "STANDARD"

}

The resource block defines a resource that exists within the infrastructure.  In this snippet, it is a cloud storage bucket resource in US with standard storage class.

Resources

Terraform resources are the most important elements in Terraform, as they provision infrastructure such as VMs, load balancers, NAT gateways, and so forth. Resources are declared as HCL objects with type resource and exactly two labels. The first label specifies the type of resource you want to create, and the second is the resource name.

In this snippet, the type of resource is google_compute_network, and the name of resource is vpc_network.

Together, the type and name make up the resource identifier, which is unique for each resource.

resource "google_compute_network" "vpc_network" {
  name                    = "my-custom-mode-network"
  auto_create_subnetworks = false
  mtu                     = 1460
}

Providers

Another important element is provider. The provider is responsible for understanding API interactions, making authenticated requests, and exposing resources to Terraform. Let’s configure the GCP provider by adding a provider block

Unlike resources, providers have only one label: Name. This is the official name of the provider as published in the Terraform Registry (e.g. “aws” for AWS, “google” for GCP, and “azurerm” for Azure).

provider "google" {

  project = "PROJECT ID"  #replace to your project id
  region  = "REGION"      #replae to your region
  zone    = "ZONE"        #replace to your zone
}