A previous post of mine Connecting to Azure Devops with a Service Principal has been popular since I have written it. Therefore, I’ve decided to extend on the topic and show how you can do it programatically with AZ DevOps.
You will need a few things already configured:
- Create a Service Principal*
- Create a Service Principal secret*
- Create a DevOps Personal Access Token (PAT) (See below)
* See code in the powershell folder from the post on https://cann0nf0dder.wordpress.com/2020/09/14/app-only-auth-connect-to-sharepoint-online-with-msal-and-azure-keyvault/ to see how you can create this programatically.
Create a DevOps PAT token
- Go to your Azure devops https://dev.azure.com
- Sign in and click on User settings -> Personal access tokens
- Click New Token
- Give it a meaningful name so you know what the PAT token is for in the future. (E.g, Devops Service Connection)
- Select your Organization
- Select the Expiration date for as long as you need. Maximum 1 Year
- Select Scopes at Full access (You might want to tighten your permission in a production environment, for this demo Full access is fine).
- Click Create
- Once you have clicked Create this is the only chance to grab a copy of the token. Please take a copy of this token as you will require it later.
You will need to first be logged into Az Cli. You can sign in using a service principal as you might with a pipeline, as long as the account being used is able to list App Registrations, and ‘User Access Administrator’ RBAC role to be able to apply contribute access to the DevOps service principal on the subscription (Line 43) .
The important part to note in the code is how the authentication works with Devops. The Personal Access Token is added to the $Env: variable “AZURE_DEVOPS_EXT_PAT”. (Line 32)
To run the above code, you will need to put in your parameters. Replace with your values then run the script, this will call the script above.
My team project is called AutomateDevOps, and I used an App Registration called DevOps.
My next blog post explains how do make a Management Group Service Connection instead of a Subscription level. ‘Programmatically connecting to Azure Devops with a Service Principal (Management Group)‘