0
votes

I have python function, which creates new Network Security Group:

def createNetworkSecurityGroup(subscription, location, resourceGroupName, networkSecurityGroupName, headers):
    print(f'Creating networking security group {networkSecurityGroupName}...')
    # https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/createorupdate#examples

    url = f'https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}?api-version=2019-09-01'

    data ={
          "properties": {
            "securityRules": [
              {
                "name": "CustomInBound",
                "properties": {
                  "protocol": "*",
                  "sourceAddressPrefix": "*",
                  "destinationAddressPrefix": "*",
                  "access": "Allow",
                  "destinationPortRange": "*",
                  "sourcePortRange": "*",
                  "priority": 100,
                  "direction": "Inbound"
                }
              },
              {
                "name": "CustomOutBound",
                "properties": {
                  "protocol": "*",
                  "sourceAddressPrefix": "*",
                  "destinationAddressPrefix": "*",
                  "access": "Allow",
                  "destinationPortRange": "*",
                  "sourcePortRange": "*",
                  "priority": 100,
                  "direction": "Outbound"
                }
              },
                            
            ]
          },
          "location": location
        }
    
    success = False
    while not success:
        try:
            response = requests.put(url, headers=headers, data=str(data))
            responseData = response.json()
            if not responseData.get('id'):
                print(responseData)
                print(responseData.text)
                print(responseData.headers)
            else:
                networkSecurityGroupId = responseData['id']
                success = True
        except Exception as e:
            print(e)
    return networkSecurityGroupId

How can I associate the already existing subnet to this newly created NSG? Is it possible to modify this function or do I have to create another one? Maybe I should use Azure CLI but in python?

On Azure Portal, it is done via this page.

1

1 Answers

0
votes

To associate the NSG to an existing subnet, there are three ways to do it as I know.

  1. I see you use the REST API to create the NSG. So you can still use the REST API here to do it, and an example body here:
{
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "172.17.0.0/24"
      ]
    },
    "subnets": [
      {
        "name": "default",
        "properties": {
          "addressPrefix": "172.17.0.0/24",
          "networkSecurityGroup": {
            "id": "xxxxxx",
            "location": "eastasia"
            }
        }
      }
    ]
  },
  "location": "eastasia"
}
  1. You can use the Azure Python SDK to do it:
subscription_id = "xxxxxx"
credential = ServicePrincipalCredentials(
  client_id="xxxxx",
  secret="xxxxx",
  tenant="xxxxx"
)

network_client = NetworkManagementClient(credential, subscription_id)

resource_group_name = "xxxxx"
vnet_name = "xxxxx"
subnet_name = "xxxxx"
sunet_data = {
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "172.17.0.0/24"
      ]
    },
    "subnets": [
      {
        "name": "default",
        "properties": {
          "addressPrefix": "172.17.0.0/24",
          "networkSecurityGroup": {
            "id": networkSecurityGroupId ,
            "location": "eastasia"
            }
        }
      }
    ]
  },
  "location": "eastasia"
}

result = network_client.subnets.create_or_update(resource_group_name, vnet_name, subnet_name, subnet_data)

You can get more details about the SDK for subnets.

  1. The Azure CLI can also do it, you just need to run the CLI command via python code:
import subprocess

resource_group_name = "xxxxx"
vnet_name = "xxxxx"
subnet_name = "xxxxx"
cmd = f"az network vnet subnet update -g {resource_group_name} -n {subnet_name} --vnet-name {vnet_name} --network-security-group {networkSecurityGroupId} "

command = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
out, err = command.communicate()

You can choose one way as you want. And it's ok if you add the code in the function or create another one.