restart cloud service using powershell - azure

we have a problem with a Microsoft bot hosted in Azure.
As long as we haven't resolved it, we want to periodically restart it.
We found 3 sets of powershell commands and spent the full day on it without making it work.
Solution 1:
we found the cmdlets : Get-AzCloudService Restart-AzCloudService.
We didn't understand from the documentation what module to install.
It returns : The term 'Restart-AzCloudService' is not recognized as the name of a cmdlet.
They talk about an obscure "extended support" to have access to it.
Solution 2:
We are able to list the cloud service using:
Connect-AzAccount
get-azresource -name $serviceName -resourcetype
"Microsoft.BotService/botServices"
But we do not find the cmdlet to restart the resource.
Solution 3:
Reset-AzureRoleInstance -serviceName $serviceName -Slot "production" -InstanceName $serviceName
Error : No default subscription has been designated. Use Select-AzureSubscription -Default
We are using MFA. Login-AzureRmAccount systematically fails , evenly saying that our account is disabled.
We did no manager to run the sequence:
Login-AzureRmAccount
Select-AzureSubscription -Default
Reset-AzureRoleInstance -serviceName $serviceName -Slot "production" -InstanceName $serviceName
The idea is to run this script twice a day, either from a VM or from an Azure Runbook.
We managed to run this code using an automation Account but we are still missing the last command that would restart the bot (that we consider a cloud service).
Param()
$automationAccount = "xxx"
$resourceGroup = "xxx"
$serviceName = "xxx"
$subscriptionname ="xxx"
$subscriptionid ="xxx"
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null
# Connect using a Managed Service Identity
try {
$AzureContext = (Connect-AzAccount -Identity).context
}
catch{
Write-Output "There is no system-assigned user identity. Aborting.";
exit
}
#Set-AzureSubscription -SubscriptionId $subscriptionid
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
-DefaultProfile $AzureContext
get-azresource -name $serviceName -resourcetype "Microsoft.BotService/botServices"

Related

Azure Connect-AzAccount in runbook with managed identity fails

