简体   繁体   中英

Get databases from SQL managed instance using azure-mgmt-sql

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?

I tried in my environment and got below results:

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

Console:

在此处输入图像描述

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:

在此处输入图像描述

Reference:

azure.mgmt.sql.SqlManagementClient class | Microsoft Learn

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