【问题标题】:Recurrent deletion of Resource Groups in an Azure Subscription定期删除 Azure 订阅中的资源组
【发布时间】:2021-05-06 08:42:11
【问题描述】:

每周清理(测试)Azure 订阅的最佳方案是什么?完全删除资源组。

可以是 DevOPS、LogicApps、PowerShell 还是其他?

有例子吗?

谢谢!

【问题讨论】:

    标签: azure azure-devops azure-logic-apps azure-resource-manager


    【解决方案1】:

    对于这个要求,你可以在你的天蓝色中create an automation account。然后创建一个 Runbook 并使用如下所示的 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 idtenant id

    然后点击“Certificates & secret”和“New client secret”。

    然后你可以把这三个参数放到你的runbook中的powershell代码中。

    在使用注册的应用程序(服务主体)连接Azure并进行删除资源组操作之前,您需要为该服务主体分配权限。复制您注册应用的名称,进入您的“订阅”并点击“访问控制(IAM)”,然后添加角色分配。

    那么您至少需要为服务主体分配“贡献者”角色。

    之后,您需要在您的自动化账户中导入 az 命令的模块,然后您才能运行 powershell runbook。

    要计划 Runbook,您可以单击 Runbook 中的“计划”-->“添加计划”以添加所需的计划。

    ==============================更新========== ==================

    对于您的进一步要求,您可以先创建一个策略。

    在策略编辑页面,您可以定义如下策略:

    {
      "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
                    }
                }
               
            }
        }
        
    }
    

    【讨论】:

    • 太棒了,谢谢!如果我想从某个订阅中删除超过 1 周的 RG,该怎么办?
    • 嗨@DanielSotreanu 我明天会做一些测试并为您提供解决方案。
    • @DanielSotreanu 请参考我的答案更新。
    • 非常感谢@Hury Shen!你是最棒的!
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2020-01-24
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多