This is a follow-up on my work with logic for adding subnets in a preconfigured vNET. By using cidrsubnet the Terraform script successfully adds four subnets into the vNET. After the first run with apply command we have four subnets in the state file with the names db01, paas01, web01 and app01. When creating the next plan we give the parameters to create four new subnets with the names db02, paas02, web02 and app02. The problem arise when running apply for the second time. According to the state file the 01-subnets exists but after execution the existing subnets are removed and creating the new 02-subnets. That was not my intension. What am I doing wrong, is not this a typical Use Case?
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~>2.0"
}
}
}
provider "azurerm" {
features {}
}
variable subnet_size {
description = "input variable indicating the subnet size: (xsmall, small, medium, large)"
type = string
default = "small"
}
variable subnet_count {
description = "input variable indicating the existing number of subnets of size: (xsmall, small, medium, large)"
type = number
default = 0
}
variable appid {
description = "Number indicating the application identity: (01, 02 etc)"
type = string
default = "01"
}
variable subnet_allocation_map {
description = "Map of CIDR blocks to carve into subnets based on size"
type = map
default = {
xsmall = "100.121.0.0/20"
small = "100.121.144.0/20"
medium = "100.121.160.0/20"
large = "100.121.176.0/20"
}
}
variable "newbit_size" {
description = "Map the friendly name to our subnet bit mask"
type = map
default = {
xsmall = "9"
small = "8"
medium = "6"
large = "5"
}
}
variable "subnet_list" {
type = map
default = {
"web" = 0
"app" = 1
"db" = 2
"paas" = 3
}
}
locals {
subnets = tomap({
for k, n in var.subnet_list : "${k}${var.appid}" => n
})
}
resource "azurerm_resource_group" "rg" {
name = "rg-infra-external-prod"
location = "westeurope"
}
resource "azurerm_virtual_network" "vnet" {
name = "vnet-external-prod-01"
address_space = [lookup(var.subnet_allocation_map, var.subnet_size)]
location = "westeurope"
resource_group_name = azurerm_resource_group.rg.name
tags = {
"IaC" = "Terraform"
}
}
resource "azurerm_subnet" "subnets" {
for_each = local.subnets
name = "snet-${each.key}-${var.subnet_size}-external-prod"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = [cidrsubnet(lookup(var.subnet_allocation_map, var.subnet_size), lookup(var.newbit_size,var.subnet_size), each.value + var.subnet_count)]
}