In this post, we will discuss different approaches to variable assignment in Terraform.
Here are the different approaches:
- Variable Defaults
- Command-line flags
- From a file
- Environment variables
We will go into detail one by one and see examples of using them.
1. Variable Default
In this approach, we create a variable.tf file and define a variable and assign a default value to a variable.
variable "instance_type" {
default = "t2.micro"
}
This is referred to as variable default if no value is mentioned for the variable then the default value will be assigned.
Here comes the question what will happen if we don’t provide a default value?
Let’s try it out. We removed the default value and now our variable looks like this.
variable "instance_type" {}
And do a terraform plan
terraform plan
You will get an output like this:
var.instance_type
Enter a value:
so if you have not defined a default variable terraform will ask you for the value from the command line.
2. Command-line flags
In the similar example above if we have a variable and we have not provided a default value or we want to override the value. We can do so by providing value in the command line.
terraform plan --var="instance_type=t2.small"
3. From a file
Another way you can provide value is using file. Create a terraform.tfvars file and provide value to variables.
//terraform.tfvarsinstance_type="t2.micro"
Now when you do terraform plan the instance type value will be taken from terraform.tfvars file.
Note: File naming is important here. Terraform by default only looks for terraform.tfvars file.
Let’s say for some reason you want to use a custom file name. Create a new file custom.tfvars and delete the terraform.tfvars
Now in order to use custom.tfvars you can provide the file name in CLI like below.
terraform plan -var-file="custom.tfvars"
finally, let’s explore the environment-based approach.
4. Environment variables
Let’s set an environment variable:
In windows:
setx TF_VAR_instance_type t2.micro
The TF_VAR_<VARIABLE> <Value> is terraform specific.
In Linux/Mac
export TF_VAR_instance_type t2.micro
Read more about terraform variables from here:
Comments
Post a Comment