Azure Function Job to Delete Azure Blobs from Blob Containers
[toc]
Introduction
I have tried many things with Azure Functions and you should be able to see then here. Here in this post we are going to see how we can create a job which runs in a particular day and time to delete the blobs we have in a blob containers in our Azure Storage Account. If you want to know how you can upload to the blobs using Azure Function, consider reading my article here.
Prerequisites
- You should have a valid Azure Subscription
- You should have a running Azure Function
- If you are not sure about how to create an Azure Function App, this post may help you.
- You should have a valid Azure Storage Account
Using the code
Configure the Dependency Injection in Azure Function
As we are going to inject our dependency via constructor we need to configure the same by creating a Startup.cs class in our solution. Let’s do that first. To configure, make sure that you had installed the Nuget Package Microsoft.Azure.Functions.Extensions.
Now create a new class and name it as Startup.cs and write the code as preceding.
Here we are adding a singleton service for our IBlobService. Do not forget to inherit your Startup class from FunctionsStartup.
Write the Azure Function
As we have set up our Startup class, now let us create our Azure Function. Follow this post to see how you can create one. And you can write the code as preceding.
Here we are making the Function to run on every Monday at 4 AM using the CRON expression. Make sure to check my previous post to see more about the CRON expression.
Below are the blob container names I have in my Azure Blob Storage.
Make sure to use the small letters for your Azure Blob Container names, otherwise you will see an exception as mentioned here.
Creating the Blob Service
Now let us create a new Interface for our service.
And then create a service BlobService.
Here you can see that in the PerformTasks function we are getting the blob container reference and then get all the blobs using ListBlobsSegmentedAsync and then cast it as ICloudBlob so that we can easily delete the blobs.
Make sure to add the AzureWebJobsStorage in your local.settings.json file and in the Azure Function Configuration in the portal.
Conclusion
Wow!. Now we have learned,
- about Azure Function and setting up the same
- about Time Trigger in Azure Function
- about CRON expressions in Azure Function
- how to set up dependency injection in Azure Function
- how to delete Azure blobs from Azure Blob Containers using Azure Function
You can always ready my Azure articles here.
Your turn. What do you think?
Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.
Kindest Regards
Sibeesh Venu