Restarting Container Instance from Azure function

Karlo Lochert 1 Reputation point
2022-11-17T12:14:13.777+00:00

Hi,

I created an Azure function (Timer Trigger) to restart my container instance with an API call:

HttpClient restarthttpClient = new HttpClient();  
string bearerToken = "token";  
restarthttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",bearerToken);  
  
var restart_domain = "https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart?api-version=2022-09-01";  
  
restarthttpClient.PostAsync(restart_domain,null);  
  

The problem is that my bearerToken expires too soon. Is there a way to get a token without expiration (or with a much longer expiration) or a better way of achieving the desired functionality?

Thank you,
Karlo

Azure Container Instances
Azure Container Instances
An Azure service that provides customers with a serverless container experience.
635 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,231 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Mennel 76 Reputation points
    2022-11-17T12:48:39.41+00:00

    Hi,

    you can assign the function a managed identity and then make sure to assign the managed identity a role which allows to restart the container instance. For simplicity you can use Contributer, but best would be a custom role which just includes Microsoft.ContainerInstance/containerGroups/restart/action permission.

    As soon as this is done, you can use powershell with the command az container restart --name name-of-the-container --resource-group your-rg-name

    A really similar problem was stated here: https://techcommunity.microsoft.com/t5/apps-on-azure-blog/manage-azure-resources-using-powershell-function-app-with/ba-p/3099282 - you can use this as a template and then just modify the code with the command given above.

    I hope this helps.

    Regards,
    Andy

    0 comments No comments

  2. MayankBargali-MSFT 68,396 Reputation points
    2022-11-23T07:42:54.32+00:00

    @Karlo Lochert Thanks for reaching out. You should not hardcode the bearer token as it expires after some time. The token cannot be generated without the expiry time. You should always get the new token (rather than hardcoding) when you function execute and make a renew token call before making any management calls. For other details on how the acquire token works you can refer to Azure Management REST API document.

    0 comments No comments