定期删除 Azure 订阅中的资源组
Recurrent deletion of Resource Groups in an Azure Subscription
每周清理(测试)Azure 订阅的最佳方案是什么?完全删除资源组。
可能是 DevOPS、LogicApps、PowerShell 或其他?
有例子吗?
谢谢!
对于这个要求,你可以 create an automation account in your azure。然后创建一个 运行book 并使用如下所示的 powershell 删除资源组:
$username = "{client id}"
$password = "{client secret}"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
Connect-AzAccount -Credential $Credential -Tenant '{tenant id}' -ServicePrincipal
$resourceGroups = Get-AzResourceGroup
Foreach($group in $resourceGroups)
{
Remove-AzResourceGroup $group.ResourceGroupName -Force
}
对于上面代码中的参数{client id}, {client secret}, {tenant id}
,你需要在你的AD中register an application。您可以在注册申请的“概述”页面中找到 client id
和 tenant id
。
然后单击“证书和密码”和“新客户端密码”。
然后你就可以把这三个参数放到你在运行书中的powershell代码中了。
在使用注册的应用程序(服务主体)连接到Azure并进行删除资源组操作之前,您需要为该服务主体分配权限。复制您注册的应用程序的名称并转到您的“订阅”并单击“访问控制(IAM)”,然后添加角色分配。
那么您至少需要为服务主体分配“贡献者”角色。
之后,您需要在您的自动化帐户中导入 az 命令的模块,然后您就可以 运行 powershell 运行book.
要安排运行图书,您可以在运行图书中点击“日程”-->“添加日程”添加您想要的日程。
=============================更新===== ======================
对于您的进一步要求,您可以先创建一个策略。
在策略编辑页面,您可以定义如下策略:
{
"mode": "All",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Resources/subscriptions/resourceGroups"
},
{
"field": "[concat('tags[', parameters('tagName'), ']')]",
"exists": "false"
}
]
},
"then": {
"effect": "modify",
"details": {
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
],
"operations": [
{
"operation": "add",
"field": "[concat('tags[', parameters('tagName'), ']')]",
"value": "[utcNow()]"
}
]
}
}
},
"parameters": {
"tagName": {
"type": "String",
"metadata": {
"displayName": "Tag Name",
"description": "Name of the tag, such as 'environment'"
},
"defaultValue": "CreatedTime"
}
}
}
然后 assign the policy 订阅。之后在创建资源组时,会生成一个CreatedTime
标签。
然后你需要修改你的powershell,检查资源组createdTime是否早于你想要的值。请参考下面的脚本,我在我这边测试了删除创建时间超过48小时的资源组。
$resourceGroups = Get-AzResourceGroup
$TimeOutHours=48
foreach($group in $resourceGroups)
{
$Tags = $group.Tags
if ($Tags -ne $null)
{
if ($Tags.ContainsKey("CreatedTime"))
{
$CreatedTimeInTags = $Tags['CreatedTime']
$CreatedTime=New-Object DateTime
if (![DateTime]::TryParse($CreatedTimeInTags,[ref] $CreatedTime))
{
if (![Datetime]::TryParseExact($CreatedTimeInTags, 'yyyy-MM-ddTHH:mm:ss.fffffffZ',$null,$null,[ref] $CreatedTime))
{
if(![Datetime]::TryParseExact($CreatedTimeInTags, 'MM/dd/yyyy HH:mm:ss',$null,$null, [ref]$CreatedTime))
{
Write-Output "Failed to recognize the datetime for $($group.ResourceGroupName). Skip it."
continue
}
}
}
if( $CreatedTime.Year -ne 1)
{
$hoursDiff=((get-date).ToUniversalTime() - $CreatedTime).TotalHours
if($hoursDiff -ge $TimeOutHours)
{
Write-Output "Removing resource:$($group.ResourceGroupName)"
Remove-AzResourceGroup $group.ResourceGroupName -Force
}
}
}
}
}
每周清理(测试)Azure 订阅的最佳方案是什么?完全删除资源组。
可能是 DevOPS、LogicApps、PowerShell 或其他?
有例子吗?
谢谢!
对于这个要求,你可以 create an automation account in your azure。然后创建一个 运行book 并使用如下所示的 powershell 删除资源组:
$username = "{client id}"
$password = "{client secret}"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
Connect-AzAccount -Credential $Credential -Tenant '{tenant id}' -ServicePrincipal
$resourceGroups = Get-AzResourceGroup
Foreach($group in $resourceGroups)
{
Remove-AzResourceGroup $group.ResourceGroupName -Force
}
对于上面代码中的参数{client id}, {client secret}, {tenant id}
,你需要在你的AD中register an application。您可以在注册申请的“概述”页面中找到 client id
和 tenant id
。
然后单击“证书和密码”和“新客户端密码”。
然后你就可以把这三个参数放到你在运行书中的powershell代码中了。
在使用注册的应用程序(服务主体)连接到Azure并进行删除资源组操作之前,您需要为该服务主体分配权限。复制您注册的应用程序的名称并转到您的“订阅”并单击“访问控制(IAM)”,然后添加角色分配。
那么您至少需要为服务主体分配“贡献者”角色。
之后,您需要在您的自动化帐户中导入 az 命令的模块,然后您就可以 运行 powershell 运行book.
要安排运行图书,您可以在运行图书中点击“日程”-->“添加日程”添加您想要的日程。
=============================更新===== ======================
对于您的进一步要求,您可以先创建一个策略。
在策略编辑页面,您可以定义如下策略:
{
"mode": "All",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Resources/subscriptions/resourceGroups"
},
{
"field": "[concat('tags[', parameters('tagName'), ']')]",
"exists": "false"
}
]
},
"then": {
"effect": "modify",
"details": {
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
],
"operations": [
{
"operation": "add",
"field": "[concat('tags[', parameters('tagName'), ']')]",
"value": "[utcNow()]"
}
]
}
}
},
"parameters": {
"tagName": {
"type": "String",
"metadata": {
"displayName": "Tag Name",
"description": "Name of the tag, such as 'environment'"
},
"defaultValue": "CreatedTime"
}
}
}
然后 assign the policy 订阅。之后在创建资源组时,会生成一个CreatedTime
标签。
然后你需要修改你的powershell,检查资源组createdTime是否早于你想要的值。请参考下面的脚本,我在我这边测试了删除创建时间超过48小时的资源组。
$resourceGroups = Get-AzResourceGroup
$TimeOutHours=48
foreach($group in $resourceGroups)
{
$Tags = $group.Tags
if ($Tags -ne $null)
{
if ($Tags.ContainsKey("CreatedTime"))
{
$CreatedTimeInTags = $Tags['CreatedTime']
$CreatedTime=New-Object DateTime
if (![DateTime]::TryParse($CreatedTimeInTags,[ref] $CreatedTime))
{
if (![Datetime]::TryParseExact($CreatedTimeInTags, 'yyyy-MM-ddTHH:mm:ss.fffffffZ',$null,$null,[ref] $CreatedTime))
{
if(![Datetime]::TryParseExact($CreatedTimeInTags, 'MM/dd/yyyy HH:mm:ss',$null,$null, [ref]$CreatedTime))
{
Write-Output "Failed to recognize the datetime for $($group.ResourceGroupName). Skip it."
continue
}
}
}
if( $CreatedTime.Year -ne 1)
{
$hoursDiff=((get-date).ToUniversalTime() - $CreatedTime).TotalHours
if($hoursDiff -ge $TimeOutHours)
{
Write-Output "Removing resource:$($group.ResourceGroupName)"
Remove-AzResourceGroup $group.ResourceGroupName -Force
}
}
}
}
}