Как получить идентификатор / имя экземпляра с публичного IP-адреса виртуальной машины в Azure через Python SDK - PullRequest
0 голосов
/ 11 мая 2018
    def get_instance_id_from_pip(self, pip):
    subscription_id="69ff3a41-a66a-4d31-8c7d-9a1ef44595c3"
    compute_client = ComputeManagementClient(self.credentials, subscription_id)
    network_client = NetworkManagementClient(self.credentials, subscription_id)

    print("Get all public IP")
    for public_ip in network_client.public_ip_addresses.list_all():
        if public_ip.ip_address == pip:
            print(public_ip)

            # Get id
            pip_id= public_ip.id.split('/')
            print("pip id : {}".format(pip_id))
            rg_from_pip = pip_id[4].lower()
            print("RG : {}".format(rg_from_pip))
            pip_name = pip_id[-1]
            print("pip name : {}".format(pip_name))

    for vm in compute_client.virtual_machines.list_all():
        vm_id = vm.id.split('/')
        #print("vm ref id: {}".format(vm_id))
        rg_from_vm = vm_id[4].lower()
        if rg_from_pip == rg_from_vm:
            ## this is the VM in the same rg as pip
            for ni_reference in vm.network_profile.network_interfaces:
                ni_reference = ni_reference.id.split('/')
                ni_name = ni_reference[8]
                print("ni reference: {}".format(ni_reference))

                net_interface = network_client.network_interfaces.get(rg_from_pip, ni_name)
                print("net interface ref {}".format(net_interface))
                public_ip_reference = net_interface.ip_configurations[0].public_ip_address
                if public_ip_reference:
                    public_ip_reference = public_ip_reference.id.split('/')
                    ip_group = public_ip_reference[4]
                    ip_name = public_ip_reference[8]
                    print("IP group {}, IP name {}".format(ip_group, ip_name))

                    if ip_name == pip_name:
                        print("Thank god. Finallly !!!!")
                        print("VM ID :-> {}".format(vm.id))
                        return vm.id

У меня есть код выше, чтобы получить идентификатор экземпляра виртуальной машины из Public ip, но он не работает.Что действительно удивительно, так это то, что во всех случаях я получаю x.public_ip_address.ip_address в качестве значения None.

У меня было несколько ссылок readthedocs для Python SDK Azure.но некоторые, как все ссылки не работают.Хорошая работа Azure:)

Некоторые из них: https://azure -sdk-for-python.readthedocs.io / en / v1.0.3 / resourcemanagementcomputenetwork.html https://azure-storage.readthedocs.io/en/latest/ref/azure.storage.file.fileservice.html

Второе редактирование: я получил ответ на этот код, и приведенный выше код вернет vm id, если публичныйайпи адрес.Хотя, как видите, это не совсем оптимизированный ответ.Следовательно, лучшие ответы приветствуются.Спасибо!

1 Ответ

0 голосов
/ 11 мая 2018

Документы перенесены сюда: https://docs.microsoft.com/python/azure/

Мы сделали некоторое перенаправление, но, к сожалению, невозможно выполнить глобальное перенаправление на RTD, поэтому некоторые страницы 404: /

О вашей проблеме, Я бы попытался использовать группу операций publicip напрямую: https://docs.microsoft.com/en-us/python/api/azure.mgmt.network.v2017_11_01.operations.publicipaddressesoperations?view=azure-python

Вы получаете это в Network client, как client.public_ip_addresses

...