3

I am trying to run a runbook to start a VM using a managed identity. With a runas account it works but because Microsoft says it recommended to use a managed identity, I want to try it.

This is part of the script that I got from internet and that works with runas account:

$ResourceGroupName = 'test' 
$AzureVMName = 'test'   

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Login-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}

And this is the script that I tried to use now but does not work:

Connect-AzAccount -Identity
 
$ResourceGroupName = 'test' 
$AzureVMName = 'test'   

"Starting Azure VM..."
Start-AzureRmVM -Name $AzureVMName -ResourceGroupName $ResourceGroupName

I always get following error:

Environments

{[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud], [AzureGermanCloud, AzureGermanCloud], [AzureUSGovernme... Starting Azure VM... Run Login-AzureRmAccount to login.

I have tried many things but I cannot get it working...

stevenvd
  • 31
  • 4
  • 1
    Oh ok i see you are mixing Az and AzureRM modules. you need to use `Start-AzVM` (https://learn.microsoft.com/en-us/powershell/module/az.compute/start-azvm?view=azps-6.3.0) and make sure you have this module `Az.Compute` in your automation account. – Thomas Sep 01 '21 at 13:10

1 Answers1

2

As Thomas has already suggested you are using 2 modules which are "Az" and "AzureRM" in the below code :

Connect-AzAccount -Identity
 
$ResourceGroupName = 'test' 
$AzureVMName = 'test'   

"Starting Azure VM..."
Start-AzureRmVM -Name $AzureVMName -ResourceGroupName $ResourceGroupName

So instead use only Az module like below:

Connect-AzAccount -Identity
$ResourceGroupName = 'ansumantest' 
$AzureVMName = 'testVM'   

"Starting Azure VM..."
Start-AzVM -Name $AzureVMName -ResourceGroupName $ResourceGroupName

I tested this in my environment using one VM with managed identity to start another VM.

Output:

enter image description here

Reference:

Install the Azure Az PowerShell module | Microsoft Docs

Ansuman Bal
  • 9,705
  • 2
  • 10
  • 27