Configuration Language Overview
Terraform uses the HashiCorp Configuration Language (HCL) to define infrastructure as code. HCL is a declarative language designed to be both human-readable and machine-friendly, making it ideal for describing infrastructure resources and their relationships.What is the Terraform Language?
The Terraform language is the primary interface for interacting with Terraform. It allows you to:- Declare resources - Define the infrastructure components you want to create
- Configure providers - Specify the cloud platforms and services to use
- Manage dependencies - Control the order of resource creation
- Use variables - Make configurations reusable and flexible
- Generate outputs - Export values for use by other configurations
- Organize code - Structure configurations using modules
Language Structure
Terraform configurations are written in files with the.tf extension. The language consists of:
Blocks
Blocks are containers for configuration. Each block has a type and may have labels:Arguments
Arguments assign values to names within blocks:Expressions
Expressions represent values, either literally or by referencing other values:File Structure
Terraform loads all.tf files in the current directory when you run commands. A typical configuration includes:
- main.tf - Primary resource definitions
- variables.tf - Input variable declarations
- outputs.tf - Output value declarations
- providers.tf - Provider configurations
- terraform.tfvars - Variable value assignments
File names don’t affect functionality - Terraform treats all
.tf files equally. File organization is purely for human readability.Core Concepts
Resources
Resources are the most important element. Each resource block describes one or more infrastructure objects:Data Sources
Data sources allow you to fetch information from external sources:Variables
Variables make configurations flexible and reusable:Outputs
Outputs expose values for external use:Language Features
Type System
Terraform has a rich type system:- Primitive types:
string,number,bool - Collection types:
list,map,set - Structural types:
object,tuple
Meta-Arguments
Special arguments that work with any resource:count- Create multiple instancesfor_each- Create instances from a map or setdepends_on- Explicit dependenciesprovider- Select a provider configurationlifecycle- Customize resource behavior
Functions
Built-in functions for data transformation:Comments
Terraform supports three comment styles:Best Practices
Use Consistent Naming
Follow a consistent naming convention for resources, variables, and outputs.
Organize by Purpose
Group related resources together and use modules for reusable components.
Document Your Code
Add descriptions to variables and outputs, and use comments for complex logic.
Validate Input
Use variable validation rules to catch errors early.
Next Steps
Syntax
Learn the detailed syntax rules
Resources
Define infrastructure resources
Variables
Make configurations flexible