Update App Settings in Azure Function App using Power Shell Script

Introduction

Managing application settings efficiently is crucial for maintaining the stability, security, and performance of your Azure Function Apps. However, manual updates to these settings can be time-consuming and error-prone, particularly as your application ecosystem grows in complexity. In this blog post, we'll explore how to streamline the process of updating application settings in Azure Function Apps using PowerShell scripting. By automating this task, you can ensure consistency across different environments, simplify deployment workflows, and minimize the risk of human error.

Problems with Manual Updates

Manual updates to application settings in Azure Function Apps present several challenges.

  1. Error-Prone: Typographical errors or incorrect values can easily slip through during manual updates, leading to runtime issues or security vulnerabilities.
  2. Time-Consuming: As the number of function apps and settings increases, manually updating them becomes increasingly laborious and time-consuming.
  3. Lack of Version Control: Without a systematic approach to managing changes, it's challenging to track modifications, leading to potential configuration drift and difficulties in troubleshooting.
  4. Inconsistencies Across Environments: Manual updates may result in discrepancies between development, staging, and production environments, leading to unexpected behavior.

Use Cases

Automating the update of application settings in Azure Function Apps offers numerous benefits across various scenarios.

  1. Continuous Deployment: Seamlessly integrate the update of application settings into your CI/CD pipelines to ensure consistent deployments and reduce manual intervention.
  2. Environment Management: Maintain parity between different environments by automating the propagation of configuration changes across development, staging, and production environments.
  3. Configuration as Code: Treat application settings as code, enabling version control, code review, and auditability, thereby enhancing collaboration and compliance.
  4. Rollback and Recovery: Facilitate rapid rollback to previous configurations in case of deployment failures or unintended consequences, minimizing downtime and customer impact.

Step by Step to Update App Settings using Power Shell

  1. Prepare the AppSettings JSON: Ensure a correctly formatted JSON file containing application settings is ready, including both standard and Key Vault reference values. Tailor this JSON file to each environment, such as development, testing, and production. Sample JSON is provided below.
    [
        {
          "name": "endpointURL",
          "value": "https://endpoint-dev.com",
          "slotSetting": false
        },
        {
          "name": "enviornment",
          "value": "dev",
          "slotSetting": false
        },
       {
          "name": "endpointUser",
          "value": "endpointuser",
          "slotSetting": false
        },
        {
          "name": "password",
          "value": "@Microsoft.KeyVault(SecretUri=https://sample-rg.vault.azure.net/secrets/password/)",
          "slotSetting": false
        }
    ]
  2. Install Azure CLI: Install Azure CLI to execute commands seamlessly within PowerShell. Install Azure CLI
  3. Check Current App Settings in Azure Portal: Review the current application settings in the Azure Portal for the Function App, which includes default settings established during provisioning.
    Azure portal
  4. Authenticate with Azure Using PowerShell: Authenticate with Azure services in PowerShell to enable interaction with Azure resources. Use the below command in Powershell.
    az login
  5. Run PowerShell Script: Execute the PowerShell script, ensuring to provide necessary parameters like Function App Name, Resource Group Name, Subscription ID, and the path to the App Settings File. Please Find the Script below.
    # Function to Update App Settings of FunctionApp
    Function Update-AppSettingsFunctionApp {
        # Parameters - FunctionAppName, ResourceGroupName, SubscriptionId, FilePath
        [CmdletBinding()]
        param (
            # FunctionApp Name
            [Parameter(Mandatory = $true)]
            [ValidateNotNullOrEmpty()]
            [String]$FunctionAppName,
      
            # ResourceGroup Name
            [Parameter(Mandatory = $true)]
            [ValidateNotNullOrEmpty()]
            [String]$ResourceGroupName,
      
            # Subscription Id
            [Parameter(Mandatory = $true)]
            [ValidateNotNullOrEmpty()]
            [String]$SubscriptionId,
      
            # AppSettingsFile Location
            [Parameter(Mandatory = $true)]
            [ValidateNotNullOrEmpty()]
            [String]$settingsFile
    
        )
        Write-Host "##[debug] -----Starting Update-AppSettingsFunctionApp Function-----" -ForegroundColor Cyan
        Write-Host "##[command] Parameters" -ForegroundColor Yellow
        "_" * 10
        # Get the command name
        $CommandName = $PSCmdlet.MyInvocation.InvocationName;
        # Get the list of parameters for the command
        $ParameterList = (Get-Command -Name $CommandName).Parameters;
      
        # Grab each parameter value, using Get-Variable
        foreach ($Parameter in $ParameterList) {
            Get-Variable -Name $Parameter.Values.Name -ErrorAction SilentlyContinue;
        }
      
        # Set Subscription
        Write-Host "Setting Subscription"
        az account set -s $SubscriptionId
      
        # Display the Existing App Settings Count
        try {
       
            Write-Host("Current AppSettings in the Function App")
            $setting = az functionapp config appsettings list --name $FunctionAppName --resource-group $ResourceGroupName
            Write-Host $setting.count  
      
            # Updating App Settings
        
            Write-Host "Updating App Settings"
            az functionapp config appsettings set -g $ResourceGroupName -n $FunctionAppName --settings @$settingsFile --only-show-errors | out-null
            Write-Host "Appsettings after Update"
            $setting = az functionapp config appsettings list --name $FunctionAppName --resource-group $ResourceGroupName
            Write-Host $setting.count 
        
            Write-Host "##[debug] -----Completed Update-AppSettingsFunctionApp Function-----" -ForegroundColor Cyan
        }
        catch [Exception] {
            write-host $_.Exception.Message
            Write-Host "`nError in Line: " $_.InvocationInfo.Line
            Write-Host "`nError in Line Number: "$_.InvocationInfo.ScriptLineNumber
            Write-Host "`nError Item Name: "$_.Exception.ItemName
            throw $_.Exception.Message
        } 
    }
    
    Update-AppSettingsFunctionApp -FunctionAppName "sangathitiog-d365-func" -ResourceGroupName "sangathitiog-d365-dev-rg"  -SubscriptionId "d98999ef-3e5c-42df-96e0-679c3b976a0b" -settingsFile "C:\Users\user\OneDrive - User\Desktop\Blogs\1-UpdateAppSettings\settings.json"
    
  6. Check the Output of PowerShell Script
    Powershell
  7. Verify Updated App Settings in Azure Portal: Confirm the incorporation of updated application settings in the designated Function App by checking the Azure Portal. This step ensures the successful implementation of desired configurations.
    App Settings

Conclusion

In summary, automating the management of application settings in Azure Function Apps using PowerShell simplifies deployment processes, improves efficiency, and reduces errors. By following the outlined steps, users can seamlessly update settings, ensuring consistency across environments and facilitating smoother operations.