Posts Getting started with Terraform for Azure
Post
Cancel

Getting started with Terraform for Azure

Terraform for Azure

Welcome to the first article in a series during which I will take you through my learning journey with Terraform and teach you how to use it effectively with Azure. By the end of this series, you’ll be well-prepared to pass the Terraform Associate (003) certification exam.

  1. Getting Started with Terraform on Azure (You are here)
  2. Transition from ARM Templates to Terraform with AI
  3. Terraform Configuration Essentials: File Types, State Management, and Provider Selection
  4. Writing Your First Azure Terraform Configuration
  5. Modules in Terraform (TBD)
  6. Advanced Terraform Techniques and Best Practices (TBD)
  7. Integrating Terraform with Azure DevOps (TBD)
  8. Terraform Associate Certification Study Guide and Tips (TBD)

As someone who has extensively worked with Azure, relying on PowerShell, ARM templates, and Bicep, I initially overlooked Terraform, focusing solely on Azure’s native solutions. However, the growing demand for multi-cloud capabilities and the universal applicability of Terraform have made it an essential tool in my toolkit.

In this article, we’ll dive into the basics of Terraform and set up an environment ready for use with Azure.

Why Terraform?

Terraform, an open-source tool by HashiCorp, is a popular choice for infrastructure as code (IaC). It offers a uniform language and workflow for managing infrastructure across multiple cloud providers, SaaS, and on-premises environments.

Setting Up Your Environment

Before diving into Terraform, we need to set up our environment. This involves installing Terraform, the Azure Command Line Interface (CLI), and a code editor like Visual Studio Code (VS Code).

Installing Terraform

Option 1: Downloading the Executable

  1. Download the Terraform executable from the HashiCorp website.

Optional steps:

  1. Create a folder on your C drive named Terraform.
  2. Extract the downloaded file to the C:\Terraform directory.
  3. Add the C:\Terraform directory to your system’s PATH environment variable.
  4. Verify the installation by opening a command prompt and typing terraform version.

Option 2: Using a Package Manager

  • Windows (winget): Open a command prompt and run winget install HashiCorp.Terraform.

  • macOS (Homebrew): Open a terminal and run brew install terraform.

Installing Azure CLI

Option 1: Downloading the Installer

  1. Download the Azure CLI from the Azure CLI download page.
  2. Run the installer and follow the prompts to complete the installation.
  3. Verify the installation by opening a new command prompt and typing az version.

Option 2: Using a Package Manager

  • Windows (winget): Open a command prompt and run winget install Microsoft.AzureCLI.
  • macOS (Homebrew): Open a terminal and run brew install azure-cli.

Setting Up Visual Studio Code

VS Code is a popular, free code editor that works well with Terraform.

Option 1: Downloading the Installer

  1. Download and install VS Code from the VS Code download page.
  2. Open VS Code and install the following extensions:
    • Azure CLI Tools
    • Terraform (by HashiCorp)
  3. Verify the setup by opening a new terminal in VS Code and typing terraform version and az version.

Option 2: Using a Package Manager

  • Windows (winget): Open a command prompt and run winget install Microsoft.VisualStudioCode.
  • macOS (Homebrew): Open a terminal and run brew install --cask visual-studio-code.

Authenticating the Azure CLI for Terraform

Before running any Terraform commands to manage Azure resources, you need to authenticate the Azure Command Line Interface (CLI) with your Azure account. This allows Terraform to interact with Azure and manage your infrastructure.

Here are the steps to authenticate the Azure CLI:

  1. In VS Code, or Command Prompot or Terminal, type az login command to authenticate your CLI session with Azure. This will open a web browser where you can enter your Azure credentials.

    1
    
    az login
    

    After successfully logging in, the CLI will display your subscription information.

  2. If you have multiple Azure subscriptions, you can specify which one to use for your Terraform deployments. Use the az account set command with the subscription ID or name.

    1
    
    az account set --subscription "Your Subscription Name or ID"
    
  3. To confirm that the Azure CLI is properly authenticated, you can use the az account show command. This will display details about the currently logged-in account.

    1
    
    az account show
    

