Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent error "WARNING: Unable to acquire token for tenant 'tenantid'" when running Powershell scripts in Azure

I'm creating a Service principal to be used as an Azure Runas Account for Azure Automation, using a Powershell script. The script works, however I get the following warning when it's completed
WARNING: Unable to acquire token for tenant 'tenantID'.

The tenantID from the warning message is another tenant that my account has access to, which has multiple subscriptions within it. However it's unrelated to the tenantid and subscription I'm logging in to.

I've tried logging in via the Powershell window, then running the script without having the login inside the script, but get the same error. When I run get-AzContext in the Powershell window after the script runs, it lists the correct tenantID

Function being used to login is below. the tenant ID is not the same as the one I get the Warning for

function Login {
    # Log in
    $tenantid = "tenantID"
    $subscriptionId = "subscriptionID"
    $subscriptionName = "subscriptionname"
    Clear-AzContext -Force
    Message("Logging In")
    $account = $(Get-AzContext).Account
    if ([string]::IsNullOrEmpty($account)) {
        Login-AzAccount -Tenant $tenantid -Subscription $subscriptionId
    }
    # Select the subscription

    Message("Selecting the '$subscriptionName' Subscription")
    Set-AzContext $subscriptionId | Out-Null
}


I have no other references to tenantID.  The only other reference I have is for the subscriptionID, in a script which is called by the original script.
$Subscription = $(Get-AzContext).Subscription

I'd like to understand why it's trying to access the different TenantID for a token, and not to have the error when running the script
like image 555
Wayno Avatar asked Nov 08 '19 08:11

Wayno


3 Answers

Login

Connect-AzAccount

Check your current available subscriptions

Get-AzContext -ListAvailable

Select the subscription you want to work on

Select-AzContext -Name ''
like image 90
shaonm Avatar answered Nov 19 '22 21:11

shaonm


I posted the answer already. The Get-AzSubscription command is the issue, it tries to access all the subscriptions you have access to. You need another command to get the subscription id, I used get-azcontext to get the current subscription id

like image 4
Wayno Avatar answered Nov 19 '22 19:11

Wayno


You are trying to logon to an MFA enabled tenant. Try this and then MFA accept on your phone

# Connect to your Subscription
# Ex: Connect-AzAccount -Credential $credentials -Subscription 0000-4566-bcb4-000 -TenantId 00-f750-00-91d3-00  
Connect-AzAccount -Subscription 00-9f21-4566-bcb4-00 -TenantId 00-f750-4013-91d3-00
like image 4
Mr Allen Visser Avatar answered Nov 19 '22 19:11

Mr Allen Visser