Terraform – Building Infrastructure

In this post, we will use the example configuration described here to build a resource group in Azure. An Azure resource group is used to logically group resources together, in a future post we will then deploy a virtual network, subnet, network security group and a Virtual machine under this resource group.

To build the infrastructure from a windows 10 computer, follow the instructions here to download and unzip the Terraform binary as well as here for setting the environment variable.

Create Configuration File
Copy the below code into a text editor such as notepad and save it as main.tf (pay attention to the .tf file extension) in C:\Terraform folder.

# Configure the Microsoft Azure Provider
provider "azurerm" {
      version = "~> 1.35"

# Create a resource group
resource "azurerm_resource_group" "rsg" {
     name     = "ResourceGroup"
     location = "eastus"

Install Azure CLI
For Terraform on a local computer to be able to provision the infrastructure on Azure from a command prompt, Azure CLI needs to be installed on the computer and then logged in

Azure CLI can be downloaded from the Microsoft website here, which gives instructions on installation and then logging in by running the az login command.

Terraform init
The first command run in a configuration is terraform init. This only needs to be run once and it downloads the plug-ins required for the configuration as well as creating a folder call .terraform.

To run terraform init open a command prompt and navigate to c:\terraform where we saved the main.tf file, then type in terraform init which produces the following output

Terraform Plan
Terraform gives the function to run the code in plan mode, this output what Terraform will do to the infrastructure, whether it will add, change or destroy.

Running terraform plan on our configuration shows that it will add (build) a resource group.

Terraform apply
After running a terraform plan, terraform apply is used to apply the changes in the configuration. If first also does a plan and then prompts to apply the change.

Terraform State
As we build, change or destroy infrastructure, Terraform writes the data into a file called terraform.tfstate. The state file is extremely important and is where it keeps track of all the managed resources. It is necessary to keep the state file for the lifetime of the resources and very often is saved in centralized security storage, like Azure blob storage.

In our example, the state file can be found in the C:\Terraform folder.

Leave a Reply