Home > Software engineering >  Reference two Azure subscriptions within the same terraform module block?
Reference two Azure subscriptions within the same terraform module block?

Time:06-02

I am currently using terraform to deploy azure resources and would like to point to a DDOS protection plan in a different subscription than the vnet is deployed to. The code is as follows:

resource "azurerm_virtual_network" "example" {
  for_each = var.virtual_networks

  name                = each.value.vnet_name
  location            = each.value.vnet_location
  resource_group_name = data.azurerm_resource_group.this[each.value.resource_group_key].name

  address_space = each.value.vnet_address_space
  tags          = each.value.vnet_tags

  ddos_protection_plan {
    id     = each.value.ddos_protection_plan_id
    enable = true
  }
}

I have referenced other subscriptions using azure provider for resources that the entire block will exist in a new subscription. https://samcogan.com/deploying-to-multiple-azure-subscriptions-with-terraform/

But running into trouble referencing another subscription for a (sub?)resource within a block.

TLDR: want to deploy VNET in one sub, reference ddos protection plan in another. is it possible?

CodePudding user response:

Yes you can deploy VNET in one sub, reference ddos protection plan in another sub. You are following the right document. Sorry I can not tested in my envirorment as i don't have another subscription.

To allow us to use another subscription, we are going to define a second AzureRM provider in the same file where you will creating a VNET.

provider "azurerm" {
  alias           = "core"
  subscription_id = "xxxx-xxxx-xxxx"
} 

After that you can use datasoruce for DDOS_Protection_Plan which you have created in another subscription like below

data "azurerm_network_ddos_protection_plan" "example" {
  provider            = "azurerm.core"
  name                = azurerm_network_ddos_protection_plan.example.name
  resource_group_name = azurerm_network_ddos_protection_plan.example.resource_group_name
}

and then rest your code will looks like this for referncing the Vnet with DDOS.

resource "azurerm_virtual_network" "example" {
  for_each = var.virtual_networks

  name                = each.value.vnet_name
  location            = each.value.vnet_location
  resource_group_name = data.azurerm_resource_group.this[each.value.resource_group_key].name

  address_space = each.value.vnet_address_space
  tags          = each.value.vnet_tags

  ddos_protection_plan {
    id     = data.azurerm_network_ddos_protection_plan.example.id
    enable = true
  }
}
  • Related