Home > Mobile >  Get databases from SQL managed instance using azure-mgmt-sql
Get databases from SQL managed instance using azure-mgmt-sql

Time:01-14

I use the library azure-mgmt-sql to get all the SQL servers and databases with the following code:

resources = sql_client.servers.list_by_resource_group("myresourcegroup")
for r in resources:
    databases = sql_client.databases.list_by_server("myresourcegroup", r.name)
    for d in databases:
        print(d.name)

I also need to get the SQL managed instances and their databases. I found that using managed_instances instead of servers returns the SQL managed instances, but I didn't find a way to get the databases.

resources = sql_client.managed_instances.list_by_resource_group("myresourcegroup")
    for r in resources:
        databases = sql_client.databases.list_by_server("myresourcegroup", r.name)
        for d in databases: <- ERROR when accessing the iterator
            print(d.name)

The error I am getting is the following:

azure.core.exceptions.ResourceNotFoundError: (ParentResourceNotFound) Can not perform requested operation on nested resource. Parent resource 'mymanagedinstancename>' not found.

How I can get the databases from the sql managed instance?

CodePudding user response:

I tried in my environment and got below results:

Initially i tried the same code and got an same error:

Console:

enter image description here

From your code sql_client.databases.list_by_server("myresourcegroup", r.name) this you were used database.list_by_server.

I found that using managed_instances instead of servers returns the SQL managed instances, but I didn't find a way to get the databases.

If you need to get database using managed instance, you can use sql_client.managed_databases.list_by_instance method.

Code:

from azure.mgmt.sql import SqlManagementClient
from azure.identity import DefaultAzureCredential

credential=DefaultAzureCredential()
subscriptionid="<subscription ID >"
sql_client=SqlManagementClient(credential=credential,subscription_id=subscriptionid)
resources = sql_client.managed_instances.list_by_resource_group("<resource grp>")
for r in resources:
    databases=sql_client.managed_databases.list_by_instance("<resource grp>",r.name)
    for d in databases:
            print(d.name)

Console:

enter image description here

Reference:

azure.mgmt.sql.SqlManagementClient class | Microsoft Learn

  • Related