Skip to content

Commit

Permalink
[Resources] Remove-AzResourceGroup - support parameter 'forceDeletion' (
Browse files Browse the repository at this point in the history
Azure#25819)

* Remove-AzResourceGroup  - support parameter 'forceDeletion'

* update changelog

* update logic in remove-azresourcegroup

* update unit test coverage

* Remove unnecessary updates
  • Loading branch information
lijinpei2008 authored Aug 16, 2024
1 parent 6ffb4c9 commit 0674f22
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Linq;
using System.Management.Automation;
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;

Expand Down Expand Up @@ -48,6 +49,9 @@ public class RemoveAzureResourceGroupCmdlet : ResourceManagerCmdletBaseWithApiVe
[ValidateNotNullOrEmpty]
public string Id { get; set; }

[Parameter(Mandatory = false, HelpMessage = "The resource types you want to force delete.Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachineScaleSets,Microsoft.Compute/virtualMachines,Microsoft.Databricks/workspaces")]
public string ForceDeletionType { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }

Expand All @@ -58,12 +62,24 @@ protected override void OnProcessRecord()
{
Name = Name ?? ResourceIdentifier.FromResourceGroupIdentifier(this.Id).ResourceGroupName;

ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemovingResourceGroup, Name),
ProjectResources.RemoveResourceGroupMessage,
Name,
() => ResourceManagerSdkClient.DeleteResourceGroup(Name));
if (string.IsNullOrWhiteSpace(ForceDeletionType))
{
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemovingResourceGroup, Name),
ProjectResources.RemoveResourceGroupMessage,
Name,
() => ResourceManagerSdkClient.DeleteResourceGroup(Name));
}
else
{
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemovingResourceGroup, Name),
ProjectResources.RemoveResourceGroupMessage,
Name,
() => NewResourceManagerSdkClient.DeleteResourceGroup(Name, ForceDeletionType));
}