I am trying to execute a runbook in an automation account within azure.
I have set a managed identity following the instructions here, then i issue the following in my runbook:
Connect-AzAccount -Identity
Set-AzContext -Subscription Subscription1
As instructed here
But i get the following error:
Set-AzContext : Please provide a valid tenant or a valid subscription.
At line:134 char:1
+ Set-AzContext -Tenant $tenantId -Subscription $subscriptionId
I pass the tenantId and subscriptionId through as parameters, and have written them out to confirm they are correct.
Can anyone see where I am going wrong?
Update
I have added the owner role to the system assigned managed identity and now it seems to get the connection ok with Dilly B's suggestion below:
$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook
$AzureContext = (Connect-AzAccount -Identity -AccountId $managedIdentity).context # Connect to Azure with user-assigned managed identity
$connectionResult = Set-AzContext -Subscription $subscriptionId -DefaultProfile $AzureContext
however when i do:
$virtualMachine = Get-AzVM -ResourceGroupName $resourceGroupName -Name $virtualMachineName
I now get the following error:
Get-AzVM : The client '****************' with object id '*****************' does
not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/***************/providers/Microsoft.Compute/virtualMachines/************' or the scope is invalid. If access was recently granted, please refresh your credentials.
ErrorCode: AuthorizationFailed
ErrorMessage: The client '******************' with object id '*****************************'
does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/**************/providers/Microsoft.Compute/virtualMachines/**************' or the scope is invalid.
Please find the sample code below. Hope this helps!
$subscription = "000000-0000-0000-0000-000000000"
$identity = "000000-0000-0000-0000-000000000"
$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook
$AzureContext = (Connect-AzAccount -Identity -AccountId $identity).context # Connect to Azure with user-assigned managed identity
$connectionResult = Set-AzContext -Subscription $subscription -DefaultProfile $AzureContext
Make sure you have up-to-date modules for Az.Accounts (2.10.2), Az.Resources (6.3.0), Az.Automation (1.8.0).
https://learn.microsoft.com/en-us/azure/automation/automation-update-azure-modules

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it

I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error
Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to
set the default subscription.
I have used the below in my script.
Add-AzureRmAccount
Select-AzureRMSubscription
After calling the select, it prints out
PSComputerName : localhost
PSSourceJobInstanceId :
Account :
Environment :
Subscription :
Tenant :
with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.
Any ideas?
The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.
So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps
Create Azure Classic Run As Account
Script
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
# Authenticate to Azure with certificate
$CertificateAssetName = $Conn.CertificateAssetName
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
#stop VM
Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
Besides, regarding how to check if the VM is classic, please refer to the blog
Try Running the below :
Get-Module AzureRm.Profile -ListAvailable
This issue might occur when there is multiple instances of the module. If there are multiple instance remove the older modules and retain the new module.
To remove the old module : Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

Azure PowerShell-Runbook

Working on this as below - Using a power-shell script inside the Automation Account for run-book. The power-shell script will help in adding a rule inside the resource of the function-app of the networking rule. But somehow the following happens -
Not able to login the azure account
And it says Subscription ID doesn't exists. (Login is done via Service principle)
Code for reference
$azureAplicationId="XXXX"
$azureTenantId="XXXXX"
$azurePassword=ConvertToSecureString "XXXXXX" -AsPlainText -Force
$psCred=New-Object System.Management.Automation.PSCredential($azureAplicationId ,$azurePassword)
Login-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Select-AzureSubscription -SubscriptionId "XXXXXX"
Add-AzWebAppAccessRestrictionRule -ResourceGroupName "XXXXX" -WebAppName "XXXXX" -Name "iprule" -Priority 100 -Action Allow -IpAddress x.x.x.x/x –

Attempting to remove sql db in azure gives error "No default subscription has been designated"

I am currently trying to write a powershell script which logs into azure and then deletes an SQL database.
When it gets to the database deletion it gives an error:
Remove-AzureSqlDatabase : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default
subscription.
When i try to add a default subscription with Select-AzureSubscription -Default -SubscriptionName Pay-As-You-Go i get an error aswell:
Select-AzureSubscription : The subscription name Pay-As-You-Go doesn't exist.
I'm confused as to what the problem is and have tried connecting to the account via connect-AzAccount aswell.
The full script is:
$passwd = ConvertTo-SecureString password -AsPlainText -Force
$pscredential = New-Object System.Management.Automation.PSCredential('accountname', $passwd)
Connect-AzureRmAccount -Credential $pscredential -Tenant "tenant string"
# Set-AzContext -SubscriptionId "subscription id"
Select-AzureSubscription -Default -SubscriptionName Pay-As-You-Go
# Get-AzureSubscription -SubscriptionName “Pay-As-You-Go” | Select-AzureSubscription -Default
Remove-AzureSqlDatabase -ServerName migrate -DatabaseName "AWS-Copy"
You could not mix the three powershell module Azure, Az, AzureRm together, and if you have installed the Az module, I recommend you to uninstall the AzureRm module, it was deprecated and will never be updated.
To remove sql db with Az module, your script should be like below. Make sure your account has an RBAC role(e.g. Owner, Contributor) of your subscription/SQL Server.
$passwd = ConvertTo-SecureString password -AsPlainText -Force
$pscredential = New-Object System.Management.Automation.PSCredential('accountname', $passwd)
Connect-AzAccount -Credential $pscredential -Tenant "<tenant-id>"
Set-AzContext -Subscription "<subscription-id>"
Remove-AzSqlDatabase -ResourceGroupName "<ResourceGroupName>" -ServerName "<ServerName>" -DatabaseName "<DatabaseName>"

How to stop all VMs with Azure Automation using Resource Manager module?

I have created some Azure VMs using the new Resource Manager and i'd like to stop them everyday.
To do so, i've published a runbook to stop aboth classic and ARM VMs, and i created a scheduler which runs the runbook every night :
workflow Stop-AzureVMs
{
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureAccount -Credential $cred
Select-AzureSubscription -Current 'SubscriptionName'
Get-AzureVM | Stop-AzureVM –Force
Get-AzureRmVM | Stop-AzureRmVM -Force
}
I have imported the AzureResourceManager module to my Azure Automation account :
But i am getting this error :
Exception
At line:34 char:2
+ Get-AzureRMVM | Stop-AzureRMVM -Force
+ ~~~~~~~~~~~~~ Cannot find the 'Get-AzureRMVM' command. If this command is defined as a workflow, ensure it is defined before the workflow that calls it. If it is a command intended to run directly within Windows PowerShell (or is not available on this system), place it in an InlineScript: 'InlineScript { Get-AzureRMVM }'
How is that possible ?
Edit : Below is the solution
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureRmAccount -Credential $cred
Select-AzureRmSubscription -Name 'SubscriptionName' -SubscipritionId 'SubscriptionId'
Get-AzureRmVM | Stop-AzureRmVM -Force
All workflows i found didn't mention the use of Add-AzureRmAccount and Select-AzureRmSubcription instead of the standard Add-AzureAccount and Select-AzureSubscription. I thought that the authentication process to our Azure account was the same.
Update : It is now possible to combine both ASM and ARM cmdlets within the same runbooks, see this post for more informations about ARM supported by default on Azure Automation
Looks like you imported the old version of the ARM cmdlets (before Azure PS 1.0) into Azure Automation. This was before the *-AzureRm* renaming. So tt should be Stop-AzureVM not Stop-AzureRmVM.
However, that makes it ambiguous as to whether you are trying to call Azure Service Management or Azure Resource Manager cmdlets -- which is exactly why the cmdlet names were renamed in Azure PS 1.0. I recommend you follow the guidance here.
As per my understanding ASM mode is default. If you are going for ARM command firstly switch mode is required using Switch-AzureMode
One more confusion is what is the purpose of Get-AzureRMVM command. I googled but coulndn't find anything -
The Get-AzureRMVM cmdlet is in the AzureRM.Compute module... The AzureRM* cmdlets are still in preview, I don't think they are available in Azure Automation yet.
The two modules in your screenshot above likely correspond to the 0.9.x version of the cmdlets and there were indeed two different modules (Azure=ASM and AzureResourceManager=ARM) behind Switch-AzureMode. Switch-AzureMode just unloads one and loads the other.
If Automation is still using the 0.9.x version of the cmdlets then you should be able to just use Get-AzureVM for ARM VMs using the AzureResourceManager module.
Below is the solution
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureRmAccount -Credential $cred
Select-AzureRmSubscription -Name 'SubscriptionName' -SubscriptionId 'SubscriptionId'
Get-AzureRmVM | Stop-AzureRmVM -Force
It is not yet possible to combine ARM and ASM cmdlets in same runbook apparently ... So you have to use only ARM cmdlet or ASM cmdlet.
Also, all workflows i found didn't mention the use of Add-AzureRmAccount and Select-AzureRmSubcription instead of the standard Add-AzureAccount and Select-AzureSubscription.
I thought that the authentication process to our Azure account was the same.
The Following code will work for both old style and new Style VM's but be aware this will shut down all machines with no warning.
{
# TODO: update to the name of the credential asset in your Automation account
$AutomationCredentialAssetName = "AzureAutomationRG"
# Get the credential asset with access to my Azure subscription
$Cred = Get-AutomationPSCredential -Name $AutomationCredentialAssetName
# Authenticate to Azure Service Management and Azure Resource Manager
Add-AzureAccount -Credential $Cred
Add-AzureRmAccount -Credential $Cred
"`n-Old Style VMS-`n"
# Get and output Azure classic VMs
$VMs = Get-AzureVM
$VMs.Name
Get-AzureVM | Stop-AzureVM -Force
"`n-New Style Resource Group VMs-`n"
# Get and output Azure v2 VMs
$VMsv2 = Get-AzureRmVM
$VMsv2.Name
Get-AzureRmVM | Stop-AzureRmVM -Force
}
For new Azure RM VMs use access extensions the following command:
Set-AzureRmVMAccessExtension -ResourceGroupName "ResourceGroupName" -VMName "VMName" -Username "Admin User Name" -Password "Admin Password" -Name "Extension Name"
Please note the -Name parameter is the arbitrary extension name.
This might be late to the party, but I would recommend you check out this link:
https://www.attosol.com/start-or-stop-all-vms-of-a-resource-group-in-azure/
Basically, you can create a script and write some aliases with switches to make your job super easy.

Resources