Getting started with Azure and Terraform - Part 2

In this part of the series, I want to start creating my resource groups with Terraform. There are more ways to do this, but since I have been working with automation a bit, I know I want to start with a list of resource group names and make a loop through these.

The first step is to create a list of resource group names. I create a file called “variables.tf” a reserved name in Terraform that you can use to contain the variables you want to use in the automation. I first add the location as a variable since I will be using this value on just about all my resources in the automation. To add this, I can create a variable called “Location”, the type is a string, and the value is for me “WestEurope”. In code, this will look like my code here. To learn more about variables in Terraform, you can go to this site: Input Variables - Configuration Language - Terraform by HashiCorp

variable "Location" {
  type = string
  default = "WestEurope"
}

Next I will create a variable of the type “map”, which will contain my resource groups.

variable "ResourceGroups" {
  type    = map
  default = {
    "HubNetwork"          = "Terraform-Hub-Network"
    "HubCoreVMs"          = "Terraform-Hub-CoreVMs"
    "HubSharedServices"   = "Terraform-Hub-SharedServices" 
    "SpokeNetwork"        = "Terraform-Spoke-Network"
    "SpokeSharedServices" = "Terraform-Spoke-SharedServices"
    "SpokeCitrixCore"     = "Terraform-Spoke-Citrix-Core"
    "SpokeCitrixSilo1"    = "Terraform-Spoke-Citrix-Silo1"
  }
}

Now that I have my list, I need to create the code to loop through the list and create each resource group. I will create a new file called “resourcegroups.tf” and write my code in this file. The code itself simple, as you can see in the snippet below her. The code has a “for_each” command which I point to my map name in the variables file. This will create a handler called “each” which has a property of “value”.

resource "azurerm_resource_group" "resourcegroups" {
  for_each  = var.ResourceGroups
  name      = each.value
  location  = var.Location
}

When I use the “Terraform plan” command, it will loop through all .tf files in the folder and combine them into a single deployment. This provides you with the ability to create small files if this is something you are looking for. I have separated the backend from the resource groups, but moving forward, I am not sure how I will handle the number of files.

To create my terraform plan, I run the command “terraform plan -out resourecegroups.plan”. This will create the output as shown below.

I can now run the automation to create my resource groups in Azure. I do this with the command ’terraform apply “resourcegroup.plan”'.

In Azure, it looks like this.

Now I have my foundation created, and I can move on to the next part, network creation.

Comments