PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,607 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I want to add SPN to Azure DevOps Service Connection through Powershell automation
You can add a service connection using the powershell script that uses the REST API 'Endpoints - Create' to create service connection.
# Parameters for the script
Param(
[string]$AZP_URL = "https://dev.azure.com/your-organization",
[string]$AZP_PROJECT = "your-project",
[string]$AZP_TOKEN = "your-PAT-token",
[string]$AZP_CONNECTION = "your-service-connection-name",
[string]$AZP_SUBSCRIPTION_ID = "your-subscription-id",
[string]$AZP_SUBSCRIPTION_NAME = "your-subscription-name",
[string]$AZP_TENANT_ID = "your-tenant-id",
[string]$AZP_SP_ID = "your-service-principal-id",
[string]$AZP_SP_KEY = "your-service-principal-secret"
)
# Base64-encode the Personal Access Token (PAT)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$AZP_TOKEN"))
# Construct the JSON body for the Azure DevOps service connection
$jsonBody = @"
{
"data": {
"SubscriptionId": "$AZP_SUBSCRIPTION_ID",
"SubscriptionName": "$AZP_SUBSCRIPTION_NAME"
},
"name": "$AZP_CONNECTION",
"type": "azurerm",
"authorization": {
"parameters": {
"tenantid": "$AZP_TENANT_ID",
"serviceprincipalid": "$AZP_SP_ID",
"serviceprincipalkey": "$AZP_SP_KEY"
},
"scheme": "ServicePrincipal"
},
"isReady": true
}
"@
# Azure DevOps REST API URL for creating a service connection
$azureDevOpsServiceConnectionUrl = "$AZP_URL/$AZP_PROJECT/_apis/serviceendpoint/endpoints?api-version=5.1-preview.2"
# Make the REST API call to create the service connection in Azure DevOps
Invoke-RestMethod -Uri $azureDevOpsServiceConnectionUrl -Method POST -Body $jsonBody -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
To learn more about this read the documention:
https://learn.microsoft.com/en-us/rest/api/azure/devops/serviceendpoint/endpoints/create?view=azure-devops-rest-7.1&tabs=HTTP
I hope this helps.