Home > Net >  I am authenticating to azure through python to list down all my virtual machines and I am getting th
I am authenticating to azure through python to list down all my virtual machines and I am getting th

Time:12-17

I am getting this error when I try to list down all my vms on Azure through python

Code: AuthorizationFailed
Message: The client "XXXX" with object id "XXXX" does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/XXXXX or the scope is invalid. If access was recently granted, please refresh your credentials.

my code is below:

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential


Subscription_Id = "XXXX"
Tenant_Id = "XXXXX"
Client_Id = "XXXXX"
Secret = "XXXXX"

credential = ClientSecretCredential(
    client_id=Client_Id,
    client_secret=Secret,
    tenant_id=Tenant_Id
)

compute_client = ComputeManagementClient(credential, Subscription_Id)
vm_list = compute_client.virtual_machines.list_all()
pageobject1 = vm_list.by_page(continuation_token=None)
for page in pageobject1:
    for j in page:
        print(j)

CodePudding user response:

Instead of passing your app registration applicationId/objectId you need to pass the service principal/appregistration name when you are trying to assign a particular role like virtualmachinecontributor to your Service principal as show in below.

enter image description here

  • Post providing the required access to the service principal/appregistration you will be able to pull the list of virtual machines in your subscription. we have checked the above python in our local environment which is also working fine.

Here is sample output screenshot for reference:

enter image description here


Updated Answer To pull list of VM's using Resource Management Client:

from azure.mgmt.resource import ResourceManagementClient
from azure.identity import ClientSecretCredential


Subscription_Id = "<subId>"
Tenant_Id = "<tenantid>"
Client_Id = "<appId>"
Secret = "<clientSecret>"

credential = ClientSecretCredential(
    client_id=Client_Id,
    client_secret=Secret,
    tenant_id=Tenant_Id
)

resource_client=ResourceManagementClient(credential=credential,subscription_id=Subscription_Id)
resource_list=resource_client.resources.list()
for item in resource_list:
    if(item.type == 'Microsoft.Compute/virtualMachines'):
        print(item)
  • Related