Leonkin
Leonkin

Reputation: 11

Get Azure resource by id with Azure Python SDK

I'd like to get/check azure resource by ID

from azure.mgmt.resource import ResourceManagementClient
resource_client = ResourceManagementClient(credentials, subscription_id)
resource_client.resources.check_existence_by_id(
'/subscriptions/<any_subscr>/resourceGroups/random_group'
'/providers/Microsoft.Compute/virtualMachines/test_vm', 
api_version='2017-12-01')

fails with:

ClientRequestError: Error occurred in request., RetryError: HTTPSConnectionPool(host='management.azure.com', port=443): Max retries exceeded with url: /subscriptions/<any_subscr>/resourceGroups/random_group/providers/Microsoft.Compute/virtualMachines/test_vm?api-version=2017-12-01 (Caused by ResponseError('too many 503 error responses',))

api_version was taken from another error. If I try to run same command with api_version=resource_client.api_version and get:

CloudError: Azure Error: NoRegisteredProviderFound
Message: No registered resource provider found for location 'eastus2' and API version '2017-05-10' for type 'virtualMachines'. The supported api-versions are '2015-05-01-preview, 2015-06-15, 2016-03-30, 2016-04-30-preview, 2016-08-30, 2017-03-30, 2017-12-01'. The supported locations are 'eastus, eastus2, westus, centralus, northcentralus, southcentralus, northeurope, westeurope, eastasia, southeastasia, japaneast, japanwest, australiaeast, australiasoutheast, brazilsouth, southindia, centralindia, westindia, canadacentral, canadaeast, westus2, westcentralus, uksouth, ukwest, koreacentral, koreasouth'.

but .get_by_id() with same api_version works fine.

Is there something wrong with check_existence_by_id?

Upvotes: 1

Views: 2280

Answers (2)

Andrew Knighton
Andrew Knighton

Reputation: 31

from azure.mgmt.resource import ResourceManagementClient

# Acquire a credential object using CLI-based authentication.
credential = AzureCliCredential()

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)
resource_client.resources.get_by_id(resource_id,api_version='2019-08-01')

Took me a while to find it.

Upvotes: 1

Laurent Mazuel
Laurent Mazuel

Reputation: 3546

check_existence_by_id is a thin wrapper on the RestAPI, that more or less just provide authentication easy. The API version you need to provide is a indeed the one linked to the Resource Type you want (if your case Microsoft.Compute/virtualMachines).

You can get this information using the CLI and az provider list or the SDK with the providers attribute of your resource client.

Note for your remark about CLI not needing an ApiVersion, if you execute the command in --debug mode, you'll see that the CLI is indeed doing a az provider list under the hood after parsing the resource ID to get the correct ApiVersion to use.

(I work in the Azure SDK for Python team)

Upvotes: 1

Related Questions