I am unable to automate Connect-AzureAD powershell command.
In order to get user objectID, I need to automate the operation Connect-AzureAD and for that i used this code:
Connect-AzureAD -TenantId $tenantId -Verbose
$userObjectID = $(Get-AzureADUser -Filter "UserPrincipalName eq '$Owner'").ObjectId
The operation stuck at the Connect-AzureAD.
how to resolve this?
I found the solution and test it.
I'm running this task in an Azure Devops pipeline; this tasks is called "Azure PowerShell script" executed with the latest installed version.
Install-Module -Name "AzureAD" -Force
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
Write-Output "Hi I'm $($context.Account.Id)"
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id
Connect-AzureAD
by default will prompt you for login and password in pop up window.
Inside Azure DevOps Connect-AzureAD
by default stacks waiting for input from user and pipeline never finishes, as user cannot input anything.
You need to use :
Connect-AzureAD -Credential $Credential -TenantId $tenantId -Verbose
Where $Credential
is PSCredential
object.
Ideally, you need to create Service Principal in your Azure AD with permissions to access to Microsoft Graph and generate a secret key. After, you can use Application ID and Key of your service principal as login and password for $Credential
.
In Azure DevOps do not forget to use secret variables or Variables group linked with KeyVault to protect your Key.