Introduction
Welcome back to our Terraform on Azure series! In our previous article, we explored the fundamental concepts of Infrastructure as Code and how Terraform can streamline your Azure deployments. Now it’s time to build on that foundation by setting up your local development environment.
Before we can start deploying infrastructure with Terraform, we need to prepare our development environment with the necessary tools and configurations. Think of this as preparing your workshop before beginning construction—having the right tools arranged properly will make your building process much more efficient.
In this article, we’ll walk through the complete process of setting up your local Terraform environment for Azure development. We’ll cover everything from installing the required tools to configuring your Azure credentials. By the end of this guide, you’ll have a fully functional Terraform setup ready to deploy resources to Azure.
Why is a proper setup so important? A well-configured local environment will:
- Make your development process more efficient and reliable
- Help you avoid common configuration errors
- Allow you to follow best practices from the beginning
- Provide a consistent platform for learning and experimenting with Terraform
Let’s begin by ensuring you have everything you need to get started with Terraform on Azure.
Prerequisites
Before diving into Terraform setup, let’s ensure you have all the necessary components for your development environment.
System Requirements
Terraform has relatively modest system requirements:
-
Operating System: Terraform is cross-platform and runs on Windows, macOS, and Linux.
-
Processor: Any modern processor will suffice. Terraform isn’t particularly CPU-intensive for most operations.
-
Memory: At least 4GB of RAM is recommended, with 8GB or more providing a better experience when working with larger infrastructure projects.
-
Storage: You’ll need approximately 1GB of free disk space for Terraform and its associated tools. SSDs provide better performance, especially when working with state files.
-
Internet Connection: A stable internet connection is essential, as you’ll be downloading tools and communicating with Azure.
Software Prerequisites
Before proceeding, you should have:
-
A Text Editor or IDE: You’ll need a code editor for writing Terraform configurations. Visual Studio Code is highly recommended for its excellent Terraform support, but any text editor will work.
-
Git: While not strictly required for Terraform itself, Git is highly recommended for version control of your infrastructure code. If you don’t have it installed yet, this is a good time to set it up.
Azure Subscription
You’ll need an Azure subscription where your Terraform-managed resources will reside. If you don’t have one yet, you can sign up for a free Azure account at https://azure.microsoft.com/free/. This includes a free tier for many services and a $200 credit valid for 30 days, which is ideal for learning Terraform.
When using Azure resources, always be mindful of potential costs. We’ll discuss cost management strategies throughout this series to help you avoid unexpected charges.
Once you’ve confirmed all prerequisites, we’re ready to begin installing the tools needed for Terraform development on Azure.
Installing Azure CLI
Our first step is to install the Azure Command-Line Interface (Azure CLI), which will allow us to interact with Azure services directly from the command line.
What is Azure CLI?
Azure CLI is a command-line tool that provides a streamlined experience for managing Azure resources. It offers the same capabilities as the Azure portal but in a scriptable, automated form. For Terraform workflows, Azure CLI serves two key purposes:
- It helps authenticate your Terraform sessions with your Azure subscription
- It provides a way to query your Azure environment before and after Terraform operations
This makes Azure CLI an essential companion tool when working with Terraform on Azure.
If you would like to learn more about Azure CLI checkout my YouTube video below:
Installing Azure CLI
The installation process varies depending on your operating system. Let’s cover the main platforms:
Windows
- Download the Azure CLI installer from the official Microsoft page.
- Once downloaded, run the installer (azure-cli-*.msi file).
- Follow the installation prompts, accept the license agreement, and click Install.
- After installation completes, you may need to restart your command prompt or PowerShell to start using Azure CLI.
macOS
For macOS, we’ll use Homebrew to install Azure CLI. If you don’t have Homebrew installed, you can get it from brew.sh.
- Open your terminal.
- Run the following command:
1
brew update && brew install azure-cli
Linux
The installation process for Linux varies depending on your distribution. Here’s how to install on Ubuntu or Debian:
- Open your terminal.
- Modify your sources list:
1 2
curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.gpg > /dev/null echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
- Update repository information and install the azure-cli package:
1 2
sudo apt-get update sudo apt-get install azure-cli
For other Linux distributions, check out the official Azure CLI installation guide.
Verifying the Installation
Once you’ve installed Azure CLI, verify the installation:
- Open a new terminal or command prompt window.
- Type the following command:
1
az --version
- If the installation was successful, you should see the version number of Azure CLI and its dependent libraries.
Now that you have Azure CLI installed, we can move on to installing Terraform itself.
Installing Terraform
With Azure CLI set up, it’s time to install Terraform—the core tool we’ll use to define and deploy our infrastructure. Let’s go through the installation process for different operating systems.
Downloading and Installing Terraform
Windows
- Visit the official Terraform downloads page: https://www.terraform.io/downloads.html.
- Scroll down to find the version for Windows.
- Click the link to download the zip file containing the Terraform binary.
- Once the zip file is downloaded, extract its contents. You’ll find a single file named
terraform.exe
. - Choose a location on your computer to store the Terraform executable. A common location is
C:\terraform
. - Move the
terraform.exe
file to this location.
Adding Terraform to Your System PATH (Windows)
For Windows users, we need to add Terraform to the system PATH so you can run it from any location in the command prompt:
- Right-click on the Start button and select “System”.
- Click on “Advanced system settings” on the right.
- Click on “Environment Variables”.
- Under “System variables”, find and select “Path”, then click “Edit”.
- Click “New” and add the directory where you placed the
terraform.exe
file (e.g.,C:\terraform
). - Click “OK” to close each window.
macOS
The easiest way to install Terraform on macOS is by using Homebrew:
-
Open your terminal and run the following commands:
1 2
brew tap hashicorp/tap brew install hashicorp/tap/terraform
Ubuntu/Debian Linux
For Ubuntu/Debian Linux, you can install Terraform by adding the HashiCorp APT repository:
-
Add the HashiCorp GPG key:
1
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
-
Add the official HashiCorp Linux repository:
1
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
-
Update and install Terraform:
1
sudo apt update && sudo apt install terraform
Verifying the Installation
To verify that Terraform is installed correctly:
-
Open a new terminal or command prompt window.
-
Type the following command:
1
terraform --version
-
If Terraform is installed correctly, you should see the version number displayed.
Now that we have both Azure CLI and Terraform installed, let’s configure the connection between them so Terraform can manage your Azure resources.
Configuring Azure Credentials
With both Azure CLI and Terraform installed, we need to establish a secure connection between Terraform and your Azure subscription. This connection will allow Terraform to create, modify, and delete resources in your Azure environment.
Creating an Azure Service Principal
To allow Terraform to access your Azure subscription, we need to create a Service Principal. A Service Principal is an identity created for use with applications, hosted services, and automated tools like Terraform to access Azure resources. It’s essentially a security identity that Terraform will use to interact with Azure.
Here’s how to create one:
-
Open your terminal or command prompt.
-
Log in to your Azure account using Azure CLI:
1
az login
This will open a browser window where you can log in to your Azure account.
-
Once logged in, create the Service Principal:
1
az ad sp create-for-rbac --name "Terraform" --role Contributor --scopes /subscriptions/YOUR_SUBSCRIPTION_ID
Replace
YOUR_SUBSCRIPTION_ID
with your actual Azure subscription ID. You can find this by runningaz account show --query id --output tsv
. -
This command will output something like this:
1 2 3 4 5 6
{ "appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "displayName": "Terraform", "password": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }
Important: Keep this information secure. These are your credentials, and you’ll need them in the next step.
Setting up Authentication for Terraform
Now that we have our Service Principal, we need to tell Terraform how to use it. There are several ways to do this, but using environment variables is recommended for this guide as it keeps sensitive information out of your Terraform code.
Set the following environment variables with the values from the Service Principal creation output:
For Windows (in Command Prompt):
|
|
For macOS and Linux:
|
|
Replace the placeholders (including < and >) with your actual values.
Security Tip: For production environments, consider storing these credentials in Azure Key Vault or your operating system’s secure credential storage.
Note About Environment Variables
It’s important to understand that the environment variables we just set will only persist for the current terminal session. If you close your terminal and open a new one, you’ll need to set these variables again. For a more permanent solution, you can:
- On Windows: Add them to your user environment variables through the System Properties dialog
- On macOS/Linux: Add the export commands to your shell profile file (like .bash_profile, .zshrc, etc.)
This ensures your Terraform authentication is available across all terminal sessions.
Now that you’ve set up authentication, let’s configure our code editor to make writing Terraform configurations more efficient.
Setting Up Your Code Editor
A good code editor can significantly enhance your Terraform development experience. While you can write Terraform configurations in any text editor, using one with Terraform-specific features will boost your productivity and help you avoid common errors.
Recommended Code Editor: Visual Studio Code
For this guide, we’ll focus on Visual Studio Code (VS Code). It’s free, open-source, and has excellent support for Terraform through extensions. If you prefer a different editor, many of these concepts can be applied to other editors as well.
Installing Visual Studio Code
- Visit the Visual Studio Code website.
- Download the appropriate version for your operating system.
- Run the installer and follow the prompts.
Once installed, open VS Code to continue with the setup.
Installing Helpful Extensions for Terraform
VS Code becomes significantly more powerful for Terraform development with the right extensions. Here are the key extensions to install:
- HashiCorp Terraform
- This official extension provides syntax highlighting, autocompletion, and other Terraform-specific features.
- To install:
- Click on the Extensions icon in the VS Code sidebar (it looks like four small squares).
- Search for “HashiCorp Terraform”.
- Click “Install” next to the extension by HashiCorp.
As shown in the screenshot above, you’ll find the HashiCorp Terraform extension in the marketplace. Look for the official extension from HashiCorp with features like “Syntax highlighting and autocompletion for Terraform.”
- Azure Terraform
- This extension adds Azure-specific features for Terraform development.
- To install:
- Search for “Azure Terraform” in the Extensions marketplace.
- Click “Install” next to the extension by Microsoft.
The Azure Terraform extension, developed by Microsoft, provides specialized features for working with Azure resources in Terraform, including command support and resource graph visualization.
Configuring VS Code for Terraform
Once you have the extensions installed, let’s configure a few settings to optimize VS Code for Terraform development:
- Open VS Code settings (File > Preferences > Settings, or
Cmd + ,
on Mac, andCtrl + ,
on Windows & Linux). - Search for “terraform” in the settings search bar.
- Enable the following settings:
- “terraform.experimentalFeatures.validateOnSave”: true
- “terraform.experimentalFeatures.prefillRequiredFields”: true
Enabling the “validateOnSave” feature provides real-time feedback as you write your Terraform code. When you save a file, VS Code will automatically check for syntax errors and other issues, helping you catch problems early.
The “prefillRequiredFields” setting is incredibly helpful when you’re learning Terraform. When you start typing a resource block, VS Code will automatically suggest required fields, eliminating guesswork about what properties are necessary.
After enabling these settings, you may need to reload VS Code for them to take effect. Look for the “Reload VSCode window” notification at the bottom right and click “Reload” if prompted.
Creating Your First Terraform File
Now that your editor is set up, let’s create your first Terraform configuration file:
- In VS Code, go to File > New File.
- Save the file with a
.tf
extension (e.g.,main.tf
). - Start typing
terraform
in this file, and you should see autocompletion suggestions pop up, confirming that your Terraform extension is working correctly.
As shown in the screenshot above, when you type “terraform” you’ll see intelligent autocompletion suggestions. The extension recognizes Terraform syntax and provides context-aware suggestions, making it much easier to write correct configurations.
With your code editor now configured for Terraform development, we’re ready to create our first Terraform configuration file for Azure.
Creating Your First Terraform Configuration File
Now comes the moment where theory meets practice—creating your first Terraform configuration file. This file will define the infrastructure you want to deploy to Azure.
The Basic Structure of a Terraform File
Terraform configuration files typically have a .tf
extension. The most common name for the main configuration file is main.tf
, so let’s start with that.
- Open your code editor (VS Code, if you’re following along).
- Create a new file and save it as
main.tf
.
Configuring the Azure Provider
The first component we need to add to our Terraform configuration is the Azure provider. This tells Terraform that we want to work with Azure resources. Here’s how to configure it:
|
|
Let’s break this down:
-
The
terraform
block is a special configuration block that defines Terraform settings, including required providers that Terraform will use.- Inside this block,
required_providers
specifies which providers are necessary for this configuration. - The
azurerm
entry indicates we need the Azure Resource Manager provider. - The
source
attribute tells Terraform where to find this provider (from HashiCorp’s provider registry). - The
version
attribute with the~>
prefix means “use any version compatible with 4.22.0” - this helps ensure compatibility.
- Inside this block,
-
The
provider
block configures the specified provider.- The
features
block is required for the Azure provider, even if left empty. - This is where you would add specific provider configurations like authentication methods if not using environment variables.
- The
When Terraform runs, it will use these instructions to establish a connection to Azure using the credentials we configured earlier.
Adding Your First Resource
Now, let’s add a resource to our configuration. We’ll start with something simple—a resource group. Resource groups in Azure are containers that hold related resources for an Azure solution.
Add this to your main.tf
file:
|
|
Here’s what each part means:
resource
: This keyword tells Terraform you’re defining a resource."azurerm_resource_group"
: This is the resource type, specifying that you want to create an Azure resource group."example"
: This is a name for this resource within your Terraform configuration. It’s used to refer to this resource elsewhere in your Terraform files.- Inside the block, we define the properties of the resource:
name
: The name of the resource group in Azure.location
: The Azure region where the resource group will be created.
The Complete Configuration
Your complete main.tf
file should now look like this:
|
|
Notice in the screenshot how VS Code highlights Terraform syntax with different colors and recognizes the “azurerm” provider. The provider name is highlighted as a link, indicating that the extension understands this is a valid provider reference.
This simple configuration is sufficient to create a resource group in Azure using Terraform.
Understanding What We’ve Done
Let’s analyze what we’ve accomplished with this configuration:
- We’ve specified that we’re using the Azure provider.
- We’ve configured the provider with basic settings.
- We’ve defined a resource (a resource group) that we want Terraform to create in Azure.
When applied, this configuration will create a new resource group named “my-first-terraform-rg” in the East US region of Azure. This resource group can later contain other Azure resources that we define with Terraform.
In the next section, we’ll learn how to initialize our Terraform working directory and prepare to apply this configuration.
Initializing Your Terraform Working Directory
Now that we’ve written our first Terraform configuration, we need to initialize our working directory. Initialization is a crucial step in the Terraform workflow that prepares your environment for use.
Verifying the Configuration Works
Let’s make sure our configuration file and Azure credentials are working correctly:
-
First, save your
main.tf
file with the Azure provider configuration we created earlier. -
Open your terminal or command prompt.
-
Navigate to the directory containing your
main.tf
file. You can do this either by:- Using the
cd
command in your terminal (e.g.,cd path/to/your/directory
) - Opening a terminal directly in that folder from your file explorer (right-click in the folder and select “Open terminal” or similar option, depending on your operating system)
- Using the
Understanding Terraform Initialization
Initialization in Terraform serves several important purposes:
- It downloads and installs the required provider plugins (in our case, the Azure provider)
- It sets up the backend for storing Terraform state
- It downloads and installs modules (if any are used in the configuration)
Think of initialization as preparing your workspace with all the tools and resources needed to execute your Terraform plans.
The terraform init
Command
To initialize your Terraform working directory, run the following command in your terminal:
|
|
What Happens During Initialization
When you run terraform init
, Terraform performs several key actions:
-
Provider Installation: Terraform downloads and installs the Azure provider we specified in our configuration.
-
Backend Initialization: Terraform sets up the backend for storing state. By default, this is a local backend (a file on your computer), but it can be configured to use remote backends like Azure Storage.
-
Module Installation: If your configuration uses any modules, Terraform would download and cache them.
You should see output similar to this:
|
|
Troubleshooting Initialization
If you encounter any issues during initialization, Terraform typically provides helpful error messages. Common issues include:
- Network problems preventing provider download
- Insufficient permissions to create files in the working directory
- Incompatible provider versions
If you run into trouble, check your internet connection, file permissions, and provider version specifications.
Next Steps
Congratulations on setting up your local Terraform environment for Azure development! You’ve accomplished a significant milestone in your Infrastructure as Code journey. Let’s recap what we’ve covered and look at what’s coming next.
What We’ve Covered
In this guide, we’ve focused entirely on setting up your Terraform development environment:
- Installing Azure CLI and Terraform
- Setting up Azure credentials for Terraform
- Configuring a code editor (VS Code) for Terraform development
- Creating your first Terraform configuration file
- Initializing a Terraform working directory
- Exploring best practices for Terraform development
You may have noticed that we haven’t yet deployed any resources to Azure. This was intentional! A proper setup is crucial before we start actually creating cloud resources. Think of this article as preparing all your tools and materials before beginning construction.
Preview of the Next Article
In the next article, “Your First Terraform Project on Azure: Step-by-Step Guide,” we’ll take the environment we’ve just set up and put it to work. We’ll move beyond initialization to actually deploying resources using the critical terraform plan
and terraform apply
commands.
You’ll learn how to:
- Design a multi-resource Azure environment
- Implement dependencies between resources
- Validate your changes with
terraform plan
- Deploy your infrastructure with
terraform apply
- Verify your deployments in the Azure portal
- Make modifications to existing infrastructure
- Clean up resources with
terraform destroy
Wrapping Up
You’ve completed an essential first milestone on your Infrastructure as Code journey. The environment you’ve set up is the foundation for all the exciting work to follow. While you haven’t deployed infrastructure yet, you now have all the tools configured correctly to do so.
Remember that proper preparation is key to success with any technology. By taking the time to set up your environment correctly now, you’re ensuring a smoother experience when we start deploying resources in the next article.
We look forward to continuing this journey with you as we move from setup to actual deployment. Until then, make sure your environment is ready for action!