简体   繁体   中英

I am authenticating to azure through python to list down all my virtual machines and I am getting this error

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)

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.

在此处输入图像描述

  • 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:

在此处输入图像描述


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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM