Reputation: 2522
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?
Upvotes: 2
Views: 6164
Reputation: 42163
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 e.g. 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 e.g. 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>"
Upvotes: 4