Posts Writing your first Azure Terraform Configuration
Post
Cancel

Writing your first Azure Terraform Configuration

First Terraform for Azure Configuration

Welcome back to the Terraform series on AzureIs.Fun! If you’ve been following along, you’ve already taken the first steps into the world of Infrastructure as Code (IaC) with Terraform. Now, in this fourth part, we’re diving deeper into the practical aspects of writing your first Terraform configuration.

Make sure you check the remainin articles in the series:

  1. Getting Started with Terraform on Azure
  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 (You are here)
  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)

In this article, we’ll guide you through writing your first Azure Terraform configuration. We’ll focus on practical examples, code, and best practices to help you get started with Terraform for Azure. By the end of this guide, you’ll be able to set up your environment, write Terraform code, and execute and destroy the resources in your Azure environment.

Setting Up Your Environment

Before you start writing Terraform configurations for Azure, you’ll need to set up your development environment. Ensure you have the following tools installed:

Terraform Azure CLI Visual Studio Code (optional, but recommended)

For more info on how to do that, check out the first article in this blog series.

Writing your Terraform code

Understanding Resource Blocks and Identifiers

In Terraform, resources are defined using resource blocks. Each resource block represents a single Azure resource that you want to manage. The syntax for a resource block is:

1
2
3
resource "<provider>_<resource_type>" "<resource_identifier>" {
  // Resource configuration goes here
}
  • Provider: Specifies the cloud or service provider for the resource (e.g., azurerm for Azure).

  • Resource Type: Specifies the type of resource you want to create (e.g., azurerm_resource_group for an Azure resource group).

  • Resource Identifier: An identifier for the resource block. It’s used to refer to this resource in other parts of your Terraform configuration.

Create your first Terraform Configuration

  1. Create a main.tf File: Start by creating a main.tf file in a new directory for your Terraform project. This file will contain your Terraform configuration code.

  2. Define the Azure Provider: Begin your main.tf file by defining the Azure provider. This tells Terraform that you want to use Azure as your cloud provider.

    1
    2
    3
    
    provider "azurerm" {
      features {}
    }
    

To learn more about Terraform Providers, check out the previous article in series or Terraform Registry.

  1. Add your resource definition:

Next, let’s define our first Azure Resource. In this example, we are going to create Azure Resource Group.

1
2
3
4
   resource "azurerm_resource_group" "example" {
     name     = "myResourceGroup"
     location = "West Europe"
   }
  • Resource Identifier: In this example, azurerm_resource_group is the resource type, and "example" is the resource identifier. The resource identifier is used to refer to this resource in other parts of your Terraform configuration.

  • Resource Name: "myResourceGroup" is the name of the resource group you want to create. You can choose any name you like, but it must be unique within your Azure subscription and follow Azure naming conventions.

  • Resource Location: "West Europe" is the location where the resource group will be created. Azure regions are geographical areas containing one or more datacenters.

Now, I’m sure you are wondering where to get the information about resource types and their definition. To get detailed information on Terraform’s syntax, configuration options, and best practices go to Azure Provider Documentation, and seaerch for desired resource type.

The Terraform Extension in VSCode and GitHub Copilot are also very useful tools and can help you get this information without leaving your command line.

Finally, check the format style and spacing of your definition file by running this command:

1
   terraform fmt

Using Variables in Your Terraform Configuration

Variables in Terraform allow you to parameterize your configurations, making them more dynamic and reusable. You can define variables to represent values that may vary between environments or to make your configurations more flexible. Let’s explore how to use variables in your Terraform configuration.

Defining Variables

You can define variables at the top of your main.tf file or in a separate .tf file. Here’s how you define a variable:

1
2
3
4
variable "resource_group_name" {
  type    = string
  default = "myResourceGroup"
}

In this example, we’re defining a variable named resource_group_name with a default value of "myResourceGroup" and a type of string. This variable will represent the name of the Azure resource group we want to create.

Using Variables in Resource Definitions

Once you’ve defined a variable, you can use it in your resource definitions. For example, to use the resource_group_name variable in the azurerm_resource_group resource:

1
2
3
4
resource "azurerm_resource_group" "example" {
  name     = var.resource_group_name
  location = "West Europe"
}

Here, var.resource_group_name refers to the value of the resource_group_name variable. This allows you to easily change the resource group name without modifying the resource definition.

Using Input Variables

In addition to defining variables directly in your configuration, you can also use input variables. Input variables allow you to provide variable values at runtime, either through command-line flags, environment variables, or a .tfvars file.

