Reading environment variables in a terraform file
Working with terraform a lot of times you need to deal with environment variables, be it reading credentials or externalising some other…
The right way to DevOps
Working with terraform a lot of times you need to deal with environment variables, be it reading credentials or externalising some other configuration.
Let’s see how to do that.
Add
TF_VAR
suffix to your regular environment variables.
i.e YOUR_VARIABLE
should be TF_VAR_YOUR_VARIABLE
Instead of changing the name of the existing environment variable create a new one.
TF_VAR_AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
2. Declare a variable with the same name as the part after the suffix inside the terraform file.
TF_VAR_AWS_ACCESS_KEY_ID
is the environment variable
We will declare the variable inside the file as :
variable "AWS_ACCESS_KEY_ID" {}
3. Automatically this variable will read the environment variable TF_VAR_AWS_ACCESS_KEY_ID
4. The variable can be used anywhere inside the file this way:
Before version 12
provider "aws" { access_key = "${var.AWS_ACCESS_KEY_ID}" secret_key = "${var.AWS_SECRET_ACCESS_KEY}" region = "us-east-1"}
Version 12 onwards
provider "aws" { access_key = var.AWS_ACCESS_KEY_ID secret_key = var.AWS_SECRET_ACCESS_KEY region = "us-east-1"}
Refer to the actual code here.
Happy Learning:)