![](/img/trans.png)
[英]How to Specify Network Security Group When Creating NIC In Azure Python SDK
[英]How to create Azure Network Security Group via Python SDK
我正在使用 Azure Python SDK 来部署 Azure VM。 我可以通过 Azure 门户毫无问题地使用网络安全组创建 VM。 但是,我无法使用以下 API 创建网络安全组:
async_nsg_create=network_client.network_security_groups.begin_create_or_update(
GROUP_NAME,
NSG_NAME,
nsg_parameters
)
它总是抱怨我“无权执行‘Microsoft.Network/networkSecurityGroups/write’操作”。 但是,我可以通过 Azure 门户通过单击“创建资源”或在资源组中添加新源来创建网络安全组。 我怀疑我可能必须通过 ResourceManagementClient 创建 NSG,但我在 API 文档中找不到任何有用的信息: https : //docs.microsoft.com/en-us/python/api/azure-mgmt-resource/azure。 mgmt.resource.resourcemanagementclient?view=azure-python#models-api-version--2020-06-01--
我检查了这个问题的解决方案: 在此处输入链接描述,但在步骤失败: resource_client.providers.register('Microsoft.Compute')
并且它抱怨:“没有授权执行操作'Microsoft.Compute/register/action '"
该错误表示您的客户端没有执行操作的权限,您需要将其添加为资源组/订阅中的 RBAC 角色。
但是,我可以通过 Azure 门户通过单击“创建资源”或在资源组中添加新源来创建网络安全组。
在门户中,您使用的是登录门户的帐户,如果您使用此处的代码,则它使用服务主体的凭据,这是不同的。
这是适合我的完整示例,您可以按照以下步骤操作。
2. 获取登录值并创建新的应用程序密钥。
3.Navigate到资源组或订阅- > Access control (IAM)
- > Add
- >的AD应用程序作为RBAC角色例如附加服务主要Contributor
,细节如下这样。
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 ,然后在本地终端(例如powershell)中使用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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.