Automate Connect-AzureAD using powershell in Azure Devops

别说谁变了你拦得住时间么 提交于 2020-06-11 09:06:33

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/60185213/automate-connect-azuread-using-powershell-in-azure-devops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!