Terraform Common Variable Attributes

·

2 min read

In Terraform, when defining variables, several attributes can be specified to control their behavior. Here are the primary attributes you can use when defining variables in Terraform:

  1. type: Specifies the type of the variable.

    Valid types are :

    string, number, bool, list(type), set(type), map(type), object({key=type,...}), and tuple([type,...]).

     variable "instance_count" {
       type = number
     }
    
  2. description: Provides a description of the variable. This is useful for documentation purposes.

     variable "instance_type" {
       description = "The type of EC2 instance to create"
       type        = string
     }
    
  3. default: Sets a default value for the variable. If no value is provided by the user, this default value will be used.

     variable "instance_type" {
       type    = string
       default = "t2.micro"
     }
    
  4. validation: Provides custom validation rules for the variable. You can use this to enforce constraints on the variable's value.

     variable "instance_type" {
       type = string
       validation {
         condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
         error_message = "The instance type must be one of t2.micro, t2.small, or t2.medium."
       }
     }
    
  5. sensitive: If set to true, prevents the variable's value from being displayed in Terraform's output.

     variable "db_password" {
       type      = string
       sensitive = true
     }
    
  6. nullable: If set to false, the variable must be provided a non-null value. The default is true, allowing null values.

     variable "domain_name" {
       type     = string
       nullable = false
     }
    

Example

Here is an example that incorporates multiple attributes:

variable "instance_type" {
  description = "The type of EC2 instance to create"
  type        = string
  default     = "t2.micro"
  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "The instance type must be one of t2.micro, t2.small, or t2.medium."
  }
}

variable "db_password" {
  description = "The password for the database"
  type        = string
  sensitive   = true
  nullable    = false
}

These attributes allow you to define variables in a way that includes type safety, default values, validations, and sensitive data handling, making your Terraform configurations more robust and easier to manage.