how to create a timer trigger function to delete resource group in azure sdk python

Sushant Seven 0 Reputation points
2023-07-26T11:10:56.79+00:00

how to create an azure function to delete resource group

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,421 questions
Azure Logic Apps
Azure Logic Apps
An Azure service that automates the access and use of data across clouds without writing code.
3,352 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Saurabh Sharma 23,826 Reputation points Microsoft Employee
    2023-07-26T22:49:05.27+00:00

    Hi Sushant Seven,

    Thanks for using Microsoft Q&A!!

    In order to delete a resource group using Azure SDK in python, you need to use the Azure Resource management client library (azure-mgmt-resource) of python.

    Here is the code snippet using the above client library to delete the resource group through a scheduled triggered function-

    import datetime
    import logging
    import azure.functions as func
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.resource import ResourceManagementClient
    
    def main(mytimer: func.TimerRequest) -> None:
        utc_timestamp = datetime.datetime.utcnow().replace(
            tzinfo=datetime.timezone.utc).isoformat()
        
        if mytimer.past_due:
            logging.info('The timer is past due!')
        
        # Get the resource group name from the environment variable
        resource_group_name = '{resource_group}'
    
        # Get the subscription ID from the environment variable
        subscription_id = '{subscription_id}'
    
        # Get the credential from the environment variable
        credential = DefaultAzureCredential()
    
        # Create the resource management client
        resource_client = ResourceManagementClient(credential, subscription_id)
    
        # Delete the resource group    
        poller = resource_client.resource_groups.begin_delete(resource_group_name)
        result = poller.result()
    
        logging.info("Deleted resource group %s.", resource_group_name)
        logging.info('Python timer trigger function ran at %s', utc_timestamp)
    
    

    PPUser's image

    PPPlease let me know if you have any questions.

    Please refer to the below documents for additional information -

    1. Delete a Resource Group using Python
    2. Example: Use the Azure libraries to create a resource group
    3. Key concepts - DefaultAzureCredential in local and on Azure
    4. Azure SDK - Python Samples
    5. Azure RBAC roles

    Thanks

    Saurabh


    Please do not forget to "Accept the answer" wherever the information provided helps you to help others in the community.


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.