Reputation: 691
I am trying to get all vm size name from my Azure account and I am using This approach In site when I click try out I am getting back result which I need.
Json look like:
{
"value": [
{
"name": "Standard_D1_v2",
"numberOfCores": 1,
"osDiskSizeInMB": 1047552,
"resourceDiskSizeInMB": 51200,
"memoryInMB": 3584,
"maxDataDiskCount": 4
},
{
"name": "Standard_D2_v2",
"numberOfCores": 2,
"osDiskSizeInMB": 1047552,
"resourceDiskSizeInMB": 102400,
"memoryInMB": 7168,
"maxDataDiskCount": 8
},
}
And after logged in microsoft gets token and request looks like:
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/North%20Europe/vmSizes?api-version=2019-12-01
Authorization: Bearer {{token.....}}
I need to get token for making request which I don't know, I have credentials like:
azure_client_id azure_client_secret azure_tenant_id azure_subscription_id
Using this credentials how can I achieve this json result, in short how can I get token.
Tried approaches:
This one Read this but no info investigated also this one also this question in stackoveflow
P.S. I am using aspnet core 3.1 web app maybe it is better client for azure. I used ComputeClient but no success. In final I thought using httpclient but first of all I need to test with postman.
Upvotes: 0
Views: 691
Reputation: 23111
If you want to manage Azure resource with a service principal, we need to assign Azure RABC role to the service principal, such as Contributor.
For example
az login
az account set --subscription "<your subscription id>"
az ad sp create-for-rbac -n "readMetric" --role "Virtual Machine Contributor"
POST /<your AD tenant domain>/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type =client_credentials
&client_id=<>
&client_secret=<>
&scope=https://management.azure.com/.default
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/eastus/vmSizes?api-version=2019-12-01
Authorization: Bearer {{token.....}}
Microsoft.Azure.Management.Compute.Fluent
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, // the sp appId
clientSecret, // the sp password
tenantId, // the sp tenant
AzureEnvironment.AzureGlobalCloud);
RestClient restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(credentials)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Build();
ComputeManagementClient client = new ComputeManagementClient(restClient);
client.SubscriptionId = subscriptionId;// the subscription you use
var vmSizes= await client.VirtualMachineSizes.ListAsync("eastus");
foreach (var vmSize in vmSizes) {
Console.WriteLine("The VM Size Name : "+ vmSize.Name);
}
Upvotes: 2