Terraform : Input Variables
Terraform allows you to define and provision infrastructure resources using declarative configuration files. Input variables in Terraform provide a way to customize the behavior of your configurations by allowing values to be passed externally. They make your configurations more reusable, dynamic, and customizable. Input variables separate configuration logic from values, making your infrastructure code more maintainable and adaptable.
Using input variables provides several benefits:
- Reusability: Input variables allow you to create reusable and configurable infrastructure code. Instead of hardcoding values, you can use variables to make your configurations more flexible and adaptable to different environments.
- Separation of Concerns: Input variables separate the infrastructure code from the variable values. This separation allows different teams or individuals to work on different parts of the infrastructure without needing to modify the underlying code.
- Dynamic Configuration: With input variables, you can dynamically configure your infrastructure based on external inputs. For example, you can define variables for the number of instances in an autoscaling group or the desired size of an Amazon S3 bucket.
Example Variable Declaration:
You can declare input variables using the variable block. This block specifies the variable's name, type, and optional default value. For example:
variable "image_id" {
type = string
}
variable "availability_zone_names" {
type = list(string)
default = ["us-west-1a"]
}
variable "docker_ports" {
type = list(object({
internal = number
external = number
protocol = string
}))
default = [
{
internal = 8300
external = 8300
protocol = "tcp"
}
]
}Arguments:
When declaring variables, you can specify several arguments to define their behavior and characteristics:
Name: This argument specifies the name of the variable. It should follow the Terraform naming conventions and be unique within the configuration.
variable "instance_type" {
// ...
}In this example, the variable is named “instance_type”. The name should be unique within the configuration.
Description: You can provide a description for the variable to document its purpose, usage, or any other relevant information. The description is helpful for other users who might interact with your Terraform configuration.
variable "instance_type" {
description = "The type of EC2 instance"
// ...
}Here, the description provides additional information about the purpose or usage of the variable. It helps document the variable for other users.
Type: This argument defines the type of the variable. Terraform supports various built-in types such as string, number, bool, list, map, and more. Specifying the correct type helps ensure that the variable is used correctly throughout your configuration.
variable "instance_type" {
type = string
// ...
}The type argument specifies the type of the variable. In this case, it is set to
string, indicating that the variable should contain a string value. Other supported types includenumber,bool,list,map, etc.
Default: You can assign a default value to the variable, which will be used if no value is provided from an external source. The default value is optional. If you don’t specify a default value and no value is provided externally, Terraform will throw an error during validation.
variable "instance_type" {
default = "t2.micro"
// ...
}The default argument assigns a default value to the variable. If no value is provided from an external source, this default value will be used. In this example, if no value is set for
instance_type, it will default to "t2.micro".
Required: By default, variables are optional, meaning they don’t have to be explicitly set if a default value is provided. However, if you want to enforce that the variable must be explicitly set, you can set the required argument to true. This will ensure that a value is provided from an external source.
variable "instance_type" {
required = true
// ...
}By setting
requiredtotrue, you make the variable mandatory. It means a value must be explicitly set from an external source. If no value is provided, Terraform will throw an error during validation.
Validation Rules: Terraform allows you to define validation rules for variables to enforce specific constraints. For example, you can specify that a variable must be within a certain range, match a regular expression, or satisfy any other custom condition.
variable "instance_type" {
# ...
validation {
condition = can(regex("^t2.*", var.instance_type))
error_message = "Invalid instance type format"
}
}Here, a validation rule is defined using the
validationblock to ensure that theinstance_typevariable matches the regular expression^t2.*. If the condition fails, the error message will be displayed.
Sensitive: If a variable contains sensitive information, such as passwords or API keys, you can mark it as sensitive. This ensures that the variable's value is not displayed in the output logs and state files, providing an additional layer of security.
variable "api_key" {
sensitive = true
# ...
}In this example, the
api_keyvariable is marked as sensitive. When Terraform logs or stores the variable's value, it will hide the actual value for security reasons.
Note, Terraform will still record sensitive data in the state file , and anyone with access to the state file can read the sensitive data value in clear text.
Empty input variable:
In Terraform, you can define an empty input variable by not specifying a default value and not marking it as required. This allows you to have a variable that can be optionally provided from an external source, but if not provided, it will be considered empty.
variable "empty_variable" {
description = "An empty variable"
type = string
}In this example, the
empty_variableis declared without a default value and without therequiredargument set totrue. This means that it is optional and can be left empty if not provided from an external source.
If you want to declare an input variable that cannot be left empty or null, you can use the nullable argument and set it to false. This ensures that a value must be provided for the variable and it cannot be left empty.
variable "example_variable" {
type = string
nullable = false
}In this example, the
example_variablevariable is defined as a string type andnullableis set tofalse. This means that a value must be provided for theexamplevariable when running Terraform commands, and an empty or null value will result in an error.
Assigning Values to Input Variables:
Command Line Flags: You can pass values directly from the command line using the -var or -var-file flags when running Terraform commands.
terraform apply -var="variable_name=value"
terraform apply -var-file="vars.tfvars"Variable Definition Files: You can create a .tfvars file to define variable values. This file contains variable assignments in a key-value format.
# definationfile.tfvars
variable_name = "value"
another_variable = 123456Use -var-file flag to load the variable values from this file:
terraform apply -var-file="definationfile.tfvars"Note: Terraform also automatically loads a number of variable definitions files if they are present:
- Files named exactly
terraform.tfvarsorterraform.tfvars.json. - Any files with names ending in
.auto.tfvarsor.auto.tfvars.json.
Variable Definition Precedence:
When multiple sources provide values for the same variable, Terraform follows a specific order of precedence to determine which value to use. The order of precedence, from highest to lowest, is as follows:
- Flags using the
-varoption take the highest precedence. *.auto.tfvarsor*.auto.tfvars.jsonfiles.terraform.tfvars.jsonfileterraform.tfvarsfile- Environment variables
Note:
There are a set of keywords that cannot be used as input variable names in Terraform. These keywords are reserved for meta-arguments in module configuration blocks.
The following keywords cannot be used as input variable names:
sourceversionproviderscountfor_eachlifecycledepends_onlocals
If you try to use one of these keywords as an input variable name, Terraform will throw an error.
Resources
Do not forget the 👏 if you like this content Also I will be glad if you hit the follow button so you get notified of my new posts. You can also follow me on Linkedin ! Thank you!!
