我正在尝试使用python代码删除其中的资源组和资源。 我已经在Powershell中尝试过了,效果很好。现在我的组织想要使用Python。我真的是python新手,尝试编写代码并失败了。
这是相同的Powershell代码。任何人都可以帮助获取python中的代码。
先谢谢了。
$rgs = Get-AzureRmResourceGroup;
#$ rgs = Get-AzureRmResourceGroup -name“ TestResourceGroupToClean1”;
if(!$rgs)
{
Write-Output "No resource groups in your subscription";
}
else{
Write-Output "You have $($(Get-AzureRmResourceGroup).Count) resource groups in your subscription";
foreach($resourceGroup in $rgs)
{
$name= $resourceGroup.ResourceGroupName;
if($resourceGroup.Tags.ExpiryDate)
{
try{
$ResourceGroupTagDate=[datetime]::ParseExact($resourceGroup.Tags.ExpiryDate,'MM/dd/yyyy',$null)
$count = (Get-AzureRmResource | where { $_.ResourceGroupName -match $name }).Count;
if($ResourceGroupTagDate.Date -lt $today.Date)
{
$subject="Automated Mail from Resource Group Cleaner"
$body="Resource Group $($resourceGroup.ResourceGroupName) including resources has been deleted"
Write-Output "The resource group $name has $count resources. Deleting it...";
Remove-AzureRmResourceGroup -Name $resourceGroup.ResourceGroupName -Force;
Write-Output "The resource group $name and $count resources. Deleted..";
Send-MailMessage -To 'XXXX@XXXXXXXX.com' -Subject $subject -Body $body -UseSsl -Port 587 -SmtpServer 'smtp.office365.com' -From $userid -Credential $creds
}
}
答案 0 :(得分:1)
这是我收到#############################失败的回溯失败(最近一次调用最近):“文件” C:\ Temp \ kukzwo13.tgf \ 9bd12580-5780-4109-abab-66e88fb4df87“,如果不是item.tags ['ExpiryDate']:KeyError:'ExpiryDate',则在第59行
在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)
答案 1 :(得分:0)