Variable precedence in Terraform

And 3 ways of passing values to variables in your terraform code

erraform variables help define server details without having to remember infrastructure-specific values. They are similarly handy for reusing shared parameters like public SSH keys that do not change between configurations. In a computer program, variables have multiple purposes. Variables are used to store information in a program that can be accessed and modified if need be. Variables have numerous purposes. It also serves to label data with a name that can be understood clearly by readers of the program. The same applies to Terraform as well.

As part of the following example, we are trying to create an AWS Instance in the us-east-1 region. In line 3, variable instance_type is declared and used at line 11.

Terraform example code

To execute the code use the command terraform init && terraform plan && terraform apply . The following is the output one would see after the execution of the command. To create an EC2, one has to provide a value.

Output of execution of terraform apply command

The following error occurs if a value is not provided.

Error when a variable is not provided

The first way to successfully create the AWS instance is to provide a value for the instance_type variable, preferably from the EC2 Instance Types page.

Response when a instance type value is provided

The second way to do this is to pass the value inline to the terraform apply command. For example, terraform apply -var instance_type=t3a.micro should do the trick. Anything that is passed to the cli as an argument takes precedence. Like in bash, we can also pass in environmental variables as values for variables in terraform. Passing environmental variables is helpful if there are sensitive values that we do not want to save as part of version control.

Passing variable value inline.

The third and final way to do it is to use a tfvars file. Please create a new file and name it terraform.tfvars and add the line instance_type = "t3a.medium". On executing the terraform plan, you should see that the instance-type of the EC2 is set to t3a.medium. We could also create an us-east.tfvars and add the instance_type = "t3a.medium" line to it. Then to the terraform plan/apply command, pass the argument --var-file=us-east.tfvars, and you should see the instance_type value take effect. Just note that a -var flag passed takes precedence over the tfvars file.

If both the var file and the -var instance_type=t3a.medium are passed, the order of the arguments is essential. The second argument takes precedence over the first argument.

Argument precedence

Almost in motion, the Future is!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store