You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure SDK添加入站规则?现有代码提示“超出范围”

解决Azure SDK添加入站安全规则的问题

你的代码报错是因为用错了方法——network_security_groups.begin_create_or_update是用来创建或更新**整个网络安全组(NSG)**的,不是单独添加单条规则。你直接传入规则参数,SDK会将其视为NSG的完整配置,自然会触发“超出范围”的参数错误。

正确的操作流程是先获取现有NSG的配置,在其中添加新规则后,再提交更新:

# 1. 获取目标网络安全组的现有配置
nsg = network_client.network_security_groups.get(resource_group_name, nsg_name)

# 2. 构造要添加的入站规则
new_inbound_rule = {
    "name": security_rule_name,
    "access": "Allow",
    "description": "New Test security rule",
    "destination_address_prefix": "*",
    "destination_port_range": str(port),  # 确保端口是字符串格式,比如"80"或"80-88"
    "direction": "Inbound",
    "priority": 400,  # 优先级必须在100-4096之间,且不能与现有规则重复
    "protocol": "Tcp",
    "source_address_prefix": ip,
    "source_port_range": str(port),
}

# 3. 将新规则添加到NSG的规则列表中
nsg.security_rules.append(new_inbound_rule)

# 4. 提交更新后的NSG配置
updated_nsg = network_client.network_security_groups.begin_create_or_update(
    resource_group_name,
    nsg_name,
    nsg
).result()

需要注意几个关键点:

  • 规则的priority必须在100到4096之间,且和NSG内已有规则的优先级不能重复,否则会报错
  • 端口参数要确保是字符串格式,不能直接传数字(比如port是整数的话要转成str(port))
  • 如果是要修改现有规则,直接找到nsg.security_rules中对应的规则对象替换即可,不用append

内容的提问来源于stack exchange,提问作者max246

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:22:15