skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search