How to detach/dissociate public IP of VM through SDK

731 Views Asked by At

I am looking for a way to dissociate public IP addresses from my nic that is associated with a VM that is part of a scale set. There is ways to do it through the Azure portal and CLI (https://learn.microsoft.com/en-us/azure/virtual-network/remove-public-ip-address-vm). My question is that is there a way to do it through azure python or ruby SDK?

I have tried thenetwork_client.network_interfaces.create_or_update(GROUP_NAME, nic.name, nic_params) approach. However, I am not quite sure what to set for the nic_params field. Existing document indicate that the field is of the format:

        nic_params = {
            'location': LOCATION,
            'ip_configurations':[{
                'name': ipconfig_name,
                'public_ip_address':ip_address_object,
                'subnet': {
                    'id': subnet_info.id
                }
            }]
        }
I tried to set ip_configuration to null, public_ip_address to null. Neither approach worked.

2

There are 2 best solutions below

2
Alex AIT On

The basic idea is to simply set the public ip address to "null".

These links should help you:

I don't know python, but the code would probably start something like this:

from azure.mgmt.network import NetworkManagementClient

network_client = NetworkManagementClient(credentials, 'your-subscription-id')

network_client.network_interfaces.create_or_update(resource_group_name, network_interface_name,
{
'ip_configurations': ...
}
)
0
macrokernel On

I know it is a late reply, but it may be useful for someone who spent a substantial amount of time on this issue like I did. The key part is that a new interface object has to be constructed with ipconfig.public_ip_address set to None.

# Authenticate and connect to Azure cloud API
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
network_client = NetworkManagementClient(credential, subscription_id)

network_interface_id = "/some/azure/resource/id/foo/bar"
resource_group_name = network_interface_id.split("/")[4]
network_interface_name = network_interface_id.split("/")[-1]

# Get network interface object by its ID
interface = network_client.network_interfaces.get(
                resource_group_name=resource_group_name,
                network_interface_name=network_interface_name)

# Update public IP address in the Primary configuration of ip_configurations array
new_ip_configurations = []
for ipconfig in interface.ip_configurations:
    if ipconfig.primary:
        ipconfig.public_ip_address = None
    new_ip_configurations.append(ipconfig)
interface.ip_configurations = new_ip_configurations

result = network_client.network_interfaces.begin_create_or_update(
                resource_group_name=resource_group_name,
                network_interface_name=network_interface_name,
                parameters=interface
         ).result()