-
Notifications
You must be signed in to change notification settings - Fork 215
Description
reading this
they provide a managed identity section
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/service-principal-managed-identity?view=azure-devops#configure-managed-identities-and-service-principals
which links to a .NET implementation
in which they pass in a managed identity into a VssCredential object
https://github.com/microsoft/azure-devops-auth-samples/blob/9097287405fde466a745dfb94c2dcaf0860a79e9/ServicePrincipalsSamples/ClientLibsNET/3-AzureFunction-ManagedIdentity/TestMIHttpTrigger.cs#L78C9-L87C10
private static VssConnection CreateVssConnection()
{
var credentials = new VssAzureIdentityCredential(credential);
var settings = VssClientHttpRequestSettings.Default.Clone();
settings.UserAgent = AppUserAgent;
var organizationUrl = new Uri(new Uri(AdoBaseUrl), AdoOrgName);
return new VssConnection(organizationUrl, credentials, settings);
}
In the repos example docs on main README, its assumed we are working with a PAT Token.
Is there a reference sample available for working with managed identity/ service principals, when inside say, an azure web app? (Avoiding creating PAT)
otherwise I will attempt to do it avoiding the library altogether just with API call
import requests
from azure.identity import ManagedIdentityCredential
import base64
# Azure DevOps organization and project details
organization = "your_organization" # Replace with your Azure DevOps organization name
project = "your_project" # Replace with your Azure DevOps project name
repository = "foo" # Your repository name
file_path = "README.md" # Path to the Markdown file in the repository
api_version = "7.1" # Azure DevOps API version
# Managed Identity client ID (for user-assigned managed identity; omit for system-assigned)
# Replace with your user-assigned managed identity client ID, if applicable
client_id = "your_managed_identity_client_id" # Optional: only for user-assigned identity
# Azure DevOps scope for authentication
scope = "499b84ac-1321-427f-aa17-267ca6975798/.default"
try:
# Initialize ManagedIdentityCredential
# Use client_id for user-assigned managed identity; omit for system-assigned
credential = ManagedIdentityCredential(client_id=client_id) if client_id else ManagedIdentityCredential()
# Get access token for Azure DevOps
token = credential.get_token(scope).token
# Construct the Azure DevOps REST API URL to get file content
url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}/items?path={file_path}&api-version={api_version}"
# Set headers for the API request
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/json"
}
# Make the API request to get the file content
response = requests.get(url, headers=headers)
# Check if the request was successful
response.raise_for_status()
print("got response")
print(response)
except Exception as e:
print(f"Error: {str(e)}")