How to Use Optional Arguments in Terraform Variables

How to Use Optional Arguments in Terraform Variables

In this short article, we will take a look at Terraform variables and the optional arguments they use. We will explain what they are, how to reference them, explain why they are useful, and how to use type constraints to enhance the quality of your code.

We will cover:

  1. What are optional arguments for variable declarations?
  2. How to use optional arguments – example
  3. Type constraints

What are optional arguments for variable declarations?

Optional arguments in Terraform can be used when specifying variables to enhance the quality of your code.

When you define a variable in Terraform, it can simply be defined as:

variable "example_var" {

The available optional arguments that you can include are:

  • type
  • default
  • description
  • validation
  • sensitive
  • nullable

An example variable declaration could look like this with all the optional parameters included:

variable "example_var" {
  type        = string
  default     = "chewbacca"
  description = "8 foot tall wookie"
  validation  = {
    condition     = var.example_var = "chewbacca"
    error_message = "Value must be a wookie"
  sensitive   = false
  nullable    = false

Why are the optional parameters useful?

Using optional parameters or combinations of the optional parameters in your variables can be useful depending on your use case. They are used to further define variables’ behavior and characteristics and make your variables more structured and controlled, making your Terraform configurations more robust and user-friendly.

Read more about Terraform variables.

How to use optional arguments — examples

Let’s look at each Terraform optional variable argument.

1. type

The type argument specifies the expected data type of the variable. This helps Terraform validate that the value provided for the variable matches the expected type.

variable "example_var" {
  type = string

2. default

The default argument provides a default value for the variable. If no value is explicitly passed when applying the configuration, Terraform will use the default value.

variable "example_var" {
  type    = string
  default = "default_value"

3. description

The description argument allows you to add a human-readable description to the variable. This description can help other users understand the purpose of the variable. As a suggested good practice, you can use the same description as the Terraform docs.

For example, the name variable description from the Azure Virtual Network page:

variable "name" {
  type        = string
  description = "(Required) The name of the virtual network. Changing this forces a new resource to be created.."

4. validation

The validation argument enables you to specify a validation rule using a function that the value of the variable must pass. If the validation fails, Terraform will raise an error.

variable "example_var" {
  type = number

  validation {
    condition     = var.example_var > 0
    error_message = "Value must be greater than 0."

5. sensitive

When set to true, the value of the variable is treated as sensitive information. Terraform will take care to prevent the value from being shown in logs and outputs. Note that Terraform will still record sensitive values in the state, so anyone who can access the state data will have access to the sensitive values in cleartext.

variable "password" {
  type      = string
  sensitive = true

6. nullable

The nullable argument in a variable block controls whether the module caller may assign the value null to the variable.

nullvalue is one that represents absence or omission. If you set an argument of a resource to null, Terraform behaves as though you had completely omitted it — it will use the argument’s default value if it has one or raise an error if the argument is mandatory.

variable "example" {
  type     = string
  nullable = false

Type constraints

Using the type constraint when defining a variable specifies the expected data type of the variable. If no type constraint is set, then a value of any type is accepted.

If both the type and default arguments are specified, the given default value must be convertible to the specified type. The Terraform language will automatically convert number and bool values to string values when needed, and vice-versa as long as the string contains a valid representation of a number or boolean value.

variable "example_var" {
  type = number

Acceptable ‘primitive’ type values are:

  • string
  • bool
  • number
  • any (indicates a value of any type is accepted).

The type constructors also allow you to specify complex types such as collections:

  • list(<TYPE>)
  • set(<TYPE>)
  • map(<TYPE>)
  • object({<ATTR NAME> = <TYPE>, ... })
  • tuple([<TYPE>, ...])

Key points

Variables can be specified with optional parameters to enhance the quality of your code. Including appropriate optional parameters in variables depending on your use case can be useful. As a best practice, you should consider at least including the description to help with the readability of your code, where you may consider adding other parameters unnecessary.

We encourage you also to explore how Spacelift makes it easy to work with Terraform. If you need any help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this. It supports Git workflows, policy as code, programmatic configuration, context sharing, drift detection, and many more great features right out of the box. You can check it for free by creating a trial account.

Note: New versions of Terraform will be placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that will expand on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6. OpenTofu retained all the features and functionalities that had made Terraform popular among developers while also introducing improvements and enhancements. OpenTofu works with your existing Terraform state file, so you won’t have any issues when you are migrating to it.

Manage Terraform Better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.

Start free trial