【问题标题】:How to associate subnet to network security group in Azure using Python?如何使用 Python 将子网关联到 Azure 中的网络安全组?
【发布时间】:2020-11-30 03:26:42
【问题描述】:

我有 python 函数,它创建新的网络安全组:

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

如何将已经存在的子网关联到这个新创建的 NSG?是否可以修改此功能或我必须创建另一个?也许我应该在 python 中使用 Azure CLI?

在 Azure 门户上,通过this page 完成。

【问题讨论】:

    标签: python azure


    【解决方案1】:

    要将 NSG 关联到现有子网,据我所知,有三种方法。

    1. 我看到您使用 REST API 创建 NSG。所以你仍然可以使用 REST API 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. 您可以使用 Azure Python SDK 来完成:
    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)
    

    您可以获取有关subnets 的 SDK 的更多详细信息。

    1. Azure CLI 也可以,只需通过 python 代码运行 CLI 命令即可:
    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()
    

    您可以根据需要选择一种方式。并且在函数中添加代码或者再创建一个也可以。

    【讨论】:

    • @Hidan123 很高兴听到这个消息。好吧,如果它适合你,请接受它作为答案。
    • @Hidan123 当它对你有用时,你不接受它的原因是什么?
    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 2015-03-08
    • 2017-08-12
    • 2021-04-25
    • 2022-10-04
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多