Search code examples
azureazure-functionsazure-storageazure-eventgrid

Azure: How to create an Event subscription programmatically


I have many storage accounts that are created programmatically, and I'd like to create an event subscription in each to listen to BlobCreated events with an existing Azure Function endpoint. Right now, I'm doing this manually by going to the portal, but it's been time-consuming to say the least.

Are there any C# code examples that would create an event subscription using Azure credentials?


Solution

  • Please find an example in GitHub

        static async Task CreateEventGridEventSubscriptionAsync(string azureSubscriptionId, string eventSubscriptionName, EventGridManagementClient eventGridMgmtClient)
        {
            Console.WriteLine($"Creating an event subscription to Azure subscription {azureSubscriptionId} with destination as queue {QueueName} under storage account {StorageAccountId}");
    
            string scope = $"/subscriptions/{azureSubscriptionId}";
    
            EventSubscription eventSubscription = new EventSubscription()
            {
                Destination = new StorageQueueEventSubscriptionDestination()
                {
                    ResourceId = StorageAccountId,
                    QueueName = QueueName
                },
                // The below are all optional settings
                EventDeliverySchema = EventDeliverySchema.EventGridSchema,
                Filter = new EventSubscriptionFilter()
                {
                    IsSubjectCaseSensitive = false,
                    SubjectBeginsWith = "",
                    SubjectEndsWith = ""
                }
            };
    
            EventSubscription createdEventSubscription = await eventGridMgmtClient.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, eventSubscription);
            Console.WriteLine("EventGrid event subscription created with name " + createdEventSubscription.Name);
        }
    

    Please find the official documentation in MS Docs - IEventSubscriptionsOperations Interface

    MS Docs - EventSubscriptionsOperationsExtensions.CreateOrUpdateAsync(IEventSubscriptionsOperations, String, String, EventSubscription, CancellationToken) Method