Tom Padilla
Tom Padilla

Reputation: 944

Access and manage Azure resources from C#

I am writing a binary cmdlet to add records to a CosmosDb collection. I need the user to login to Azure (user credentials) and I can use PS commands to get the rest of the info. I can do this in Powershell by using the Get-AzCosmosDbAccount given that the person has permissions in Azure to view the resource.

What I can't find is a way to do this in C# code. I have found several examples that come very close but fail to actually work. For example, I found this example in the Azure SDK for .NET but I can't find a reference to the Azure.ResourceManager.Resources library.

I found this example but it uses app registration credentials to authenticate not user credentials. I need to use user credentials.

I want to do this PS Script, in C#:

Login-AzAccount
Get-AzSubscription -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxx-cxxxxxxxxxxx | Select-AzSubscription
$cosmosKey = Get-AzCosmosDBAccountKey -ResourceGroupName 'rg-temp' -Name 'doctemp'
$cosmosKey.PrimaryMasterKey

Sadly, it's the Login-AzAccount that I can't understand.

Upvotes: 0

Views: 586

Answers (2)

Alex
Alex

Reputation: 18546

The key is to use new DefaultAzureCredential(true) - the true will also enable interactive authentication for user credentials. You can also look at this document for general information about authentication.

The following example uses nuget packages Azure.Identity and Azure.ResourceManager.CosmosDB. The latter is currently only available as a prerelease version. You could also try Microsoft.Azure.Management.CosmosDB instead.

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");

If you need to switch to a different tenant, you can set the AZURE_TENANT_ID environment variable.

Upvotes: 1

kamil-mrzyglod
kamil-mrzyglod

Reputation: 4998

What you need is a Microsoft.Azure.Cosmos package. With it you can connect to Cosmos DB using CosmosClient class:

this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);

You can see more detailed tutorial here.

Upvotes: 0

Related Questions