Terraform basics: Variables

Yogesh
2 min readJul 5, 2021

--

There are multiple ways to use variables in TF. Variables are like passing arguments to programme.

Let’s start with a basic example.

Define a variable as shown in line 9:

variable “subnet_cidr_block” {    description = “Subnet cidr block”}

and then call it in line 20:

cidr_block = var.subnet_cidr_block

Now, you have 2 options to pass values:

$ terraform apply  << this will ask for a user input while we execute it.

Or better, we can pass value as below:

$ terraform apply -var “subnet_cidr_block=10.0.10.0/24”

Third option is preferred way to do this. Create a terraform.tfvars file

With this you can just use terraform apply. By default terraform will pickup terraform.tfvars as variable file.

A more glorified example would for variables where you can use environment variable to define multiple environments.

And reflect that in tfvars file.

Since we have changed file name from default, we need to pass on custom file name as var-file. for eg:

$ terraform apply -var-file terraform-dev.tfvars

FAQ:

  1. How to pass aws secrets via environment variables to terraform?

Execute following in your shell:

$ export AWS_SECRET_ACCESS_KEY=<access_secret_here_without_quotes>
$ export AWS_ACCESS_KEY_ID=<access_key_id_here_without_quotes>

--

--

No responses yet