HCL Language – 4 – Data Types (strings, numbers, lists, maps) in HCL

Data Types in HCL

HashiCorp Configuration Language (HCL) supports various data types to represent different kinds of values within your configurations. Understanding these data types is essential for creating flexible and expressive infrastructure as code. In this guide, we’ll explore the core data types in HCL, including strings, numbers, lists, and maps.

Strings

Strings are a fundamental data type in HCL and are used to represent text values. They are enclosed in double quotes.


variable "message" {
  description = "A greeting message"
  type        = string
  default     = "Hello, HCL!"
}
    

In this example, the “message” variable is of type string and contains the default greeting message.

Numbers

Numbers in HCL can be represented as integers or floating-point values. They are used for various purposes, including specifying counts, sizes, and numerical configurations.


variable "instance_count" {
  description = "Number of instances to create"
  type        = number
  default     = 3
}
    

Here, the “instance_count” variable is of type number and represents the count of instances to create.

Lists

Lists are ordered collections of values. They are defined using square brackets and can include a mix of different data types.


variable "tags" {
  description = "List of tags"
  type        = list(string)
  default     = ["app", "prod", "web"]
}
    

In this example, the “tags” variable is a list of strings, containing tags for resources. Lists are versatile and can hold any combination of data types.

Maps

Maps in HCL are collections of key-value pairs. They are defined using curly braces and are often used to represent configurations with named properties.


variable "subnet_config" {
  description = "Subnet configuration"
  type        = map(object({
    cidr_block = string
    availability_zone = string
  }))
  default = {
    us-east-1a = {
      cidr_block = "10.0.0.0/24"
      availability_zone = "us-east-1a"
    }
    us-east-1b = {
      cidr_block = "10.0.1.0/24"
      availability_zone = "us-east-1b"
    }
  }
}
    

In this case, the “subnet_config” variable is a map that defines subnet configurations for different availability zones in a region. The values in the map are of type object, which itself includes key-value pairs.

Working with Data Types

HCL provides powerful ways to work with these data types. You can perform operations, validations, and interpolations based on the specific data type. For instance, you can concatenate strings, perform mathematical operations on numbers, iterate over lists, and access values in maps.

Conclusion

Data types in HCL allow you to create expressive and flexible configurations for your infrastructure as code. By understanding and correctly using strings, numbers, lists, and maps, you can define and manage complex infrastructure resources with precision and clarity.