azure - 如何从本地运行的 docker 容器访问 Azure Keyvault?
问题描述
我有一个包含 ASP.NET Core 应用程序的 docker 映像,该应用程序使用 Azure Key Vault 来访问连接字符串等内容。当我在本地运行映像时,出现此错误:
Unhandled Exception: Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/[guid]. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/[guid]. Exception Message: Tried to get token using Managed Service Identity. Unable to connect to the Managed Service Identity (MSI) endpoint. Please check that you are running on an Azure resource that has MSI setup.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/[guid]. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Environment variable LOCALAPPDATA not set.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/[guid]. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. /bin/bash: az: No such file or directory
据我了解,它首先尝试将访问令牌作为托管服务身份获取。由于它未在 Azure 云中运行,因此无法执行此操作并尝试通过 Visual Studio 连接服务获取它。由于这不会出现在 docker 映像上,因此它会尝试使用 Azure CLI,但这并未安装在 docker 映像上。
所以我需要将 Azure CLI 安装到 docker 映像中。鉴于 Dockerfile 的基本映像是 ,这是如何完成的FROM microsoft/dotnet:2.1-aspnetcore-runtime
?
这个基础镜像是 Alpine OS 镜像吗,所以我需要看看用 Alpine 安装 Azure CLI 吗?
假设我安装了 Azure CLI,有没有一种方法可以访问 Key vault,而无需在 Dockerfile 源代码中存储任何凭据或通过纯文本将它们传递给容器?
更一般地说,这里最好的方法是什么。
解决方案
我当前的解决方案是使用带有访问令牌的环境变量。
获取密钥并存储在环境变量中(在您执行 az login 并设置正确的订阅之后):
$Env:ACCESS_TOKEN=(az account get-access-token --resource=https://vault.azure.net | ConvertFrom-Json).accessToken
将代码更改为:
config.AddEnvironmentVariables();
KeyVaultClient keyVaultClient;
var accessToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN");
if (accessToken != null)
{
keyVaultClient = new KeyVaultClient(
async (string a, string r, string s) => accessToken);
}
else
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
}
config.AddAzureKeyVault(
$"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
keyVaultClient,
new DefaultKeyVaultSecretManager());
推荐阅读
- c# - 如何从布局中的部分视图中获取实际视图的 URL
- azure-active-directory - 通过 Azure AD 进行本地网络共享访问
- android - ScrollView 剪切 TextView 中的最后一行
- amazon-web-services - AWS:是否可以使用 Step Functions 来调用 LEX
- bash - 如何隐藏来自 dbus-send(打印回复)的响应?
- java - 在 Java Spring MVC 中记录错误
- matlab - 在matlab中通过反复试验求解方程
- python-3.x - 重复字母的计数,计数后跟字母
- android - 包含布局的逻辑
- mysql - MySql查询NodeJS的订单占位符