Course outlines for learning terraform.
There are a few location where you can set variables. Which location you choose depends a bit on the use case.
The variables can be overwritten, the ordering below. (Where the first item on the list is the weakest variable, overwritten by a variable lower in the list.
-var
).-var-file=
).*.auto.tfvars
.TF_VAR_variable
).variable "identifier" { default="value" }
).variable "identifier" { default="value" }
).You can set variables that are only usable in the (root) module. For example, you could take a regular variable, prefix or suffix and use the local variable.
# You can define a mandatory input variable.
variable "name" {}
# now you define the local variable.
locals {
default_name = "rg-${var.name}-sbx"
}
# Later you can reuse the local variable
resource "azurerm_resource_group" "rg" {
name = local.default_name
}
Tool | exposed | internal |
---|---|---|
Terraform | variable | local |
Ansible | defaults | vars |
Bicep | param | var |
You can define a map, and later lookup details from that map.
In variables.tf
you can define:
variable "sizes" {
default = {
small = "Standard_DS1_v2"
medium = "Standard_DS2_v2"
large = "Standard_DS3_v2"
}
}
In main.tf
you can looup the variable:
resource "azurerm_virtual_machine" "vm" {
vm_size = var.sizes["medium"]
# This is similar, but uses `lookup`:
# vm_size = lookup(var.sizes, "medium")
In the example above a value of (literally) “medium” is used. That can also be a vvariable:
variable "size" {
default = "medium"
}
resource "azurerm_virtual_machine" "vm" {
vm_size = var.sizes[size]