Terraform to create azure subnet delegation for selected subnets using for_each

Viewed 2259

I want some help on creating delegation on selected azure subnets. My code is as per below details.

Variables defined in my variable file

variable “subnets” {
type = map(any)
}

My tfvar file contains below values

subnets = {
mlops-aue-snt-aks = [“10.255.232.0/24”]
mlops-aue-snt-stg = [“10.255.233.0/26”]
mlops-aue-snt-kv = [“10.255.233.128/27”]
AzureBastionSubnet = [“10.255.233.160/27”]
mlops-aue-snt-shd = [“10.255.234.0/25”]
mlops-aue-snt-db1 = [“10.255.235.0/26”]
mlops-aue-snt-db2 = [“10.255.235.64/26”]
mlops-aue-snt-aci = [“10.255.235.128/26”]
}

This is my code for subnet

resource “azurerm_subnet” “azr_subnet” {
for_each = var.subnets

name = each.key
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = each.value
enforce_private_link_endpoint_network_policies = true
}

All subnets are created with this and it is all fine but now I have a requirement to add service_delegation for mlops-aue-snt-db1 and mlops-aue-snt-db2 and different for other subnets. I am not sure how to achieve this with my existing code. I can’t separate out subnets from the code as it will force to delete existing ones and create new which is not recommended. I did read some posts about using dynamic block to make changes but not sure how to implement it for selective subnets as per my requirement.

Can anyone please suggest how to achieve this in terraform?

1 Answers

You can do this with dynamic blocks and the by changing your subnets a bit.

subnets = {
    mlops-aue-snt-aks = {
            cidr = [“10.255.232.0/24”]
            service_delegation = false
    }    
    # the rest in same format
    mlops-aue-snt-db1 = {
            cidr = [“10.255.235.0/26”]
            service_delegation = true
    }    
    mlops-aue-snt-db2 = {
            cidr = [“10.255.235.64/26”]
            service_delegation = true
    }
    # ...
}

then

resource "azurerm_subnet" "azr_subnet" {
    for_each = var.subnets

    name = each.key
    resource_group_name = azurerm_resource_group.rg.name
    virtual_network_name = azurerm_virtual_network.vnet.name
    address_prefixes = each.value.cidr
    enforce_private_link_endpoint_network_policies = true
    
    dynamic "delegation" {
        for_each = each.value.service_delegation == "true" ? [1] : []
        
        content {
            name = "delegation"

            service_delegation {
            name    = "Microsoft.ContainerInstance/containerGroups"
            actions = ["Microsoft.Network/virtualNetworks/subnets/join/action", "Microsoft.Network/virtualNetworks/subnets/prepareNetworkPolicies/action"]
            }        
        }
    
    }
}
Related