When building a multi-environment application using Terraform, you will need a way to specify environment specific variables. We will discuss how we accomplish this through the use of input variables and tfvars files.
Terraform input variables
When constructing your cloud architecture using Terraform, you can dynamically configure your resources and services using input variables. You must define input variables in a .tf file. Typically we define our input variables in a “variables.tf” file. Within our file we define variable names, types, default values, and descriptions. Below is an example of what our “variables.tf” looks like.
variable "environment" {
type = "string"
description = "Environment in which to deploy application"
}
variable “another_variable” {
default = “tg4solutions”
}
There are a few things we would like to call out above. If a variable type is not specified, the type is assumed to be string. When a default value is not specified, a value must be assigned to that variable. Otherwise, when executing a statement Terraform will prompt you for the values via the console. You will only be prompted for string variable types that are missing value assignments. You must assign other variable types prior to execution.
Assign input variable values
In the previous step we defined our input variables, now we must specify their assigned values. Terraform will source values for input variables in the following three locations.
- Command line – You can set input variable values by passing them directly using the “-var” flag.
- Environment variables – Terraform will source environment variables that begin with “TF_VAR_” and assign to matching input variables.
- File – Using a .tfvars file, you can assign values to your input variables.
Below you can find a sample .tfvars file.
environment = "dev"
Deploy changes using tfvars
In order to configure our variables to be environment agnostic, we will create a tfvars file for each environment in which we want our application to run. Therefore, when running Terraform init, plan, and apply commands we only have to specify the associated tfvars file for the environment in which we would like to run. For example, if we have a development, qa, and production environment we would execute the following command to apply a change in the production environment.
terraform apply -auto-approve -input=false -var-file=terraform/production.tfvars
Conclusion
When deploying our cloud architecture across multiple environments, we use a tfvars file for each environment within the same repo. This allows us to deploy changes using the same repo without updating our tfvars for each environment. This structure simplifies our continuous delivery process because once we identify the environment for which to deploy, we already know which tfvars file to use to configure our resources.
If you have further questions or suggestions, don’t hesitate to contact us.