Terraform Azure Tutorial: How to Create Resource Groups, VNets, Subnets, NSGs, and VMs Step‑by‑Step IaC

6 min read

Terraform on Azure: Building a Real-World Infrastructure from Scratch.

Terraform is not just another automation tool. In modern Azure environments, it is a core operational skill used by cloud engineers, DevOps engineers, and platform teams to build, manage, and scale infrastructure safely.

This guide takes you beyond a simple lab. Instead of only showing what to deploy, it explains why each component exists, how Terraform interacts with Azure, and how this approach mirrors real production workflows.

If your goal is to work professionally with Azure and Infrastructure as Code, this is the foundation you must understand.

Why Terraform Matters for Azure Engineers

Infrastructure as Code (IaC) is the practice of defining infrastructure using machine-readable configuration files instead of manual steps in the Azure Portal.

In traditional environments, infrastructure is created by clicking through interfaces. This approach does not scale, is difficult to audit, and often leads to configuration drift. IaC solves this by allowing infrastructure to be:

  • Version-controlled

  • Peer-reviewed

  • Reproducible

  • Automated

Terraform is one of the most widely adopted IaC tools because it uses a declarative model. You describe the desired end state, and Terraform determines how to reach it.

Key characteristics that make Terraform valuable in Azure environments:

  • Cloud-agnostic: Terraform works across Azure, AWS, GCP, and more

  • Declarative syntax: You define what you want, not how to build it

  • State-aware: Terraform tracks deployed resources to prevent duplication or drift

In real Azure jobs, Terraform is commonly used to:

  • Provision identical infrastructure across dev, test, and production

  • Reduce manual errors

  • Detect and correct configuration drift

  • Enable safe automation through CI/CD pipelines

This lab is intentionally hands-on and explicit. There are no shortcuts, no portal clicks, and no hidden abstractions. The workflow mirrors how infrastructure is deployed in professional environments.

Sources

Understanding Terraform Before Writing Code

Before diving into configuration files, it’s important to understand how Terraform actually works.

Declarative vs Imperative Infrastructure

With Terraform, you do not write scripts that say “Create this resource, then that resource.”
Instead, you define the desired outcome, and Terraform computes the execution plan.

Terraform compares:

  • What exists in Azure

  • What exists in the Terraform state file

  • What is defined in your configuration

From this comparison, Terraform determines what must be created, updated, or destroyed.

Terraform State (Why It Matters)

Terraform stores resource metadata in a state file. This file allows Terraform to:

  • Track existing resources

  • Detect drift

  • Avoid recreating infrastructure unnecessarily

In production, state is usually stored remotely (for example, in Azure Storage). In this lab, local state is sufficient and aligns with beginner workflows.

Architecture Overview

Lab Overview: What We’re Building

In this lab, we build a complete Azure infrastructure stack using Terraform that reflects a realistic production layout.

Environment Components Explained

Each component exists for a specific operational reason:

  • Resource Group
    A logical container used to manage lifecycle, access control, and billing.

  • Virtual Network (VNet)
    Defines a private network boundary for Azure resources.

  • Subnet
    Segments the VNet to isolate workloads and apply network policies.

  • Network Security Group (NSG)
    Controls inbound and outbound traffic using security rules.

  • Network Interface (NIC)
    Connects the virtual machine to the subnet and NSG.

  • Windows Virtual Machine
    Represents the compute workload.

  • AzureRM Provider
    Enables Terraform to communicate with Azure Resource Manager APIs.

This structure aligns with Microsoft’s recommended Azure resource hierarchy and networking model.

Source

Prerequisites

Before starting, ensure the following are installed and configured:

  • An active Azure subscription

  • Visual Studio Code (for writing Terraform code)

  • Terraform CLI

  • Azure CLI

Terraform uses the Azure CLI for authentication when running locally. This is the recommended approach for development and learning environments.

After installing Azure CLI, authentication is handled via:

az login

Terraform then automatically uses the authenticated Azure context.

Sources

🎥 Video Walkthrough

 

Using Variables for Secure and Reusable Code

Hardcoding values directly into Terraform files is discouraged in real environments.

Instead, Terraform separates configuration logic from environment-specific values.

variables.tf

