Help with Bicep Template for Deleting Azure Resources Based on Resource Name

Gupta, Shalu 30 Reputation points
2024-10-14T10:34:46.59+00:00

I have created Bicep templates for provisioning various Azure resources such as Azure OpenAI, Azure Cognitive Search, Azure App Service, and Azure Cosmos DB.

In a similar way, I would like to write a Bicep template or script that allows for the deletion of a specific resource, based on a resource name provided by the user at runtime. This deletion should completely remove the resource from the resource group.

Could someone please guide me on how to achieve this? Any insights or examples would be greatly appreciated. Thank you in advance!

Azure Machine Learning
Azure Machine Learning
An Azure machine learning service for building and deploying models.
2,951 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,073 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,659 questions
Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
3,193 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,881 questions
{count} votes

Accepted answer
  1. VenkateshDodda-MSFT 21,491 Reputation points Microsoft Employee
    2024-10-18T17:59:20.8033333+00:00

    @Gupta, Shalu Thanks for your response,

    Deployment scripts use a managed identity to authenticate to Azure. deploymentScripts resources are either PowerShell or Bash scripts that run in a Docker container as part of your template deployment.

    As mentioned above, I have made couple of changes to the above template and tested it in my subscription by creating a sample logic app and deleting it through the bicep template it is working fine.

    Here are the modified templates:

    **Main.bicep template:

    
    @description('Name of the resource to delete')
    
    param resourceName string
    
    @description('Subscription ID where the resource exists')
    
    param subscriptionId string
    
    @description('Resource Group where the resource is located')
    
    param resourceGroup string
    
    var userAssignedIdentityName = 'configDeployer57'
    var roleAssignmentName = guid(userAssignedIdentity.id, 'contributor')
    var contributorRoleDefinitionId = resourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
    var deploymentScriptName = 'ResourceDeleted57'
    
    resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
      name: userAssignedIdentityName
      location: 'westus'
    }
    
    resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
      name: roleAssignmentName
      properties: {
        roleDefinitionId: contributorRoleDefinitionId
        principalId: userAssignedIdentity.properties.principalId
        principalType: 'ServicePrincipal'
      }
    }
    
    resource deleteScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
        name: deploymentScriptName
        location: 'swedencentral'
        kind: 'AzureCLI'
        identity: {
          type: 'UserAssigned'
            userAssignedIdentities: { 
              '${userAssignedIdentity.id}': {}}
            }
        properties: {
            azCliVersion: '2.30.0'
            arguments: '${resourceName} ${subscriptionId} ${resourceGroup}'
            scriptContent: '''
              #!/bin/bash
              set -e 
              # Set subscription context
              az account set --subscription "$2"
    
              # Get the resource ID using the az resource list command
              RESOURCE_ID=$(az resource list --subscription "$2" --resource-group "$3" --name "$1" --query "[0].id" --output tsv)
              if [ -n "$RESOURCE_ID" ]; then
                # If the resource exists, delete it
                az resource delete --ids $RESOURCE_ID
                  echo "Resource $1 deleted successfully."
              else
                 echo "Resource $1 not found in resource group $RESOURCE_GROUP."
               fi
            '''
        retentionInterval: 'P1D'
        timeout: 'PT30M'
      }
      dependsOn: [
        roleAssignment
      ]
    }
    
    
    

    Here is the parameters template :

    using 'main.bicep'
    param resourceName  = '<resourceName>'
    param subscriptionId  = '<subscriptionId>'
    param resourceGroup = '<ResourceGroupName>'
    
    

    The output will be shown in the deployment script resource logs as shown in the below.

    User's image

    You can go through learn tutorial on how to work with deployment scripts in Bicep for better understanding.

    Note : Please do modify the bicep template based on your requirement.

    Hope this helps let me know if you have any further questions on this.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.