Introduction to Terraform
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It enables users to define and provision infrastructure resources across cloud providers using a declarative configuration language called HCL (HashiCorp Configuration Language).
What is Terraform?
Think of Terraform like a blueprint for your infrastructure.
๐๏ธ Real-world analogy: Imagine you’re building a house. You don’t start by randomly placing bricks. Instead, you start with an architectural plan. That plan details how many rooms, where the doors and windows go, what the plumbing layout looks like, and so on. Similarly, Terraform lets you define the โplanโ of your cloud infrastructure โ virtual machines, networks, databases โ all written in code.
Once this plan is in place, Terraform goes and builds the house โ your infrastructure โ exactly how itโs defined.
๐ง Sample Terraform Code for Azure Resource Group:
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "rg-demo"
location = "East US"
}
Why Terraform?
- โ Cloud Agnostic: Works with major cloud providers like Azure, AWS, GCP, and others.
- ๐งฑ Modular: Write reusable modules for consistency and reduced duplication.
- ๐ Idempotent: Re-applying the same configuration doesnโt create duplicate resources.
- ๐ก Dependency Management: Terraform understands dependencies between resources and builds/destroys them in the correct order.
- ๐ Plan & Apply Workflow: You can preview changes before applying them using
terraform plan, and apply them safely withterraform apply.
Core Concepts
1. Providers
Terraform interacts with different platforms via providers (e.g., AzureRM for Azure, AWS, Kubernetes, etc.).
2. Resources
Resources are the infrastructure components you want to manage โ like azurerm_virtual_machine, azurerm_storage_account, etc.
3. State
Terraform maintains a state file that tracks the actual infrastructure it manages. This helps it detect drift and reconcile future changes.
4. Modules
Modules let you group resources and reuse them like functions โ making your code cleaner and easier to manage.
Common Terraform Workflow
# 1. Initialize the working directory
terraform init
# 2. Preview the changes
terraform plan
# 3. Apply the changes
terraform apply
๐ก Whatโs Next?
Now that youโve got the basics, weโll explore real-world Terraform examples and how to structure your modules efficiently in Azure.