Lab description
In this lab we learn about locals
in Terraform.
Locals
Setup
Make sure you are in the correct folder:
1
cd ~/terraform-labs
1
cd ~/terraform-labs
If you were unable to complete the last lab, you can find a copy of the files in the solutions folder
1. Refactor main.tf to use locals
-
Make below changes to
main.tf
so we are no longer hardcoding values.Please avoid
copying and pasting
unless specified. Authoring terraform config files on your own is the best way to learn terraform and understand how it works.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "~> 4.0" } } } provider "azurerm" { features {} } locals { prefix = "contoso" region = "UK South" tags = { cost_center = "contoso research" } } resource "azurerm_resource_group" "contoso_rg" { name = "${local.prefix}_rg" location = local.region tags = local.tags } resource "azurerm_resource_group" "contoso_dev_rg" { name = "${local.prefix}_dev_rg" location = local.region tags = local.tags }
-
Run a
plan
andapply
as we’ve done before.
1
2
terraform plan -out "contoso.tfplan"
terraform apply "contoso.tfplan"
1
2
terraform plan -out "contoso.tfplan"
terraform apply "contoso.tfplan"
Your plan should add 2 resource groups.
Note: From now on, we will simply refer to these operations as
plan and apply
.
2. Verify
- Verify that resources have been created correctly as we’ve done before. (via azure portal or cli)
- Run a
terraform show
on the the state to ensure it’s correct and as expected.
3. Commit your changes to git
- Do a
git add .
andgit commit -m "added locals"
as before. Ensure that only themain.tf
file gets added. - Optionally, push it your remote if you have it setup.
4. Topics covered
Back to Lab Index