HashiCorp Configuration Language

On this page 7

HashiCorp Configuration Language (HCL) is a declarative configuration language designed to describe infrastructure and tool settings in a form that is readable by people and precise enough for machines. In Infrastructure as code for the Cloud, it is best known as the language of Terraform and OpenTofu, where it defines resources, providers, variables and modules.

HCL sits between a pure data format such as JSON and a general-purpose programming language. It offers blocks, attributes and expressions, including references, functions and conditional logic, while deliberately avoiding arbitrary control flow so that configurations remain predictable and analyzable before anything is changed.

How HCL structures a configuration

An HCL file is built from two primitives: attributes, which assign a value to a name, and blocks, which group attributes under a type and optional labels. A Terraform resource block such as resource "aws_instance" "web" has the block type resource and two labels that name the resource type and its local identifier.

The language specification defines a native syntax, normally stored in files ending in .tf or .hcl, and an equivalent JSON syntax for machine-generated configuration. Both map to the same information model, so tools can accept hand-written and generated files side by side.

The table below lists the main structural elements and their roles.

ElementExamplePurpose
Attributeinstance_type = "t3.micro"Assigns one value to a name
Blockresource "aws_s3_bucket" "logs" { }Groups settings under a type and labels
Expressionvar.regionComputes a value from references
Function callcidrsubnet(var.cidr, 8, 1)Transforms values with built-in logic
Comment# primary networkDocuments intent without effect
Structural elements of HCL

Expressions, types and dependencies

HCL expressions give configurations controlled dynamism. Values can reference input variables, local values, data sources and attributes of other resources, and they can be combined with operators, conditional expressions of the form condition ? a : b, and for expressions that transform lists and maps.

The language has a type system with primitive types (string, number, bool) and structural types (list, set, map, object, tuple). Terraform uses type constraints on variables to reject invalid input early, and it performs automatic conversion where it is safe, such as turning the string “5” into a number.

References between blocks also create an implicit dependency graph. When a subnet refers to aws_vpc.main.id, the tool knows that the network must exist first. This lets Terraform and OpenTofu order and parallelize operations without explicit sequencing, while depends_on covers rare hidden dependencies.

The following table compares the most used expression features.

FeatureSyntax patternTypical use
Referenceresource_type.name.attributePass outputs between resources
Conditionalvar.prod ? 3 : 1Vary size by environment
For expression[for s in var.subnets : s.id]Reshape collections
Splataws_instance.web[*].idCollect one attribute from many
Dynamic blockdynamic "ingress" { }Generate repeated nested blocks
Meta-argumentcount or for_eachCreate multiple instances
Common expression features

HCL compared with other configuration formats

HCL is one of several ways to express infrastructure as code, and its position is defined by readability with limited logic. YAML and JSON carry data only, while tools such as Pulumi and AWS CDK use full programming languages. Bicep and HCL occupy the same middle ground of purpose-built declarative languages.

The comparison below shows how HCL relates to its main alternatives.

ApproachLogic supportReadabilityMain ecosystems
HCLExpressions, loops, functionsHighTerraform, OpenTofu, Packer, Nomad
JSONNoneLow for large filesAWS CloudFormation, generated configs
YAMLNone without templatingHigh until deeply nestedAnsible, Kubernetes, CloudFormation
BicepExpressions and loopsHighMicrosoft Azure only
General-purpose languagesUnlimitedDepends on code qualityPulumi, AWS CDK
HCL and alternative configuration approaches

The main advantage of HCL over general-purpose languages is that a configuration can be evaluated without executing arbitrary code, which simplifies review, static analysis and policy as code checks. The trade-off is that complex abstractions can feel verbose or awkward compared with a real programming language.

Where HCL is used and how to write it well

Beyond Terraform and OpenTofu, HCL appears in Packer templates, Nomad job specifications, Consul and Vault configuration, and in Terragrunt files. Each tool defines its own schema of permitted blocks on top of the shared language, so the syntax is common while the vocabulary differs.

Well-maintained HCL code follows a few consistent conventions: one purpose per file, such as variables.tf, outputs.tf and main.tf; descriptive resource names; typed variables with descriptions and validation rules; and automatic formatting with terraform fmt or tofu fmt. Repeated patterns belong in a reusable Terraform module rather than in copied blocks.

The decision table below covers frequent design choices.

SituationRecommended constructReason
Instances keyed by namefor_each with a mapStable addresses when items change
Identical copies by numbercountSimple scaling of uniform resources
Repeated derived valueslocals blockOne definition, many references
Environment differencesVariables and tfvars filesSame code, different inputs
Invalid input riskVariable validation blocksFails before planning starts
Practical HCL design decisions

Limitations and common mistakes

HCL is intentionally not Turing-complete in everyday use, so complex logic often ends up in long expressions that are difficult to read and test. Error messages for type mismatches inside nested objects can also be hard to interpret, especially for newcomers.

  • Using count for lists whose order changes, which causes unexpected destroy and recreate operations.
  • Hardcoding regions, account identifiers or secrets instead of passing them as typed input variables.
  • Writing secrets in plain text, forgetting that values can still appear in Terraform state even when marked sensitive.
  • Overusing dynamic blocks, which makes configurations harder to review than explicit blocks.
  • Confusing HCL syntax with tool behavior: the language defines structure, while each tool decides meaning.

A non-technical view

HashiCorp Configuration Language is a structured way of writing down what infrastructure should exist. Think of it as a detailed order form. You list the servers, networks and storage you need. A tool such as Terraform then builds exactly that.

The form allows a little intelligence, such as “three servers in production, one in testing”. It still stays simple enough for colleagues to read and check. The key point is that the file describes the result, not the steps, and the tool works out how to get there.

A concrete example

A platform team at a mid-sized online retailer manages three environments, development, staging and production, on a public cloud. Previously, engineers created resources by hand in the web console, and the environments slowly drifted apart.

The team rewrites the setup in HCL as one Terraform module for networking, one for a container cluster and one for databases. A variable named environment controls instance sizes through a conditional expression, and `for_each` creates subnets in three availability zones from a single map. Every change now goes through a pull request where reviewers read the HCL diff and the plan output.

Within one quarter, staging becomes a faithful copy of production at smaller scale, a new region is added by supplying a different variables file, and configuration drift is detected by scheduled plan runs. The readable, reviewable files turned infrastructure changes from manual console work into a routine, auditable process.