Sunday 28 May 2023

Dynamically Adding Virtual Network Rules to Azure Cognitive Account Using Terraform

 To enable access to various Azure resources via given virtual networks and subnets, we have to setup allowd subnets using virtual network rules in Azure resources. For example Azure Cognitive Account can be restricted to access only from given virtual networks and subnets. This requirement of allowed virtual networks and subnets may changed based on the deploying environment such as develop, qa or production. Let's look at how to write a terraform dynamic block to handle such scenarios, using Azure Cognitive Account virtual network rule as example, which can be used in other Azure resources as well.

Full sample code with  Azure Cognitive Account is available here in GitHub.

What We Want to Achive

If env is dev then two subnets should be added to the cognitive account allowed subnets. 

terraform apply -var='env=dev'



If env is not dev then only one subnet should be added to the cognitive account allowed subnets. 

terraform apply -var='env=prod'



The secret is to use the dynamic block in teraform as shown below.

    dynamic "virtual_network_rules" {
      for_each = var.env == "dev" ? [1] : []
      content {
        subnet_id = azurerm_subnet.aks_snet.id
      }
    }

The cognitive account source code as below. As you can see below vm subnet is added regardless of the deploying environment. However, the aks sbnet is only added when the deploying env is dev. For this example I have sued hardcoded name for cognitive account, but ideally it should be a name based on the env.

resource "azurerm_cognitive_account" "ca" {
  name                  = "cs-cognitive-test01"
  location              = azurerm_resource_group.rg.location
  resource_group_name   = azurerm_resource_group.rg.name
  kind                  = "TextTranslation"
  custom_subdomain_name = "cs-cognitive-test01"

  sku_name = "F0"

  network_acls {
    default_action = "Deny"

    virtual_network_rules {
      subnet_id = azurerm_subnet.vm_snet.id
    }

    dynamic "virtual_network_rules" {
      for_each = var.env == "dev" ? [1] : []
      content {
        subnet_id = azurerm_subnet.aks_snet.id
      }
    }
  }
}




No comments:

Popular Posts