Variables for Template Simplification
What you'll learn: How to use variables in ARM templates to eliminate repetition and make complex expressions easier to read and maintain.
Why Variables Matter
You've already learned about parameters (external inputs from users). Variables, on the other hand, are internal to your template—they're values you calculate or define once and reuse throughout the template. Think of variables as "nickname labels" you create for complex values or repeated expressions, just like giving a long address a short name like "home."
The Core Idea
Variables live in the variables section of your ARM template and can reference parameters, combine strings, or store computed values. Once defined, you reference them using the variables() function anywhere in your template.
Here's the basic pattern:
{
"parameters": {
"environment": {
"type": "string"
}
},
"variables": {
"storageAccountName": "[concat('storage', parameters('environment'), uniqueString(resourceGroup().id))]",
"location": "[resourceGroup().location]"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"location": "[variables('location')]"
// ... more properties
}
]
}
Instead of repeating concat('storage', parameters('environment'), uniqueString(resourceGroup().id)) everywhere you need that storage account name, you define it once as a variable and reuse it.
When to Use Variables
- Complex expressions that appear multiple times
- Computed values based on parameters
- Resource naming conventions you want to standardize
- Environment-specific values derived from parameters
Key Takeaway: Variables in ARM templates act as reusable constants that simplify your template, reduce errors from repetition, and make complex expressions more readable by giving them meaningful names.