In Terraform Cloud, variables are used to:
π Pass dynamic values to your Terraform code
π Avoid hardcoding sensitive or environment-specific data
π§ Simple Definition
π Variables = Inputs to your Terraform code
Example:
- Region
- VM name
- Credentials
π― Why Use Variables?
Without variables:
region = "eastus"
π Hardcoded ❌
With variables:
region = var.region
π Flexible ✅
π§© Types of Variables in Terraform Cloud
1️⃣ Terraform Variables
Used inside .tf code
Example:
variable "region" {
type = string
}
2️⃣ Environment Variables
Used for:
- Credentials
- API keys
Example:
ARM_CLIENT_ID
ARM_SECRET
π Sensitive Variables
π Used for secrets:
- Passwords
- Tokens
✔ Hidden in UI
✔ Not printed in logs
π Where to Define Variables in Terraform Cloud?
Go to:
π Workspace → Variables
You’ll see:
- Terraform Variables
- Environment Variables
π Step-by-Step: Using Variables
πͺ Step 1: Define Variable in Code
variable "resource_group_name" {
description = "Azure Resource Group"
type = string
}
πͺ Step 2: Use Variable
resource "azurerm_resource_group" "rg" {
name = var.resource_group_name
location = "East US"
}
πͺ Step 3: Add Variable in Terraform Cloud
Go to:
π Workspace → Variables → Add Variable
Example:
-
Key:
resource_group_name -
Value:
my-rg-demo
πͺ Step 4: Run Terraform
terraform apply
π Value comes from Terraform Cloud
☁️ Azure Example (Real Use Case)
Variables
variable "location" {}
variable "rg_name" {}
Resource
resource "azurerm_resource_group" "example" {
name = var.rg_name
location = var.location
}
Terraform Cloud Values
| Key | Value |
|---|---|
| rg_name | demo-rg |
| location | East US |
π Environment Variables Example (Azure Login)
For **Microsoft Azure:
Set in Terraform Cloud:
ARM_CLIENT_ID
ARM_CLIENT_SECRET
ARM_SUBSCRIPTION_ID
ARM_TENANT_ID
π These are required for authentication
π§ Variable Priority (Important)
Terraform uses variables in this order:
- CLI input
-
.tfvarsfile - Environment variables
- Terraform Cloud variables
π Terraform Variables vs Environment Variables
| Feature | Terraform Variable | Environment Variable |
|---|---|---|
| Usage | Config values | Credentials |
| Visible | Yes | Hidden |
| Example | region | API key |
⚠️ Common Mistakes
❌ Hardcoding secrets
❌ Wrong variable names
❌ Not marking sensitive data
✅ Best Practices
✔ Use variables for flexibility
✔ Use environment variables for secrets
✔ Mark sensitive variables
✔ Use naming conventions
π§ Easy Analogy
π Terraform code = Template
π Variables = Input values
Like:
π Form + User input
π― Final Summary
π Variables make Terraform reusable
π Terraform Cloud stores them securely
π Environment variables handle secrets
This is gold for anyone learning DevOps π
ReplyDeleteMost people skip Terraform fundamentals… and struggle later.
Are you using inputs & data sources correctly?
Comment “YES” or “NO” π https://www.linkedin.com/pulse/terraform-resources-inputs-outputs-data-sources-aws-complete-kumar-gdayc