如何将输出从分页容器转换为变量从资源组获取单个虚拟网络

时间:2019-05-08 05:12:28

标签: python azure azure-virtual-network

预先感谢,我在代码的顶部有变量LOCATION,VNET_NAME,SUBNET,SUBNETRANGE。我想从函数List_VNET的输出中填写此信息。使用此功能,我从天蓝色的资源组中获取虚拟网络(每个资源组只有一个虚拟网络)。然后想将其填充到变量中,但它会将输出作为分页容器提供。我主要在powershell上工作,因此我了解数组,我们可以使用array [0]获得实例。

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models


SUBSCRIPTION_ID = 'xxx'
GROUP_NAME = 'AQRG'
LOCATION = ''
VM_NAME = 'myVM'
VNET_NAME = ''
SUBNET_NAME = ''
SUBNETRANGE = ''


def List_VNET(network_client):
    result_create = network_client.virtual_networks.list(
            GROUP_NAME,
        )
    SUBNET_NAME = result_create


    return SUBNET_NAME

def get_credentials():
    credentials = ServicePrincipalCredentials(
        client_id = 'xxxx',
        secret = 'xxxx',
        tenant = 'xxxx'
    )

    return credentials


if __name__ == "__main__":
    credentials = get_credentials()

resource_group_client = ResourceManagementClient(
    credentials, 
    SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
    credentials, 
    SUBSCRIPTION_ID
)

creation_result = List_VNET(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

获得如下输出

<azure.mgmt.network.v2018_12_01.models.virtual_network_paged.VirtualNetworkPaged object at 0x0000023776C13908>

1 个答案:

答案 0 :(得分:1)

更新:在函数List_VNET中将VNET_NAME定义为全局变量:

   SUBSCRIPTION_ID = 'xxx'
   GROUP_NAME = 'AQRG'
   LOCATION = ''
   VM_NAME = 'myVM'
   VNET_NAME = ''
   SUBNET_NAME = ''
   SUBNETRANGE = ''


def List_VNET(network_client):
    result_create = network_client.virtual_networks.list(
            GROUP_NAME
        )
    global VNET_NAME
    for re in result_create:
        VNET_NAME=re.name

    return VNET_NAME

代码后:creation_result = List_VNET(network_client)

添加以下代码:

for re in creation_result:
    print(re.name)

然后您可以获得所有虚拟网络的名称。

enter image description here