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