Terraform Common Variable Attributes
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:
type
: Specifies the type of the variable.Valid types are :
string
,number
,bool
,list(type)
,set(type)
,map(type)
,object({key=type,...})
, andtuple([type,...])
.variable "instance_count" { type = number }
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 }
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" }
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." } }
sensitive
: If set totrue
, prevents the variable's value from being displayed in Terraform's output.variable "db_password" { type = string sensitive = true }
nullable
: If set tofalse
, the variable must be provided a non-null value. The default istrue
, 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.