Configure ServiceBusTriggerAttribute from AppSettings

See original GitHub issue

I’m developing an application where the infrastructure is completely deployed with ARM. I create the service bus / the topic / the subscription with it also.

In my azure functions, I set the app settings for the service bus with ARM also.

Currently only the Connection parameter parameter looks in app settings.

Since the Attribute is sealed and it wants constant parameters there is no way to fix this.

[FunctionName("MyFunction")]
public static void Run(Run([ServiceBusTrigger("MyTopic", "MySubscription", AccessRights.Listen, Connection = "ConnectionString")]BrokeredMessage mySbMsg, TraceWriter log)

It would be nice to have MyTopic & MySubscription fetched from AppSettings like the ConnectionString

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

18reactions
TheeJamesLeecommented, Jul 11, 2017

Been in the same boat. It is already done.

Have a look at this sample function here and in the AnalyseImage.cs file at the trigger attribute:

[FunctionName("ReviewImageAndText")]
  public static async Task ReviewImageAndText(
  [QueueTrigger("%queue-name%")]  ReviewRequestItem queueInput,
  [Blob("input-images/{BlobName}", FileAccess.Read)]  Stream image,
  [DocumentDB("customerReviewData", "reviews", Id = "{DocumentId}", PartitionKey = "Reviews", ConnectionStringSetting = "customerReviewDataDocDB")]  dynamic inputDocument)
  {

In the QueueTrigger, the ‘%’ is specifying that it wants to be resolved from a setting. This will look (when deployed on azure) at the WebApp settings you can set via arm. When running functions locally, they are defined in the local.settings.json as you can see in the sample app, that the queue-name has been assigned there.

In the ARM template, as normal, resolve and apply the values as settings in the web app properties with the same name as you use for the config setting in local.settings.json, which is the same as between the %'s

4reactions
rhythmnewtcommented, Aug 14, 2020

In my case i have config for keyvault loaded first, then I have to load keyvault, then I have to deserialize my credentials from keyvault and only then I can have the service bus connection string to bind to. It took me a bit of time to get it right, but here’s the solution in case someone else runs into same issue. Hope it helps someone!

           // Gets the default configuration so we can load keyvault
            var bootstrapConfig = new ConfigurationBuilder()
                .AddEnvironmentVariables("config:") //this only picks app settings that start with "config:" and at the same time strips off "config;" after load
                .Build();

           //get the keyvault URL from current config
           var keyvault = bootstrapConfig["VaultBaseUrl"];

            // Creates a new config based on the default one and adds the keyvault configuration builder
            var keyVaultConfig = new ConfigurationBuilder()
                .AddConfiguration(bootstrapConfig)
                .AddAzureKeyVault(keyvault)
                .Build();

            //this is my custom step to deserialize JSON in mycustomsecret to an POCO that I can work with
            var credentials = CredentialManager.GetFromString(keyVaultConfig["mycustomsecret"]);

            //this is needed for the servicebus function binding to work properly
            Environment.SetEnvironmentVariable($"dynamic:ServiceBusConnectionString", credentials.ConnectionStrings.ServiceBus);

            //creates a final config including dynamic environment variables used for function bindings like ServiceBus
            var config = new ConfigurationBuilder()
                .AddConfiguration(keyVaultConfig)
                .AddEnvironmentVariables("dynamic:") //this only picks app settings that start with "dynamic:" and at the same time strips off "dynamic;" after load
                .Build();

            //this is required to replace the IConfiguration with current settings otherwise the new Environment variable isn't picked up
            builder.Services.AddSingleton<IConfiguration>(config);

Now when setting up the binding for the function I can reference the new environment variable

        [ServiceBusAccount("ServiceBusConnectionString")]
        [FunctionName("ProcessMessage")]
        public async Task ProcessMessage([ServiceBusTrigger("%myQueueName%")] Message message, ILogger log, CancellationToken cancellationToken, MessageReceiver messageReceiver)
        {
              var request = JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(message.Body));
        }

local.settings.json NOTE: You will get a warning on build/run that ServiceBusConnectionString doesn’t exist in local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "config:VaultBaseUrl": "https://MYKEYVAULT.vault.azure.net",
    "myQueueName": "service-bus-dev-queue"
  }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

ServiceBusTrigger: local.settings to "cloud" settings
1 Answer 1 · tnx, I know local.settings. · Another problem is that we also tried (as workaround) to add an appsettings.json in...
Read more >
Azure Service Bus trigger for Azure Functions
For information on setup and configuration details, ... use the ServiceBusTriggerAttribute attribute to define the function trigger.
Read more >
Azure Functions with Azure Service Bus
ServiceBusTriggeredEndpointConfiguration loads certain configuration values from the Azure Function host environment in the following order:.
Read more >
Untitled
The following screenshot demonstrates these three app settings in use: Step ... at computer chip Configure ServiceBusTriggerAttribute from AppSettings #1221 ...
Read more >
Untitled
Code for local.settings.json where the Service Bus connection string is set. ... and subscribers Configure ServiceBusTriggerAttribute from AppSettings #1221 ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found