Once the Azure CLI is authenticated, you can proceed to use Terraform commands to manage your Azure resources.

Using Service Principal for Automation

For automated workflows or continuous integration/continuous deployment (CI/CD) pipelines, it’s recommended to use a service principal for authentication. A service principal is a type of Azure Active Directory (AAD) application that provides a non-interactive way to authenticate and authorize applications.

To create and use a service principal with Terraform:

  1. Use the az ad sp create-for-rbac command to create a new service principal. This will output the credentials needed for Terraform.

    1
    
    az ad sp create-for-rbac --name "TerraformSP" --role Contributor --scopes /subscriptions/YourSubscriptionID
    
  2. Set the following environment variables with the service principal’s credentials:

    • ARM_CLIENT_ID: The application (client) ID of the service principal.
    • ARM_CLIENT_SECRET: The client secret (password) of the service principal.
    • ARM_SUBSCRIPTION_ID: Your Azure subscription ID.
    • ARM_TENANT_ID: The tenant ID of your Azure Active Directory.
  3. With the environment variables set, Terraform can use the service principal to authenticate with Azure and manage resources.

Using a service principal is a secure and scalable way to authenticate Terraform in automated environments.

Using Terraform

Now that we have our environment configured, let’s dive deeper into using Terraform commands and organizing your Terraform project for a more efficient workflow.

Terraform commands

To execute Terraform deployments and manage your infrastructure, we need to use the following commands:

  • terraform init: Initializes a new or existing Terraform configuration by installing necessary plugins and setting up the backend for state management.

  • terraform plan: Creates an execution plan, showing what actions Terraform will take to change your infrastructure to match the configuration.

  • terraform apply: Applies the changes specified in the Terraform plan to reach the desired state of your infrastructure.

  • terraform destroy: Removes all resources defined in the Terraform configuration.

  • terraform fmt: Automatically formats your Terraform files to a canonical format and style.

  • terraform validate: Validates the syntax of your Terraform files.

It’s important to understand and use these commands effectively to manage your infrastructure as code.

Organizing Your Terraform Project

A well-organized Terraform project is crucial for maintainability and scalability. Here are some tips for organizing your Terraform project:

  • Use Modules: Break down your configuration into reusable modules for common infrastructure patterns.

  • Folder Structure: Organize your Terraform files into logical folders. For example:
    • modules/: Contains reusable modules.
    • environments/: Contains configurations for different environments (e.g., dev/, prod/).
    • main.tf: The main Terraform configuration file.
    • variables.tf: Defines variables used in your configuration.
    • outputs.tf: Defines outputs from your Terraform configuration.
  • Naming Conventions: Use clear and consistent naming conventions for your files, resources, and modules.

  • State Management: Use remote backends like Azure Blob Storage or AWS S3 to store your Terraform state file securely and enable collaboration.

Saving Your Terraform Configuration

When saving your Terraform configuration, consider the following:

  • Version Control: Use a version control system like Git to track changes to your Terraform files. This also enables collaboration among team members.

  • Sensitive Data: Avoid storing sensitive data like passwords or secret keys in your Terraform files. Use environment variables or a secrets manager instead.

  • .gitignore File: If you’re using Git, include a .gitignore file in your repository to exclude files that shouldn’t be tracked, such as:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    # Local .terraform directories
    **/.terraform/*
      
    # .tfstate files
    *.tfstate
    *.tfstate.*
      
    # Crash log files
    crash.log
      
    # Exclude all .tfvars files, which might contain sensitive data
    *.tfvars
    

By following these best practices, you can create a well-organized and maintainable Terraform project that is easy to manage and collaborate on.

Conclusion

You now have a fully configured environment ready for working with Terraform on Azure. In the next articles, we’ll dive deeper into writing and deploying Terraform configurations.

Also, make sure to check out my GitHub Terraform repo with some code samples to start with.

Thank you for reading and keep clouding around!

Vukasin Terzic

Updated Mar 22, 2024 2024-03-22T18:34:09+01:00
This post is licensed under CC BY 4.0