gpt4 book ai didi

azure - 在 azure pipeline 中运行 terraform 以部署到另一个租户

转载 作者:行者123 更新时间:2023-12-03 06:18:35 25 4
gpt4 key购买 nike

我使用 2 个 Azure 租户:

租户A用于存储存储库和管道

tenantB用于部署基础设施,terraform(后端)状态文件也存储在这里

因此,我从租户 A 获取存储库,使用 az login 连接到租户 B 并运行 terraform 命令。现在我想在租户A 中使用Azure 管道来自动化此过程。我在租户 A 中创建了连接到租户 B 的服务主体。验证成功,az login --service-principal -u "spn_id"-p "spn_secret"--tenant "tenantB_id" 也有效。但是,当我从tenantA运行管道时,或者当我使用az login登录到tenantA并运行terraform时,我收到错误:

错误:构建 ARM 配置时出错:从 Azure CLI 获取订阅(id):从 Azure CI 解析 json 结果:WAITING Azure CLI:退出状态 1:错误:找不到订阅“id”。检查拼写并重试。

我的 TF 代码:

terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
}
backend "azurerm" {
tenant_id = tenantB_id
subscription_id = tenantB_subscription_id
resource_group_name = resource_group_name
storage_account_name = storage_account_name
container_name = container_name
key = key_name
}
}
}

provider "azurerm" {
features {}
client_id = tenantA_service_principal_id
client_secret = tenantA_service_principal_secret
tenant_id = tenantB_id
subscription_id = tenantB_subscription_id
}

请注意,在tenantA中我没有订阅,只能使用az login --allow-no-subscriptions登录。

最佳答案

检查以下内容:

您需要进行az登录使用凭据登录并

为租户B设置订阅

az account set --subscription <desiredSubscriptionId>

enter image description here

您可以向 az login --allow-no-subscriptions 授予租户级别访问权限。

由于您使用服务主体向租户 B 进行身份验证,因此请确保服务主体在租户 B 中具有访问订阅所需的权限。为服务主体分配“贡献者”角色或更高级别的tenantB 订阅。

另外检查 Terraform 代码中的订阅 ID 是否正确。

如果没有正确提供订阅,您将面临订阅错误。

Status=404 Code="SubscriptionNotFound" Message="The subscription 'fx0' could not be found."xx

enter image description here

如果租户错误,您可能会遇到如下错误:构建 ARM 配置时出错:请确保您已安装 Azure CLI 版本

在这种情况下,运行以下命令来设置正确的租户,其中授予贡献者等适当的权限。

az login --tenant TENANT_ID

使用 terraform 的 Assin 贡献者角色。

resource "azurerm_role_assignment" "example" {
scope = "/subscriptions/${var.tenantB_subscription_id}"
role_definition_id = "/subscriptions/${var.tenantB_subscription_id}/providers/Microsoft.Authorization/roleDefinitions/${var.role_definition_id}" or // azurerm_role_definition.Contributor.id
principal_id = var.tenantA_service_principal_id
}

或者您可以通过 Azure cli 来完成

az role assignment create --assignee-object-id <ServiceprincipleObjectId> --assignee-principal-type ServicePrincipal --role Reader --scope /subscriptions/subscrptionIdoFtenantB/resourceGroups/MyResourceGroup --name <Idofrole>

enter image description here

然后尝试运行 terraform init> terraform planterraform apply

关于azure - 在 azure pipeline 中运行 terraform 以部署到另一个租户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76045971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com