This file defines inputs such as:

  • Location

  • VM name

  • Admin username

  • VM size

Each variable includes a type and description, making the configuration self-documenting.

terraform.tfvars

This file stores actual values for a specific environment.
For example:

  • Development VM size

  • Region

  • Naming conventions

This separation allows the same Terraform codebase to be reused across multiple environments without modification.

Why Variables Matter in Production

Using variables helps to:

  • Improve security by avoiding hardcoded credentials

  • Enable reuse across environments

  • Simplify long-term maintenance

  • Support automation and CI/CD pipelines

This approach follows Terraform’s official best practices.

Source

Terraform Lifecycle Commands Explained

Terraform follows a clear and predictable lifecycle.

terraform init

Initializes the working directory and downloads required providers.

This step must be run before any other command.

terraform plan

Generates an execution plan showing exactly what Terraform will change.

This step is critical in production environments to prevent accidental changes.

terraform apply

Applies the planned changes and deploys infrastructure to Azure.

Terraform will prompt for confirmation unless auto-approved.

terraform destroy

Safely removes all resources managed by Terraform.

This ensures clean teardown without leaving orphaned resources.

These commands are intentionally designed to encourage safe and auditable infrastructure changes.

Source

How Terraform Interacts with Azure (Conceptual Flow)

Understanding the execution flow helps prevent confusion and errors:

  1. Terraform CLI reads configuration files

  2. Provider authenticates via Azure CLI

  3. Terraform queries Azure Resource Manager

  4. A plan is generated by comparing state and configuration

  5. Approved changes are applied

  6. State file is updated

This flow ensures Terraform always knows what exists and what it controls.

Common Troubleshooting Scenarios

Even simple labs surface real-world issues. Common problems include:

  • Authentication failures (Azure CLI not logged in)

  • Region-specific VM SKU availability

  • NSG rules blocking connectivity

  • Resource name conflicts

  • State file inconsistencies

When issues occur:

  • Always review terraform plan

  • Read error messages carefully

  • Avoid manually changing resources created by Terraform

Terraform errors are usually descriptive and actionable.

Introduction to Modularization (Best Practice)

As environments grow, a single main.tf file becomes difficult to manage.

In production, infrastructure is often split into modules:

  • Network module (VNet, subnets, NSGs)

  • Compute module (VMs)

  • Shared variables and outputs

Modules enable:

  • Reuse across projects

  • Cleaner code organization

  • Team collaboration

For learning purposes, a single configuration file is appropriate.
As complexity grows, modularization becomes essential.

Lab Validation and Cleanup

Validation

After deployment:

  • Verify resources in the Azure Portal

  • Confirm VM provisioning and networking

  • Validate NSG rule behavior

This confirms Terraform deployed infrastructure as expected.

Cleanup

Always destroy lab resources when finished to avoid unnecessary costs.

Terraform ensures that only resources it created are removed, protecting unrelated infrastructure.

Source

Final Thoughts

This guide demonstrates how real Azure infrastructure is built using Terraform, not just how to run commands.

Once you understand:

  • Declarative infrastructure

  • State management

  • Safe deployment workflows

You can confidently scale this knowledge into production, automation pipelines, and enterprise environments.


Discover more from Humble Cloud Tech

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners. View more
Cookies settings
Accept
Decline
Privacy & Cookie policy
Privacy & Cookies policy
Cookie name Active

Who we are

Suggested text: Our website address is: https://humbletech.cloud.

Comments

Suggested text: When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection. An anonymised string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service Privacy Policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.

Media

Suggested text: If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.

Cookies

Suggested text: If you leave a comment on our site you may opt in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year. If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser. When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select "Remember Me", your login will persist for two weeks. If you log out of your account, the login cookies will be removed. If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.

Embedded content from other websites

Suggested text: Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website. These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.

Who we share your data with

Suggested text: If you request a password reset, your IP address will be included in the reset email.

How long we retain your data

Suggested text: If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognise and approve any follow-up comments automatically instead of holding them in a moderation queue. For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.

What rights you have over your data

Suggested text: If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.

Where your data is sent

Suggested text: Visitor comments may be checked through an automated spam detection service.
Save settings
Scroll to Top