-1

We have a azure function where we are calling few API's. its an eventhub trigger function. we have a scenario where the api which we are calling goes into schedule maintenance very often. we want to build a re try mechanism where we are re trying for x number of times and on failure we want to disable the function on runtime. is there a way we can do that in the function app itself?

Ecstasy
  • 1,866
  • 1
  • 9
  • 17
rohvin
  • 21
  • 5
  • I think this answer might help you: https://stackoverflow.com/a/67780780/3652378 – Melissa Aug 08 '21 at 01:39
  • Does this answer your question? [How to Enable/Disable Azure Function programmatically](https://stackoverflow.com/questions/42400963/how-to-enable-disable-azure-function-programmatically) – Ian Kemp Aug 09 '21 at 05:46

1 Answers1

1

Thank you Melissa and Ian Kemp. Posting your suggestions as answer to help other community members.

Use the below code to disable the Azure Function

public class FunctionsHelper
{
    private readonly ClientSecretCredential _tokenCredential;
    private readonly HttpClient _httpClient;

    public FunctionsHelper(string tenantId, string clientId, string clientSecret, string subscriptionId, string resourceGroup, string functionAppName)
    {
        var baseUrl =
            $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{functionAppName}/";
        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(baseUrl)
        };

        _httpClient = httpClient;
        
        _tokenCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    }

    private async Task SetAuthHeader()
    {
        var accessToken = await GetAccessToken();
        _httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Bearer {accessToken}");
    }

    private async Task<string> GetAccessToken()
    {
        return (await _tokenCredential.GetTokenAsync(
            new TokenRequestContext(new[] {"https://management.azure.com/.default"}))).Token;
    }
    
    public async Task StopFunction(string functionName)
    {
        await SetFunctionState(functionName, isDisabled: true);
    }

    public async Task StartFunction(string functionName)
    {
        await SetFunctionState(functionName, isDisabled: false);
    }

    private async Task SetFunctionState(string functionName, bool isDisabled)
    {
        await SetAuthHeader();
        var appSettings = await GetAppSettings();
        appSettings.properties[$"AzureWebJobs.{functionName}.Disabled"] = isDisabled ? "1" : "0";

        var payloadJson = JsonConvert.SerializeObject(new
        {
            kind = "<class 'str'>", appSettings.properties
        });

        var stringContent = new StringContent(payloadJson, Encoding.UTF8, "application/json");
        
        await _httpClient.PutAsync("config/appsettings?api-version=2019-08-01", stringContent);
    }
    
    private async Task<AppSettings> GetAppSettings()
    {
        var res  = await _httpClient.PostAsync("config/appsettings/list?api-version=2019-08-01", null);
        
        var content = await res.Content.ReadAsStringAsync();
        
        return JsonConvert.DeserializeObject<AppSettings>(content);
    }
}

internal class AppSettings
{ 
    public Dictionary<string, string> properties { get; set; }
}

Check the SO for further information.

SaiSakethGuduru
  • 2,218
  • 1
  • 5
  • 15