在azure中使用资源组标记删除资源组代码的Python代码

2024-09-29 02:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python代码删除其中的资源组和资源。 我在powershell中试过了,效果很好。现在我的组织需要Python语言。我试着写新的python代码,但我真的失败了。在

这是相同的powershell代码。有谁能帮忙用python编写代码吗。在

提前谢谢。在

 $rgs = Get-AzureRmResourceGroup; 

$rgs=Get-AzureRmResourceGroup-name“TestResourceGroupToClean1”

^{pr2}$

Tags: 代码name语言get资源效果powershellrgs
2条回答

Here is the Error I am getting ############################# Failed Traceback (most recent call last): File "C:\Temp\kukzwo13.tgf\9bd12580-5780-4109-abab-66e88fb4df87", line 59, in if not item.tags['ExpiryDate']:KeyError: 'ExpiryDate'

在python代码中,我们需要检查字典的键是否有效。我用python代码做了一个用标签删除资源组的演示。在

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
import datetime
from datetime import time

# Tenant ID for your Azure Subscription
TENANT_ID = 'tenant id '
# Your Service Principal App ID
CLIENT = 'client id'
# Your Service Principal Password
KEY = 'scret key'
subscription_id = 'subscrptionId'
credentials = ServicePrincipalCredentials(client_id=CLIENT, secret=KEY, tenant=TENANT_ID)
client = ResourceManagementClient(credentials, subscription_id)
groups = client.resource_groups.list()
null_variable = None
for item in groups:
    if item.tags != null_variable:
            if 'ExpiryDate' in item.tags:
                expiryDate = datetime.datetime.strptime(item.tags["ExpiryDate"],"%m/%d/%Y")
                timediff = expiryDate < datetime.datetime.today()
                if timediff:
                    print(item.tags["ExpiryDate"])
                    print(item.name)
                    client.resource_groups.delete(item.name)

相关问题 更多 >