9. Terraform Variables
Input Variables
We can define input variables in the config file as follows
variable "subnet_prefix" {
description = "cidr block for the subnet"
default = "10.0.2.0/24"
type = string
}Accessed as
var.<name>defaultvalue like name suggests is the default value when we don't assign any value to ittype = anymeans any data type is acceptedWe can also use lists type or list of objects
Usage
Order of precedence // lowest -> highest
If we dont specify any value, it will ask us for input while running
terraform apply.Second is the default value in declaration block
TF_VAR_<name>environment variableBest way is to use a seperate file for variables with name
terraform.tfvarsWe can assign values in that file like
subnet_prefix = "10.0.1.0/24" avail_zone = "eu-west-1"If you want to use other file like
example.tfvars, you have to specify it while applying config liketerraform apply -var-file example.tfvars
*.auto.tfvarsfileCommand line arguments to enter the value of the variables like
terraform apply -var "subnet_prefix=10.0.1.0/24"or-var-file
Local Variables
We can define local variables in the config file as follows
Can be accessed as
local.<name>Temporary variables within the scope of the function
Types
Primitive Types
string
number
bool
Complex Types
list(<TYPE>)set(<TYPE>)map(<TYPE>)object({ <ATTR NAME> = <TYPE>, ... })tuple([<TYPE>, ...])
Sensitive Data
Mark variables as sensitive
Pass to terraform apply with
TV_VAR_variable-var(retrieved from secret manager at runtime)
Can also use external secret store
AWS Secrets manager
Last updated