Plan and apply your first Terraform
In this task you'll describe a resource in Terraform and create it.
Terraform reads .tf files that describe what should exist, compares them with what it created before (the state) and with reality, and shows a plan of changes. Apply carries it out.
The azurerm provider talks to Azure. Version 4 needs your subscription ID, from the ARM_SUBSCRIPTION_ID variable or the provider block.
Example. Fernhill Cloud's network is 40 lines of Terraform; a pull request shows the plan, a reviewer reads it, and the pipeline applies it.
Before you start
You need: Contributor on a subscription or resource group. Time: 20 minutes.
Where to look
- main.tf
- terraform init
- terraform plan
- terraform apply
Steps
- In an empty folder, write main.tf with the azurerm provider (~> 4.0) and one azurerm_resource_group.
- Run
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv), thenterraform init. - Run
terraform planand read it: + means create. - Run
terraform applyand type yes. Thenterraform destroyto clean up.
Commands
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
terraform init
terraform fmt
terraform validate
terraform plan -out tfplan
terraform apply tfplan
Watch out for
- Cost
- Terraform is free; you pay for what it creates.
- Security
- State can contain secrets: never commit it; keep it in a protected storage account.
- Common mistakes
- Applying without reading the plan, and running Terraform from laptops with local state.
Clean up
terraform destroy removes everything this configuration created.
Words to know
- Provider
- The plug-in for a platform, such as hashicorp/azurerm.
- Plan
- The list of changes Terraform would make.
- State
- Terraform's record of what it manages and their IDs.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On