多个订阅中的 Terraform 资源组部署

问题描述 投票:0回答:3

我正在尝试使用 Terraform 和 Terragrunt 在 Azure 中创建一堆不同的资源。 其中,我正在部署订阅和资源组。

我有一个包含一些元数据的中心变量文件,并基于该文件部署资源。 我可以部署我想要的所有订阅,但我有一个问题,因为我想在这些订阅中部署资源组,并且我不确定如何以最佳方式做到这一点,因为资源组资源没有订阅参数。

变量文件看起来像:

inputs = {

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

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

}

所以在我的资源组模块中我是这样定义的:

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

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

没关系,但我需要将上下文切换到正确的订阅,以便资源组被放置在正确的子目录中。 有什么想法吗?

terraform terraform-provider-azure
3个回答
1
投票

要在多个订阅中部署资源,您可以使用多个提供程序,在这里您可以获取更多详细信息和下面的示例代码:

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
    ...
}

如果你在terraform中使用for_each,你可以在输入中添加alias选项:

inputs = {

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

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

这只是一个示例,但它是解决方法。您可以根据需要更改代码。


0
投票

我希望下面的代码可以解决您的问题。 (这对我有用!)

main.tf


provider "azurerm" {
  features {}
}

data "azurerm_billing_mca_account_scope" "bl" {
  billing_account_name = var.billing_account
  billing_profile_name = var.billing_profile
  invoice_section_name = var.invoice_section
}

resource "azurerm_subscription" "subs" {
  subscription_name = "test-new"
  billing_scope_id  = data.azurerm_billing_mca_account_scope.bl.id
}

created Subscription
provider "azurerm" {
  alias           = "new_sub"
  subscription_id = azurerm_subscription.subs.subscription_id
  features {}
}

# Create a Resource Group in the newly created Subscription
resource "azurerm_resource_group" "example" {
  provider = azurerm.new_sub
  name     = "new-rg-in-new-sub"
  location = "eastus2"
}

注意:如果您在创建 rg 时遇到错误,请再次运行

az login
terraform apply
即可工作,az 有时不会自动获取新订阅。


0
投票

谢谢查尔斯。需要这个示例来弄清楚如何部署到多个订阅。 我已在 terraform.io 中设置的环境中设置了所有 evt 通过使用别名,我可以轻松覆盖 subscription_id 并为另一个订阅创建资源。

为什么我们需要这个? 我们在一个订阅中有三个测试环境,另一个订阅用于核心测试资源(大量网络)。 因此,当应用专用端点时,我想将 DNS 记录部署到核心子系统。通过使用上面的例子,我可以轻松地做到这一点,而不会有太多麻烦。

provider "azurerm" {
  alias = "core"
  subscription_id = "xxxxx"
  features {}
}

然后创建资源时使用provider参数即可 提供者= azurerm.core

© www.soinside.com 2019 - 2024. All rights reserved.