Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate Connect-AzureAD using powershell in Azure Devops

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?

like image 931
Makram Avatar asked Feb 12 '20 09:02

Makram


People also ask

How do I import AzureAD module into PowerShell?

Follow these steps to install the Microsoft Azure Active Directory Module for Windows PowerShell: Open an elevated Windows PowerShell command prompt (run Windows PowerShell as an administrator). Run the Install-Module MSOnline command. If you're prompted to install the NuGet provider, type Y and press Enter.


2 Answers

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 -MsAccessToken $graphToken
like image 197
Makram Avatar answered Dec 28 '22 23:12

Makram


@Makram's answer is good for the AzureRM module.

With the Az powershell module, there is now an easier way:

$context = Get-AzContext
$aadToken = Get-AzAccessToken -ResourceTypeName AadGraph
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id
like image 35
gallivantor Avatar answered Dec 29 '22 00:12

gallivantor