Skip to content

Instantly share code, notes, and snippets.

@timothywarner
Created April 17, 2019 14:38
Show Gist options
  • Save timothywarner/089fdbc4a39fee3143011d57f10c4745 to your computer and use it in GitHub Desktop.
Save timothywarner/089fdbc4a39fee3143011d57f10c4745 to your computer and use it in GitHub Desktop.
Automate Azure PowerShell login with a service principal and self-signed certificate
$cert = New-SelfSignedCertificate -CertStoreLocation "cert:\CurrentUser\My" `
-Subject "CN=psauth1" `
-KeySpec KeyExchange
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
$sp = New-AzADServicePrincipal -DisplayName 'psauth1' `
-CertValue $keyValue `
-EndDate $cert.NotAfter `
-StartDate $cert.NotBefore
Start-Sleep -Seconds 20
New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId
$TenantId = (Get-AzSubscription -SubscriptionName "Microsoft Azure Sponsorship").TenantId
$ApplicationId = (Get-AzADApplication -DisplayNameStartWith psauth).ApplicationId
$Thumbprint = (Get-ChildItem cert:\CurrentUser\My\ | Where-Object { $_.Subject -eq "CN=psauth1" }).Thumbprint
Connect-AzAccount -ServicePrincipal `
-CertificateThumbprint $Thumbprint `
-ApplicationId $ApplicationId `
-TenantId $TenantId
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment