0
0
Terraformcloud~30 mins

Environment variables (TF_VAR_) in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Environment Variables (TF_VAR_) in Terraform
📖 Scenario: You are setting up a Terraform configuration to create a cloud resource. To keep your configuration flexible and secure, you want to use environment variables to pass values into Terraform variables.
🎯 Goal: Build a Terraform configuration that uses environment variables prefixed with TF_VAR_ to set variable values without hardcoding them in the configuration files.
📋 What You'll Learn
Create a Terraform variable named region with a default value
Set an environment variable named TF_VAR_region to override the default
Use the region variable in a Terraform resource configuration
Apply the configuration to verify the environment variable is used
💡 Why This Matters
🌍 Real World
Using environment variables to configure Terraform variables allows teams to keep sensitive or environment-specific data out of code files, making deployments safer and more flexible.
💼 Career
Cloud engineers and DevOps professionals often use environment variables to manage infrastructure configurations securely and efficiently across different environments.
Progress0 / 4 steps
1
Define a Terraform variable region
Create a Terraform variable named region with the default value us-west-1 inside a file called variables.tf. Write exactly this variable block:
Terraform
Need a hint?

This variable block defines a string variable named region with a default value.

2
Set the environment variable TF_VAR_region
Set an environment variable named TF_VAR_region with the value us-east-2 in your shell before running Terraform. Write this exact command for a Unix-like shell:
Terraform
Need a hint?

Use export TF_VAR_region="us-east-2" to set the environment variable in bash or similar shells.

3
Use the region variable in a Terraform provider block
In a file called main.tf, write a Terraform provider block for AWS that uses the variable region for its region attribute. Use this exact syntax:
Terraform
Need a hint?

The provider block tells Terraform which AWS region to use, referencing the variable region.

4
Add a simple AWS S3 bucket resource using the region variable
In main.tf, add a resource block to create an AWS S3 bucket named my-tf-bucket with the bucket name my-tf-bucket-12345. Use the region variable indirectly by relying on the provider configuration. Write exactly this resource block:
Terraform
Need a hint?

This resource creates a private S3 bucket. The region is set by the provider using the variable.