gpt4 book ai didi

azure - 如何使用服务托管标识通过 Terraform 在 Azure 中配置资源

转载 作者:行者123 更新时间:2023-12-02 06:25:57 24 4
gpt4 key购买 nike

我遇到了与托管身份相关的错误。我想在 Azure 中使用 Terraform 预配虚拟机。这是我的代码块:

terraform {
# Use a recent version of Terraform
required_version = ">= 0.13"

# Map providers to thier sources, required in Terraform 13+
required_providers {

# Azure Resource Manager 2.x
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.0"
}
}
}

provider "azurerm" {

features {}
use_msi = true
// subscription_id = "XXXXXXXXX-4663-4c2e-XXXX-XXXXXXXXX"
// tenant_id = "XXXXXXXXX-232r-3w2e-XXXX-XXXXXXXXX"
}

我尝试过同时启用 use_msi = true 以及稍后使用tenant_id 和subscription_id

它提示我以下错误:

Unable to list provider registration status, it is possible that this is due to invalid credentials or the service principal does not have permission to use the Resource Manager API, Azure error: azure.BearerAuthorizer#WithAuthorization: Failed to refresh the Token for request to https://management.azure.com/subscriptions//providers?api-version=2016-02-01: StatusCode=0 -- Original Error: the MSI endpoint is not available. Failed HTTP request to MSI endpoint: Get "http://177.xxx.232.324/metadata/identity/oauth2/token?api-version=2018-02-01": dial tcp 177.xxx.232.324:80: connectex: A socket operation was attempted to an unreachable network.

注意我已经设置了订阅

az account set --subscription="XXXXXXXXXXXXXXXXXX"

但是没有成功。

我应该在代码库中保留什么或者什么是正确的方法?

最佳答案

问题是,您仅在设置 use_msi = true 时告诉 Terraform 使用托管标识。我们需要在 managed identity support Azure services 上运行 terraform 工作区在 Azure 环境中。 MSI 在本地环境中不起作用,因为我们无法为其启用身份。

that document提到:

We recommend using a service principal or a managed identity whenrunning Terraform non-interactively (such as when running Terraform ina CI/CD pipeline), and authenticating using the Azure CLI when runningTerraform locally.

例如,假设您有一个启用了系统分配身份的 Azure VM。

enter image description here

分配对此身份的权限。

enter image description here

将 Terraform 配置为使用托管身份。请注意,将 use_msi 设置为 true 会告诉 Terraform 使用托管身份。然后,您可以使用此 MSI 向 Azure 进行身份验证以创建其他 Azure 资源。

RDP 连接到 Azure VM 并运行 Terraform 命令。以下示例代码使用系统分配的标识在我当前的订阅中创建一个资源组。

provider "azurerm" {

subscription_id = var.subscription_id
# client_id = var.client_id
# client_secret = var.client_secret
tenant_id = var.tenant_id

# skip_provider_registration = true

features {}

use_msi = true

}

terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
# version = "=2.46.0"
}

}
}

data "azurerm_subscription" "current" {}

resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West US"
}


output "current_subscription_display_name" {
value = data.azurerm_subscription.current.display_name
}

enter image description here

关于azure - 如何使用服务托管标识通过 Terraform 在 Azure 中配置资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66352724/

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