该错误表示您的客户端没有执行操作的权限,您需要将其添加为资源组/订阅中的 RBAC 角色。
但是,我可以通过 Azure 门户创建网络安全组,方法是单击“创建资源”或在资源组中添加新源。
在门户中,您使用的是在门户中登录的帐户,如果您使用的是代码here,它使用的是服务主体的凭据,它是不同的。
这是一个完整的示例作品,您可以按照以下步骤操作。
1.Register an application with Azure AD and create a service principal.
2.Get values for signing in 和create a new application secret。
3.导航到资源组或订阅 -> Access control (IAM) -> Add -> 将 AD App 的服务主体添加为 RBAC 角色,例如Contributor,详情关注this。
4.然后使用下面的代码。
from azure.identity import ClientSecretCredential
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.network.v2020_06_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2020_06_01.models import SecurityRule
tenant_id = "<tenant-id>"
client_id = "<client-id>"
client_secret = "<client-secret>"
subscription_id = "<subscription-id>"
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
network_client = NetworkManagementClient(credential, subscription_id)
resource_group_name = "<group-name>"
nsg_name = "testnsg"
nsg_params = NetworkSecurityGroup(id= "testnsg", location="UK South", tags={ "name" : "testnsg" })
nsg = network_client.network_security_groups.begin_create_or_update(resource_group_name, "testnsg", parameters=nsg_params)
print(nsg.result().as_dict())
5.签入门户:
更新:
如果要使用用户帐号,只需使用AzureCliCredential即可。
1.安装Azure CLI,然后在本地终端使用az login登录您的帐户,例如电源外壳。
2.登录后,修改如下代码并运行。
from azure.identity import ClientSecretCredential
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.network.v2020_06_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2020_06_01.models import SecurityRule
subscription_id = "<subscription-id>"
credential = AzureCliCredential()
network_client = NetworkManagementClient(credential, subscription_id)
resource_group_name = "<group-name>"
nsg_name = "testnsg"
nsg_params = NetworkSecurityGroup(id= "testnsg", location="UK South", tags={ "name" : "testnsg" })
nsg = network_client.network_security_groups.begin_create_or_update(resource_group_name, "testnsg", parameters=nsg_params)
print(nsg.result().as_dict())