简体   繁体   中英

"No subscription found in the context" error when invoking Azure Powershell cmdlets

I am trying to write some simple Powershell scripts to stop, start and restart our Azure web app. I can see that there are cmdlets called Stop-AzWebApp , Start-AzWebApp and Restart-AzWebApp that do this. The problem is they all require a parameter called DefaultProfile of type Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer . How do I get hold of this?

I have looked around for solutions but it seems confusing as there seem to be several ways of doing this including invoking Connect-AzAccount , but this requires multiple parameters (and I'm not sure which ones I need to supply).

Here is the error I get when I invoke Get-AzSubscription from our TFS build.

在此处输入图片说明

Here is the error I get when I invoke Stop-AzWebApp from our TFS build.

在此处输入图片说明

No subscription found in the context Please ensure that the credentials you provided are authorized to access the Azure subscription then run Connect-AzAccount to login

Here's the PS script I'm using.

$ResourceGroupName = "MyResourceGroup"
$Name = "MyWebAppName"

"Stopping web application " + $Name

"ResourceGroupName: " + $ResourceGroupName
"Name: " + $Name

$SubscriptionId = "xxxx-xxxx-xxxx-xxxx"
"SubscriptionId is: " + $SubscriptionId

$Subscription = Get-AzSubscription -SubscriptionId $SubscriptionId
"Subscription : " + $Subscription

Stop-AzWebApp -ResourceGroupName $ResourceGroupName -Name $Name

What's the simplest way to start, stop and restart an Azure web app?

From the error, you need to run Connect-AzAccount to login to azure powershell, but in TFS, you could not use the interactive way to login, so your option is to use the service principal to login, it is a non-interactive way.

Please follow the steps below.

1. Register an AD App in azure ad , then get values for signing in and create a new application secret .

2.Navigate to your subscription in the portal -> Access control (IAM) -> Add role assignment -> seacrh for the name of the AD App and add it as a role eg Owner/Contributor , see this link . 在此处输入图片说明

3.In your script, use the command below to login, you can get the vaules in step 1, then run the command eg Stop-AzWebApp , it will work fine.

$azureAplicationId ="<Application-ID>"
$azureTenantId= "<Tenant-ID>"
$azurePassword = ConvertTo-SecureString "<Client-secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal 
Set-AzContext -Subscription "<Subscription-id>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM