Search code examples
pythonazureazure-sdk

How to Specify Network Security Group When Creating NIC In Azure Python SDK


Right now, I am creating a NIC to be used by a VM on Azure but I need the VM to allow port 80. To do so, I need to use a network security group but I don't know how to specify that when I create the NIC for my VM. Here is my current code: nicParams = { 'location': LOCATION, 'ip_configurations': [{ 'name': VM_NAME + "-ipconfig", 'public_ip_address': publicIP, 'subnet': { 'id': subnetInfo.id } }], } nicCreationResult = network_client.network_interfaces.create_or_update(GROUP_NAME, VM_NAME + "-nic", nicParams)

What should I add into the nicParams to specify the network security group?


Solution

  • You need to get the ID of your NSG and reference it in your NIC parameters at the first level of the vNIC:

    nicParams = {
        'location': LOCATION,
        'ip_configurations': [{
            'name': VM_NAME + "-ipconfig",
            'public_ip_address': publicIP,
            'subnet': {
                'id': subnetInfo.id
            }
        }],
        'network_security_group': {
            'id': '<NSG-ID-HERE>'
        }
    }
    nicCreationResult = network_client.network_interfaces.create_or_update(GROUP_NAME, VM_NAME + "-nic", nicParams)
    

    If network_security_group doesn't work, try networkSecurityGroup.