Loading...
Loading...
Parameterize configurations with input variables and expose values with outputs
Variables let you parameterize your Terraform config so it works for different environments (dev, staging, production) without copying files.
variable "location" {
description = "Azure region for resources"
type = string
default = "East US"
}
variable "environment" {
description = "Environment name (dev/staging/prod)"
type = string
}
variable "tags" {
description = "Common resource tags"
type = map(string)
default = {
managed_by = "terraform"
}
}resource "azurerm_resource_group" "main" {
name = "app-${var.environment}"
location = var.location
tags = var.tags
}| Syntax | What it does |
|---|---|
| `var.variable_name` | References a variable value |
| `"app-${var.environment}"` | String interpolation |
| `variable "name" {}` | Declares a variable block |
# Via command-line
terraform apply -var="environment=dev" -var="location=West US"
# Via .tfvars file
echo 'environment = "prod"
location = "North Europe"' > terraform.tfvars
# Via environment variable
export TF_VAR_environment=stagingOutputs expose information about your infrastructure after creation:
output "resource_group_name" {
description = "Name of the created resource group"
value = azurerm_resource_group.main.name
}
output "storage_account_endpoint" {
value = azurerm_storage_account.data.primary_blob_endpoint
}After apply, outputs are displayed:
Apply complete! Resources: 3 added.
Outputs:
resource_group_name = "app-prod"
storage_account_endpoint = "https://proddata123.blob.core.windows.net"| Wrong | Why | Right |
|---|---|---|
| `variable name` without quotes around default string | HCL requires strings in quotes | `default = "East US"` |
| Referencing `variable.name` instead of `var.name` | Variables use `var.` prefix | `var.location` |
| Hard-coding values across resources | Breaks reusability | Use variables for anything that changes |
Create a variable block for environment (string, no default) and instance_count (number, default 2). Then create an output that displays the values.
variable "environment" {
description = "Environment name"
type = string
}
variable "instance_count" {
description = "Number of instances"
type = number
default = 2
}
output "env_name" {
value = var.environment
}
output "count" {
value = var.instance_count
}