For example, you can create a variables.tfvars file with the following content:

1
2
resource_group_name = "myResourceGroup"
location = "West Europe"

Then, you can use these variables in your main.tf file like this:

1
2
3
4
resource "azurerm_resource_group" "example" {
  name     = var.resource_group_name
  location = var.location
}

To apply the values from the variables.tfvars file, you can run terraform apply with the -var-file flag:

1
terraform apply -var-file=variables.tfvars

Best Practices for Using Variables

  • Use Descriptive Names: Use descriptive names for your variables to make your configuration more readable.
  • Use Input Variables for Sensitive Information: For sensitive information, such as passwords or API keys, use input variables and provide the values securely at runtime.
  • Use Variables for Reusability: Use variables to parameterize your configurations and make them more reusable across different environments.

Creating your Resource

Now that you have your first file, we can move to provisioning your resource in Azure.

Authenticate the Azure CLI for Terraform

You need to authenticate Azure CLI with your Azure account. This allows Terraform to interact with Azure and manage your infrastructure.

1
2
3
   az login
   az account set --subscription "SubscriptionID"
   az account show

Initialize Terraform directory

Next, navigate your CLI to your work folder run the following command:

1
   terraform init

Terraform Plan

Before making any changes to your Azure resources, it’s a good practice to run terraform plan to preview the changes that Terraform will make. This command compares your Terraform configuration to the current state of your Azure environment and shows you what actions Terraform will take.

  1. Run terraform plan: In your terminal, navigate to the directory containing your Terraform configuration (main.tf) and run the following command:

    1
    
    terraform plan
    
  2. Review the Plan: Terraform will output a summary of the changes it will make, including any new resources it will create, any existing resources it will update, and any resources it will destroy. Take the time to review this plan to ensure it aligns with your expectations.

Terraform Apply

After reviewing the plan and ensuring it meets your requirements, you can apply the changes to your Azure environment using terraform apply.

  1. Run terraform apply: In your terminal, run the following command:

    1
    
    terraform apply
    
  2. Review Changes: Terraform will display the same plan as before and prompt you to confirm that you want to apply the changes. Type yes and press Enter to proceed.

  3. Wait for Execution: Terraform will now apply the changes to your Azure environment. This process may take some time, depending on the number of resources being created or updated.

  4. Verify Changes: Once Terraform has finished applying the changes, you can verify the changes in the Azure portal or using the Azure CLI to ensure that your resources have been created or updated as expected.

  5. Save State: Terraform will automatically save the state of your infrastructure in a state file (typically terraform.tfstate). Do not modify this file manually, as it is managed by Terraform and contains important information about your infrastructure.

And that’s it. Just like that you created your first Azure Resource with Terraform.

Best Practices for Execution

  • Review Plans Carefully: Always review the output of terraform plan before applying changes to your environment to avoid unexpected modifications.
  • Use -target for Specific Resources: If you only want to apply changes to specific resources, you can use the -target flag with terraform apply.
  • Use -auto-approve for Non-Interactive Runs: In automated or non-interactive environments, you can use the -auto-approve flag with terraform apply to automatically apply changes without requiring manual confirmation.

By following these steps, you can safely apply your Terraform configuration to your Azure environment and manage your infrastructure as code with confidence.

Cleaning Up Your Azure Resources

Terraform Destroy

Once you’re done with your Azure resources and want to clean up, you can use terraform destroy to remove all the resources created by your Terraform configuration. This command is useful for avoiding unnecessary costs and keeping your Azure environment tidy.

Use with Caution: Be sure you want to destroy the resources before running this command, as it cannot be undone.

  1. Run terraform destroy: In your terminal, navigate to the directory containing your Terraform configuration (main.tf) and run the following command:

    1
    
    terraform destroy
    
  2. Review the Plan: Terraform will display a plan showing all the resources it will destroy. Review this plan carefully to ensure you are deleting the correct resources.

  3. Confirm Destruction: Terraform will prompt you to confirm that you want to destroy the resources. Type yes and press Enter to proceed.



As you continue your Terraform journey, remember to always review your Terraform plans before applying changes to your environment and to use variables to make your configurations more dynamic and reusable. Terraform’s flexibility and power allow you to manage your infrastructure as code with ease, enabling you to automate and streamline your Azure deployments.

Stay tuned for more tips, tricks, and best practices for Terraform on Azure, and keep clouding around!


Vukasin Terzic

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