如何使用Powershell重新启动容器实例

时间:2019-12-05 16:00:53

标签: azure powershell automation cmdlets

我试图使用PowerShell设置自动化作业以重新启动容器实例。但是似乎没有内置的PowerShell模块/ cmdlet可以帮助您

我可以使用azure CLI(https://docs.microsoft.com/en-us/cli/azure/container?view=azure-cli-latest#az-container-restart)重新启动容器实例

az container restart --name <name> --resource-group <group>

有没有一种方法可以使用Powershell来完成。

预先感谢

1 个答案:

答案 0 :(得分:1)

Azure PowerShell不提供直接重启容器实例的建议,但我们可以使用Powershell调用Azure管理API来重启容器实例作为解决方法。

  1. 在Azure AD中注册应用程序,为其创建客户端密钥,记下其值和应用程序ID(可以在“概述”中找到): enter image description here

enter image description here

  1. 为其分配贡献者角色,以便它有权管理您的Azure资源: enter image description here

3。尝试下面的powershell脚本重新启动容器实例:

$appid = "<application ID we resistered>"
$appSecret= "<application client secret we created>"
$tenant = "<your tenant ID/NAME>"

$resourceGroup = "<resource group>"
$containerInstanceName = "<containerInstances name>"
$subscrptionId = "<subscription ID>"

$body=@{
    "grant_type"="client_credentials";
    "resource"="https://management.azure.com/";
    "client_id"=$appid;
    "client_secret"=$appSecret
}
 
$result=Invoke-RestMethod -Uri "https://login.windows.net/$tenant/oauth2/token" -Method POST -Body $body 
$accessToken = $result.access_token

Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$subscrptionId/resourceGroups/$resourceGroup/providers/Microsoft.ContainerInstance/containerGroups/$containerInstanceName/restart?api-version=2018-10-01" -Method POST -Headers @{"Authorization"="Bearer $accessToken"} 

结果: enter image description here