Get private IP addresses for VMs in a Scale Set via Python SDK (no public IP addresses in Scale Set)

huangapple go评论87阅读模式
英文:

Get private IP addresses for VMs in a Scale Set via Python SDK (no public IP addresses in Scale Set)

问题

我正在尝试获取规模集中所有虚拟机的私有IP地址列表(没有任何虚拟机故意具有公共IP地址)。我已经找到了如何使用az cli获取此信息的方法,如下所示:

az vmss nic list -g ResourceGroup --vmss-name ScaleSetName --query [].{ip:ipConfigurations[0].privateIpAddress} -o tsv

然而,我无法使用Python SDK获得相同的输出。我正在使用以下基本代码:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

credentials = ServicePrincipalCredentials(client_id=CLIENT, secret=KEY, tenant=TENANT)

compute_client = ComputeManagementClient(credentials, SUBSCRIPTION)

vmss = compute_client.virtual_machine_scale_sets.get(RG, SC)
print(vmss.virtual_machine_profile.network_profile.network_interface_configurations[0].ip_configurations[0])

这个SDK对象模型中的位置是否正确用于查找它们?从我的理解,网络属性应该在规模集级别,这是API中唯一看到与网络相关的地方。然而,在随后的属性中,我只看到了'private IP version',并且由于没有公共IP,这部分属性为空白。

英文:

I'm trying to get a list of private IP addresses for all VMs in a Scale Set (none of the VMs deliberately has any public IP addresses). I've found how to get this from az cli as follows:

az vmss nic list -g ResourceGroup --vmss-name ScaleSetName --query [].{ip:ipConfigurations[0].privateIpAddress} -o tsv

However I'm unable to get the same output using Python SDK. I am using the following basic code:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

credentials = ServicePrincipalCredentials(client_id = CLIENT, secret = KEY, tenant = TENANT)

compute_client = ComputeManagementClient(credentials, SUBSCRIPTION)

vmss = compute_client.virtual_machine_scale_sets.get(RG, SC)
print(vmss.virtual_machine_profile.network_profile.network_interface_configurations[0].ip_configurations[0])

Is this the right place in the SDK object model to look for them? From what I understand, the network properties should be at the Scale Set level, and that's the only place in the API where I see anything network-related. However, I only see 'private IP version' in the subsequent properties, and since there are no public IPs, that portion of the properties is blank.

答案1

得分: 3

抱歉,我怕你不能获取虚拟机规模集实例的私有IP。虚拟机规模集的网络接口不是 Azure 中的资源,无法直接获取。目前,Azure Python SDK 不支持通过 Python SDK 获取 VMSS 的私有IP。

你可以尝试使用 REST API 来实现这个目的,可以通过 CLI 命令调试获取 REST API,如下所示:

az vmss nic list -g ResourceGroup --vmss-name ScaleSetName --query [].{ip:ipConfigurations[0].privateIpAddress} -o tsv --debug

这将显示进度和 REST API。

英文:

Unfortunately, I'm afraid you cannot get the private IP of virtual machine scale set instances. The network interfaces of virtual machine scale sets are not the resources in Azure and you cannot get them. Currently, Azure python SDK does not support get the VMSS private IPs through the python SDK.

You can try to use the REST API to achieve the purpose and get the REST API via the CLI command debug like this:

az vmss nic list -g ResourceGroup --vmss-name ScaleSetName --query [].{ip:ipConfigurations[0].privateIpAddress} -o tsv --debug

It will show the progress and the REST API:

Get private IP addresses for VMs in a Scale Set via Python SDK (no public IP addresses in Scale Set)

答案2

得分: 3

如果您已经在使用Python Azure SDK,您可以从azure.identity凭据中提取Bearer令牌,这将使这个REST API调用变得更容易:

credentials = ClientSecretCredential(
    client_id=os.environ['AZURE_CLIENT_ID'],
    client_secret=os.environ['AZURE_CLIENT_SECRET'],
    tenant_id=os.environ['AZURE_TENANT_ID']
)  

# 从现有的Azure凭据中获取Bearer令牌,
# 并将其用于认证REST API调用:
rest_token = credentials._request_token('https://management.core.windows.net//.default')
vmss_nic_json = vmss_rest_api_list_nics(rest_token.token, subscription_id, resource_group, vmss_name)

# REST API调用:
def vmss_rest_api_list_nics(token, subscription_id, resource_group, vmss_name, api_version='2018-10-01'):
    
    url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/microsoft.Compute/virtualMachineScaleSets/{vmss_name}/networkInterfaces"
    params = {'api-version': api_version}
    request = requests.Request('GET', url, params=params)
    prepped = request.prepare()
    prepped.headers['Authorization'] = f'Bearer {token}'

    with requests.Session() as session:
        response = session.send(prepped )

        if( response.status_code == 200 ):
            return json.loads(response.text)
        else:
            logger.error(f"Failed to communicate with api service: HTTP {response.status_code} - {response.text}")
            return None

希望对您有所帮助。

英文:

If you're already using the Python azure sdk, you can pull the Bearer token from the azure.identity credential which makes this REST API call much easier to do:

credentials = ClientSecretCredential(
    client_id=os.environ['AZURE_CLIENT_ID'],
    client_secret=os.environ['AZURE_CLIENT_SECRET'],
    tenant_id=os.environ['AZURE_TENANT_ID']
)  

# Grab the bearer token from the existing azure credential,
# and use it to AUTH the REST api call:
rest_token = credentials._request_token('https://management.core.windows.net//.default')
vmss_nic_json = vmss_rest_api_list_nics(rest_token.token, subscription_id, resource_group, vmss_name)

# REST API call:
def vmss_rest_api_list_nics(token, subscription_id, resource_group, vmss_name, api_version='2018-10-01'):
    
    url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/microsoft.Compute/virtualMachineScaleSets/{vmss_name}/networkInterfaces"
    params = {'api-version': api_version}
    request = requests.Request('GET', url, params=params)
    prepped = request.prepare()
    prepped.headers['Authorization'] = f'Bearer {token}'

    with requests.Session() as session:
        response = session.send(prepped )

        if( response.status_code == 200 ):
            return json.loads(response.text)
        else:
            logger.error(f"Failed to communicate with api service: HTTP {response.status_code} - {response.text}")
            return None

huangapple
  • 本文由 发表于 2020年1月6日 21:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定