Search code examples
c#azureazure-functionsapplication-settings

Updating remote Function App Application Settings in C#


I am currently writing a scheduled Function App that in part will need to update an Application Setting of a different Function App on which I have given the Service Principal access. The Function App that I need to update is hosted within the same App Service Plan.

I understand that I can achieve this through Powershell using the az functionapp config appsettings set cmdlet but I wanted to know if this is possible in C#


Solution

  • Looks like it is possible using the Microsoft.Azure.Management.AppService.Fluent and Microsoft.Azure.Management.ResourceManager.Fluent extension libraries which are wrappers around the REST calls.

    using Microsoft.Azure.Management.AppService.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using System;
    using System.Threading.Tasks;
    
    namespace Azure_Storage_Account_Key_Rotation
    {
        internal async Task UpdateApplicationSetting(string appServiceResourceGroupName, string appServiceName, string appSettingName, string appSettingValue)
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(Environment.GetEnvironmentVariable("AZURE_CLIENT_ID"),
                                                                                        Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET"),
                                                                                        Environment.GetEnvironmentVariable("AZURE_TENANT_ID"),
                                                                                        AzureEnvironment.AzureGlobalCloud);
    
            RestClient restClient = RestClient.Configure()
                                        .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        .WithCredentials(credentials)
                                        .Build();
    
            WebSiteManagementClient webSiteManagementClient = new WebSiteManagementClient(restClient) { SubscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID") };
    
            var appServiceSettings = await webSiteManagementClient.WebApps.ListApplicationSettingsAsync(appServiceResourceGroupName, appServiceName);
    
            if (appServiceSettings.Properties.ContainsKey(appSettingName))
            {
                appServiceSettings.Properties[appSettingName] = appSettingValue;
                await webSiteManagementClient.WebApps.UpdateApplicationSettingsAsync(appServiceResourceGroupName, appServiceName, appServiceSettings);
            }
        }
    }