How to: Viewing which repositories have branch policies on Azure DevOps
Learn how you use Azure DevOps CLI to extract branch policies of each of the Azure DevOps repositories
Every time we create a repository on Azure DevOps, we can apply Branch Policies on these repositories. Over time and with a large number of repositories, it becomes increasingly difficult to verify that all these repositories have the same policies applied.
Thinking about it, I decided to create one script using Azure DevOps CLI that extracts this information about each repository on our organization and I exposed them on PowerBI. To do this, I used again PowerShell to automate this procedure (see original GitHub repository here):
In this script, I’ve used commands below:
- PowerShell script will receive the following parameters:
- $PAT = Personal Access token to connect on Azure DevOps;
- $Organization = Organization URL to list all branches and policies.
2. az devops project list = use this command to list all projects on the organization
$ProjectsResult = az devops project list --org $Organization | ConvertFrom-Json
Foreach ($project in $ProjectsResult.value)
{
Write-Host $project.id
}
3. az repos list = use this command to list all repositories from each project
$ReposResult = az repos list --org $Organization --project $project.id | ConvertFrom-Json
Foreach ($repo in $ReposResult)
{
Write-Host $repo.id
}
4. az repos policy list = use this command to list all policies that are applied from each repository
$ReposPolicyResult = az repos policy list --branch $repo.defaultBranch --org $Organization --project $project.id --repository-id $repo.id | ConvertFrom-Json
Foreach ($repoPolicy in $ReposPolicyResult)
{
Write-Host $repoPolicy.type.displayName
}
At the end of the script, I just created a JSON that contains all information about repositories and their respective policies. The example below show the same:
{
"RepositoryId": "[Repository ID]",
"RepositoryDefaultBranchRequiredReviewers": true,
"RepositoryDefaultBranchCommentRequirements": true,
"TeamProjectName": "[Team Project Name]",
"TeamProjectId": "[Team Project Id]",
"RepositoryDefaultBranchWorkItemLinking": true,
"RepositoryURL": "[Repo URL]",
"RepositoryDefaultBranch": "refs/heads/master",
"RepositoryName": "WorkItemDeployment",
"RepositoryDefaultBranchBuild": true,
"RepositoryDefaultBranchMinimumNumberOfReviewers": true
}
After that, I connected this JSON on PowerBI to show information about repositories and policies:
This report brings five different branch policies:
- Require a minimum number of reviewers
- Automatically include code reviewers
- Check for comment resolution
- Build validation
- Check for linked work items
Using a stacked column chart, I can identify which repositories have (or not) each of the policies listed above. Viewing the problem in a single repository, I can apply the missing policies, thus establishing the same validations for my entire organization.