dark

Use multiple Azure subscriptions in Terraform modules

blank
blank

Due to billing or organizational structures, certain parts of the infrastructure could be divided over several Azure subscriptions. From an infrastructure management point of view however, it might be interesting to manage the resources in those multiple subscriptions in one Terraform playbook.

In the required_providers section, the configuration_aliases must be configured first (usually in the main.tf file). This parameter must contain the same name (or names as the parameter takes a list of strings as input) as the alias parameter further below in the second provider section. Each provider section can have its own configuration parameters, such as for instance the subscription_id.

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "3.4.0"
      configuration_aliases = [ azurerm.other-sub ]
    }
}

provider "azurerm" {
  subscription_id = var.subscription_id
  features {}
}

provider "azurerm" {
  alias           = "other-sub"
  subscription_id = var.other_subscription_id
  features {}
}

When calling a module, each provider containing an alias and which is required in the module, must be specified in the providers parameter. The key is the name configured in the configuration_aliases in the required_providers section of the module (see below), the value is the name of the provider alias in the playbook.

module "diagnostic_sa_private_endpoint" {
  source = "../terraform_modules/private_endpoint/"
  providers = {
      azurerm.other-sub = azurerm.other-sub
  }

  for_each = { for snet in data.azurerm_subnet.subnets : snet.id => snet }
  ...
}

The module itself (in ../terraform_modules/private_endpoint/) however must again define the alias in a “required_providers” section. This means that a file must be include in the directory ../terraform_modules/private_endpoint which includes:

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      configuration_aliases = [ azurerm.other-sub ]
    }
  }
}

Finally, all Azure resources which require the other Azure subscription, must include a “provider” line similar as:

data "azurerm_private_dns_zone" "dns_zone" {
  provider            = azurerm.other-sub
  name                = var.private_dns_zone_name
}
1 comment
Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Previous Post
blank

Read the HAProxy UNIX socket file using Perl

Next Post
blank

Using multipath together with mdadm on Debian

Related Posts