0
votes

I am trying to use Terraform and Terragrunt to create a bunch of different resources in Azure. Amongst others, I am deploying subscriptions and resource groups.

I have one central variable file that contains some metadata, and deploys resources based on that. I can deploy all the subscriptions that I want, but I have an issue because I want to deploy resource groups within those subscriptions, and I am not sure how to do it the best way, since the resource group resource doesn't have a subscription parameter.

Variable file looks something like:

inputs = {

    departments = [
    {
        name = "test",
        region = "West Europe"
        email = "[email protected]"

    },
    {
        name = "test2"
        region = "West Europe"
        email = "[email protected]"
    }
]

}

So in my resource group module I have defined it like this:

resource "azurerm_resource_group" "example" {
for_each = {for dep in var.departments: dep.name => dep}

  name     = "rg-${each.value.name}"
  location = "${each.value.region}"
}

And that is ok, but I need to switch context to the correct subscriptions, so the resource groups are being placed in the proper subs. Any ideas?

1
Any updates on this question? Does it solve your problem? Please let me know if you have any responses.Charles Xu

1 Answers

0
votes

To deploy resources in multiple subscriptions, you can use multiple providers, here you can get more details and the example code below:

provider "azurerm" {
    subscription_id = "xxxxxx"
    tenant_id = "xxxxxx"
    client_id = "xxxxxx"
    client_secret = "xxxxxx"
}

provider "azurerm" {
    alias = sub2
    subscription_id = "xxxxxx"
    tenant_id = "xxxxxx"
    client_id = "xxxxxx"
    client_secret = "xxxxxx"
}

resource "azurerm_resource_group" "example1" {
    provider = azurerm
    ...
}

resource "azurerm_resource_group" "example1" {
    provider = azurerm.sub2
    ...
}

And if you use the for_each in terraform, you can add the alias option in the input:

inputs = {

    departments = [
      {
        name = "test",
        provider = "azurerm"
        region = "West Europe"
        email = "[email protected]"

      },
      {
        name = "test2"
        provider = "azurerm.sub2"
        region = "West Europe"
        email = "[email protected]"
      }
    ]
}

This is just an example, but it's the workaround. You can change the code as you need.