Change Azure website app settings from code

Is it possible to change the app settings for a website from the app itself?

This is not meant to be an everyday operation, but a self-service reconfiguration option. A non-developer can change a specific setting, which should cause a restart, just like I can do manually on the website configuration page (app setting section)


Solution 1:

You can also use the Azure Fluent Api.

using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

...

public void UpdateSetting(string key, string value)
{
    string tenantId = "a5fd91ad-....-....-....-............";
    string clientSecret = "8a9mSPas....................................=";
    string clientId = "3030efa6-....-....-....-............";
    string subscriptionId = "a4a5aff6-....-....-....-............";

    var azureCredentials = new AzureCredentials(new
      ServicePrincipalLoginInformation
    {
        ClientId = clientId,
        ClientSecret = clientSecret
    }, tenantId, AzureEnvironment.AzureGlobalCloud);

    var _azure = Azure
   .Configure()
   .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
   .Authenticate(azureCredentials)
   .WithSubscription(subscriptionId);

    var appResourceId = "/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Web/sites/xxx"; //Get From WebApp -> Properties -> Resource ID

    var webapp = _azure.WebApps.GetById(appResourceId);

    //Set App Setting Key and Value
    webapp.Update()
        .WithAppSetting(key, value)
        .Apply();
}

Solution 2:

It wasn't that hard once I found the right lib to do it, Microsoft Azure Web Sites Management Library.

var credentials = GetCredentials(/*using certificate*/);
using (var client = new WebSiteManagementClient(credentials))
{
    var currentConfig = await client.WebSites.GetConfigurationAsync(webSpaceName,
                                                                    webSiteName);
    var newConfig = new WebSiteUpdateConfigurationParameters
                    {
                        ConnectionStrings = null,
                        DefaultDocuments = null,
                        HandlerMappings = null,
                        Metadata = null,
                        AppSettings = currentConfig.AppSettings
    };
    newConfig.AppSettings[mySetting] = newValue;
    await client.WebSites.UpdateConfigurationAsync(webSpaceName, webSiteName,
                                                   newConfig);
}

Solution 3:

Have you read into the Service Management REST API? The documentation mentions that it allows you to perform most the actions that are available via the Management Portal programmatically.