从 C# 访问和管理 Azure 资源
Access and manage Azure resources from C#
我正在编写二进制 cmdlet 以将记录添加到 CosmosDb 集合。我需要用户登录到 Azure(用户凭据),我可以使用 PS 命令获取其余信息。
我可以在 Powershell 中使用 Get-AzCosmosDbAccount 执行此操作,前提是此人在 Azure 中具有查看资源的权限。
我找不到在 C# 代码中执行此操作的方法。我发现了几个非常接近但无法实际工作的示例。例如,我在适用于 .NET 的 Azure SDK 中找到 this example,但找不到对 Azure.ResourceManager.Resources
库的引用。
我找到了 this example,但它使用应用程序注册凭据进行身份验证,而不是用户凭据。我需要使用用户凭据。
我想这样做 PS 脚本,在 C# 中:
Login-AzAccount
Get-AzSubscription -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxx-cxxxxxxxxxxx | Select-AzSubscription
$cosmosKey = Get-AzCosmosDBAccountKey -ResourceGroupName 'rg-temp' -Name 'doctemp'
$cosmosKey.PrimaryMasterKey
可悲的是,这是我无法理解的Login-AzAccount
。
您需要的是 Microsoft.Azure.Cosmos
包。有了它,您可以使用 CosmosClient
class:
连接到 Cosmos DB
this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
可以看更详细的教程here。
关键是使用 new DefaultAzureCredential(true)
- true
还将启用用户凭据的交互式身份验证。您还可以查看 this document 以了解有关身份验证的一般信息。
以下示例使用 nuget 包 Azure.Identity 和
Azure.ResourceManager.CosmosDB。
后者目前仅作为预发布版本提供。您也可以尝试 Microsoft.Azure.Management.CosmosDB。
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new Azure.ResourceManager.CosmosDB.CosmosDBManagementClient(
subscriptionId, new DefaultAzureCredential(true));
var keys = client.DatabaseAccounts.ListKeys("resourcegroupName", "accountname");
如果需要切换到不同的租户,可以设置AZURE_TENANT_ID
环境变量。
我正在编写二进制 cmdlet 以将记录添加到 CosmosDb 集合。我需要用户登录到 Azure(用户凭据),我可以使用 PS 命令获取其余信息。 我可以在 Powershell 中使用 Get-AzCosmosDbAccount 执行此操作,前提是此人在 Azure 中具有查看资源的权限。
我找不到在 C# 代码中执行此操作的方法。我发现了几个非常接近但无法实际工作的示例。例如,我在适用于 .NET 的 Azure SDK 中找到 this example,但找不到对 Azure.ResourceManager.Resources
库的引用。
我找到了 this example,但它使用应用程序注册凭据进行身份验证,而不是用户凭据。我需要使用用户凭据。
我想这样做 PS 脚本,在 C# 中:
Login-AzAccount
Get-AzSubscription -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxx-cxxxxxxxxxxx | Select-AzSubscription
$cosmosKey = Get-AzCosmosDBAccountKey -ResourceGroupName 'rg-temp' -Name 'doctemp'
$cosmosKey.PrimaryMasterKey
可悲的是,这是我无法理解的Login-AzAccount
。
您需要的是 Microsoft.Azure.Cosmos
包。有了它,您可以使用 CosmosClient
class:
this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
可以看更详细的教程here。
关键是使用 new DefaultAzureCredential(true)
- true
还将启用用户凭据的交互式身份验证。您还可以查看 this document 以了解有关身份验证的一般信息。
以下示例使用 nuget 包 Azure.Identity 和 Azure.ResourceManager.CosmosDB。 后者目前仅作为预发布版本提供。您也可以尝试 Microsoft.Azure.Management.CosmosDB。
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new Azure.ResourceManager.CosmosDB.CosmosDBManagementClient(
subscriptionId, new DefaultAzureCredential(true));
var keys = client.DatabaseAccounts.ListKeys("resourcegroupName", "accountname");
如果需要切换到不同的租户,可以设置AZURE_TENANT_ID
环境变量。