Home > Software engineering >  How do I connect to Azure through PowerShell Modules, using the Service principal of a Registered Ap
How do I connect to Azure through PowerShell Modules, using the Service principal of a Registered Ap

Time:01-04

I need to create a powershell script that queries Azure Resources. What I have is an App Registration.

App Registrations give us the following information:


    # --- APP REGISTRATION OUTPUT
    # appId = "***** APP ID *******"
    # displayName = "**** APP Name **** "
    # password = "***** SECRET *******"
    # tenant = "**** TENANT ID *****"

I need to use these credentials to now access Azure via PowerShell script.

I have tried the following:

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential

But I get an error:

 … Account -ServicePrincipal -TenantId $TenantId -Credential $Credential
     |  ~~~~~~~~~~~
     | Cannot bind argument to parameter 'Credential' because it is null.

I don't think what Im doing is abnormal. App Registrations give us the ability to allow Apps (PowerShell Apps!) to interact with a given tenant. Or am I mistaken?

I don't want the app to login every time using an account (i.e. To have a browser window open whenever the script runs).

What am I doing wrong?

CodePudding user response:

You have missed converting your password into secure string. You could verify that in your $credential variable.

$ApplicationId = "0000-0000-0000-0000"
$Password = "000000000000000"
$TenantId = "0000-0000-000-000"
$subscriptionId = "0000-0000-0000-0000"
$SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential
$sub = Get-AzSubscription -SubscriptionId $subscriptionId
Set-AzContext -Subscription $sub

CodePudding user response:

I have reproduced in my environment and below script worked for me :

$appId ="53f3ed85-70c1c2d4aeac"   
$pswd="55z8Q~_N9SRajza8R"  
$t = "72f988bf-cd011db47"
[ValidateNotNullOrEmpty()]$pswd="55z8BU4oik.kVrZWyaK8R" $sp = ConvertTo-SecureString -String $pswd -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $appId, $sp
Connect-AzAccount -ServicePrincipal -TenantId $t -Credential $Credential

Output:

enter image description here

You need to convert the secret value(password) into secured password like above, then it will work as mine worked.

  • Related