在 Azure 中,如果订阅中没有 IP 地址,则返回订阅中所有资源的 IP 地址,将返回 null。使用蟒蛇



当我尝试运行此代码时,它给我null作为每个资源的IP地址,不知道为什么。试图返回每个资源的IP地址,如果资源没有IP地址,也将返回null。

from ipaddress import ip_address
import logging
import json
import os
from azure.mgmt.resource import ResourceManagementClient

返回资源组中的资源。这是我需要返回IP地址的地方。

def process_r_instance(resource):
"""
Get the resources from a ResourceGroup instance.
"""
return {
"Name": resource.name,
"Type": resource.type,
"Location": resource.location,
"Tags": resource.tags,
"IP Address: ": resource.properties.ipAddress 
if resource.properties and resource.properties.ipAddress else None,



}

该函数返回订阅中的资源组。

def process_rg_instance(group):
"""
Get the relevant pieces of information from a ResourceGroup 
instance.
"""
return {
"Name": group.name,
"Id": group.id,
"Location": group.location,
"Type": group.type,
"Tags": group.tags,
"Properties: Provisioning State: ": group.properties.provisioning_state 
if group.properties and group.properties.provisioning_state else None,

}

该函数获取订阅ID传递的资源组列表,并返回该列表。

async def list_rgs(credentials, subscription_id):
"""
Get list of resource groups for the subscription id passed.
"""
list_of_resource_groups = []
with ResourceManagementClient(credentials, subscription_id) as 
rg_client:
try:
for i in rg_client.resource_groups.list():
list_of_resource_groups.append(process_rg_instance(i)),

for i in rg_client.resources.list():
list_of_resource_groups.append(process_r_instance(i)),

except Exception as e:
logging.error("encountered: {0}".format(str(e)))

return json.dumps(list_of_resource_groups)

变通方法之一,

要使用python返回IP地址,您可能需要在代码中使用regex模式来extract the ip address如下例:-

Example Of Code:-

pattern = re.compile(r'(d{1,3}.d{1,3}.d{1,3}.d{1,3})')

更多信息请参考SO THREAD|是否有python API可以获取Azure虚拟机的IP地址(内部或外部).

和获取IP地址从Azure函数Http请求与Python请参考这个SO线程变通办法

最新更新