WriteObject(true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ public DeploymentExtended ProvisionDeploymentStatus(PSDeploymentCmdletParameters

Action writeProgressAction = () => this.WriteDeploymentProgress(parameters, deployment, deploymentOperationError);

var deploymentExtended = this.WaitDeploymentStatus(
var deploymentExtended = this.WaitDeploymentStatus(
getDeploymentFunc,
writeProgressAction,
ProvisioningState.Canceled,
Expand All @@ -217,8 +217,8 @@ public DeploymentExtended ProvisionDeploymentStatus(PSDeploymentCmdletParameters

if (deploymentOperationError.ErrorMessages.Count > 0)
{
WriteError(GetDeploymentErrorMessagesWithOperationId(deploymentOperationError,
parameters.DeploymentName,
WriteError(GetDeploymentErrorMessagesWithOperationId(deploymentOperationError,
parameters.DeploymentName,
deploymentExtended?.Properties?.CorrelationId));
}

Expand Down Expand Up @@ -260,11 +260,11 @@ private void WriteDeploymentProgress(PSDeploymentCmdletParameters parameters, De
}
else
{
deploymentOperationError.ProcessError(operation);
deploymentOperationError.ProcessError(operation);
}
}
}

private DeploymentExtended WaitDeploymentStatus(
Func<Task<AzureOperationResponse<DeploymentExtended>>> getDeployment,
Action listDeploymentOperations,
Expand Down Expand Up @@ -680,7 +680,7 @@ private Dictionary<string, List<string>> ConvertAuxTenantDictionary(IDictionary<
{
if (auxTenants == null) return null;

var headers = new Dictionary<string, List<string>> ();
var headers = new Dictionary<string, List<string>>();
foreach (KeyValuePair<string, IList<string>> entry in auxTenants)
{
headers[entry.Key] = entry.Value.ToList();
Expand Down Expand Up @@ -950,6 +950,27 @@ public virtual void DeleteResourceGroup(string name)
}
}

/// <summary>
/// Deletes a given resource group
/// </summary>
/// <param name="name">The resource group name</param>
/// <param name="forceDeletionTypes">
/// The resource types you want to force delete. Currently, only the following
/// is supported:
/// forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets
/// </param>
public virtual void DeleteResourceGroup(string name, string forceDeletionTypes)
{
if (!ResourceManagementClient.ResourceGroups.CheckExistence(name))
{
WriteError(ProjectResources.ResourceGroupDoesntExists);
}
else
{
ResourceManagementClient.ResourceGroups.Delete(name, forceDeletionTypes);
}
}

/// <summary>
/// Filters the resource group deployments with provided options
/// </summary>
Expand Down Expand Up @@ -1691,7 +1712,8 @@ private void CancelDeploymentAtResourceGroup(List<PSDeployment> deployments, str
/// <returns>The validation errors if there's any, or empty list otherwise.</returns>
public virtual List<PSResourceManagerError> ValidateDeployment(PSDeploymentCmdletParameters parameters)
{
if (parameters.DeploymentName == null){
if (parameters.DeploymentName == null)
{
parameters.DeploymentName = GenerateDeploymentName(parameters);
}
Deployment deployment = CreateBasicDeployment(parameters, parameters.DeploymentMode, null);
Expand Down Expand Up @@ -1729,7 +1751,7 @@ public string GetDeploymentErrorMessagesWithOperationId(DeploymentOperationError
.AppendLine());

// Add correlationId
sb.AppendLine().AppendFormat(ProjectResources.DeploymentCorrelationId, correlationId);
sb.AppendLine().AppendFormat(ProjectResources.DeploymentCorrelationId, correlationId);

return sb.ToString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,26 @@ public class RemoveAzureResourceGroupCommandTests : RMTestBase

private Mock<ResourceManagerSdkClient> resourcesClientMock;

private Mock<NewResourceManagerSdkClient> newResourceClientMock;

private Mock<ICommandRuntime> commandRuntimeMock;

private string resourceGroupName = "myResourceGroup";
private string resourceGroupId = "/subscriptions/subId/resourceGroups/myResourceGroup";
private string resourceId = "/subscriptions/subId/resourceGroups/myResourceGroup/providers/myResourceProvider/resourceType/myResource";
private string resourceForceDeletionType = "Microsoft.Compute/virtualMachineScaleSets,Microsoft.Compute/virtualMachines,Microsoft.Databricks/workspaces";

public RemoveAzureResourceGroupCommandTests(ITestOutputHelper output)
{
resourcesClientMock = new Mock<ResourceManagerSdkClient>();
newResourceClientMock = new Mock<NewResourceManagerSdkClient>();
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
commandRuntimeMock = new Mock<ICommandRuntime>();
cmdlet = new RemoveAzureResourceGroupCmdlet()
{
CommandRuntime = commandRuntimeMock.Object,
ResourceManagerSdkClient = resourcesClientMock.Object
ResourceManagerSdkClient = resourcesClientMock.Object,
NewResourceManagerSdkClient = newResourceClientMock.Object
};
}

Expand Down Expand Up @@ -99,5 +104,21 @@ public void RemovesResourceGroupFromResourceId()

resourcesClientMock.Verify(f => f.DeleteResourceGroup(resourceGroupName), Times.Never());
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RemovesResourceGroupFromForceDeletionType()
{
commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
newResourceClientMock.Setup(f => f.DeleteResourceGroup(resourceGroupName, resourceForceDeletionType));

cmdlet.Name = resourceGroupName;
cmdlet.ForceDeletionType = resourceForceDeletionType;
cmdlet.Force = true;

cmdlet.ExecuteCmdlet();

newResourceClientMock.Verify(f => f.DeleteResourceGroup(resourceGroupName, resourceForceDeletionType), Times.Once());
}
}
}
1 change: 1 addition & 0 deletions src/Resources/Resources/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
-->

## Upcoming Release
* `Remove-AzResourceGroup` - support parameter "[-ForceDeletionType]".
* Removed specific characters from the codebase to unblock digital signature verification.

## Version 7.3.0
Expand Down
31 changes: 27 additions & 4 deletions src/Resources/Resources/help/Remove-AzResourceGroup.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ Removes a resource group.

### RemoveByResourceGroupName (Default)
```
Remove-AzResourceGroup [-Name] <String> [-Force] [-AsJob] [-ApiVersion <String>] [-Pre]
[-DefaultProfile <IAzureContextContainer>] [-ProgressAction <ActionPreference>] [-WhatIf] [-Confirm]
Remove-AzResourceGroup [-Name] <String> [-ForceDeletionType <String>] [-Force] [-AsJob] [-ApiVersion <String>]
[-Pre] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm]
[<CommonParameters>]
```

### RemoveByResourceGroupId
```
Remove-AzResourceGroup -Id <String> [-Force] [-AsJob] [-ApiVersion <String>] [-Pre]
[-DefaultProfile <IAzureContextContainer>] [-ProgressAction <ActionPreference>] [-WhatIf] [-Confirm]
Remove-AzResourceGroup -Id <String> [-ForceDeletionType <String>] [-Force] [-AsJob] [-ApiVersion <String>]
[-Pre] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm]
[<CommonParameters>]
```

Expand Down Expand Up @@ -55,6 +55,14 @@ Get-AzResourceGroup | Remove-AzResourceGroup

This command uses the **Get-AzResourceGroup** cmdlet to get all resource groups, and then passes them to **Remove-AzResourceGroup** by using the pipeline operator.

### Example 4: Remove a resource groups use ForceDeletionType
```powershell
Remove-AzResourceGroup -Name "ContosoRG01" -ForceDeletionType "Microsoft.Compute/virtualMachineScaleSets,Microsoft.Compute/virtualMachines,Microsoft.Databricks/workspaces"
```

This command removes the ContosoRG01 resource group use the ForceDeletionType.
The cmdlet prompts you for confirmation and returns no output.

## PARAMETERS

### -ApiVersion
Expand Down Expand Up @@ -118,6 +126,21 @@ Accept pipeline input: False
Accept wildcard characters: False
```
### -ForceDeletionType
The resource types you want to force delete.Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Id
Specifies the ID of resource group to remove.
Wildcard characters are not permitted.
Expand Down

0 comments on commit 0674f22

Please sign in to comment.