It's so easy - backup build and release definitions from VSTS using Azure Functions

When working with build and release definitions in VSTS we're blessed with the possibility to check audit logs, what was changed, when and by who. This - together with proper permissions setup - allow proper access management and easy rollback if something was misused. Unfortunately VSTS lacks an easy way to export those definitions so we can backup them or version in our repository. In this post I'll show you a quick way to schedule daily backups using Azure Functions.

Prerequisities

To perform actions from this post you'll need Visual Studio 2017 15.3 with Azure Functions SDK installed. Since those tools are no longer in preview, I no longer use CSX to create examples and proofs of concepts. I strongly advise you to update to the latest VS version so you can take the most from the new SDK.

What is more you'll need also a personal access token(PAT) from VSTS. Please read this article if you haven't for an idea how to get it.

Creating functions

To be able to schedule our backup, we'll need two functions. Both we'll be triggered by a timer and both will upload a blob to a Blob Storage container. Here's our infrastructure needed:

ARM template visualization created by ARMata

As you can see this is the basic infrastructure needed to be able to use Functions, which can be easily set up in Azure Portal. Once we have required components provisioned, we can prepare code, which will create backups.

In VS when you go to Create project wizard, you'll see a window with available templates. When you go to the Cloud tab you should see Azure Functions template ready to be created:

Once a project is created right-click on it, to to Add menu and select New item:

From the available positions select Azure Function and click Add. You'll see plenty of different function templates, from which we have to choose Timer trigger. Change the schedule to 0 0 0 */1 * * so it will be triggered once a day and click Ok.

Creating a backup

To create a backup we'll use once more VSTS REST API. Here are endpoint, which we'll use here:

They return JSON definitions, which can be easily stored and versioned. The actual code for creating a build definition backup looks like this:

/
public static class BuildBackup
{
	private const string Personalaccesstoken = "PAT";

	[FunctionName("BackupBuild")]
	public static async Task Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, [Blob("devops/build.json", FileAccess.Write)] Stream output, TraceWriter log)
	{
		try
		{
			using (var client = new HttpClient())
			{
				client.DefaultRequestHeaders.Accept.Add(
					new MediaTypeWithQualityHeaderValue("application/json"));

				client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
					Convert.ToBase64String(
						System.Text.Encoding.ASCII.GetBytes(
							string.Format("{0}:{1}", "", Personalaccesstoken))));

				using (var response = await client.GetAsync(
					$"https://{instance}.visualstudio.com/DefaultCollection/{project}/_apis/build/definitions?api-version=2.0")
				)
				{
					var data = await response.Content.ReadAsAsync<JObject>();
					foreach (var pr in data.SelectToken("$.value"))
					{
						var id = pr.First.SelectToken("$.id");
						using (var release = await client.GetAsync(
							$"https://{instance}.visualstudio.com/DefaultCollection/{project}/_apis/build/definitions/{id}?api-version=2.0")
						)
						{
							release.EnsureSuccessStatusCode();
							var releaseData = await release.Content.ReadAsStringAsync();
							var bytes = Encoding.UTF8.GetBytes(releaseData);
							await output.WriteAsync(bytes, 0, bytes.Length);
						}
					}
				}
			}
		}
		catch (Exception ex)
		{
			log.Info(ex.ToString());
		}
	}
}

To create a backup of a release definition you can use following function:

/
public static class ReleaseBackup
{
	private const string Personalaccesstoken = "PAT";

	[FunctionName("BackupRelease")]
	public static async Task Run([TimerTrigger("0 0 0 */1 * *")]TimerInfo myTimer, [Blob("devops/release.json", FileAccess.Write)] Stream output, TraceWriter log)
	{
		try
		{
			using (var client = new HttpClient())
			{ 
				client.DefaultRequestHeaders.Accept.Add(
					new MediaTypeWithQualityHeaderValue("application/json"));

				client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
					Convert.ToBase64String(
						Encoding.ASCII.GetBytes(
							string.Format("{0}:{1}", "", Personalaccesstoken))));

				using (var response = await client.GetAsync(
					"https://{instance}.vsrm.visualstudio.com/{project}/_apis/Release/definitions")
				)
				{
					var data = await response.Content.ReadAsAsync<JObject>();
					foreach (var pr in data.SelectToken("$.value"))
					{
						var id = pr.First.SelectToken("$.id");
						using (var release = await client.GetAsync(
							$"https://{instance}.vsrm.visualstudio.com/{project}/_apis/Release/definitions/{id}")
						)
						{
							release.EnsureSuccessStatusCode();
							var releaseData = await release.Content.ReadAsStringAsync();
							var bytes = Encoding.UTF8.GetBytes(releaseData);
							await output.WriteAsync(bytes, 0, bytes.Length);
						}
					}
				}
			}
		}
		catch (Exception ex)
		{
			log.Info(ex.ToString());
		}
	}
}

Some details:

  • I used a blob container named devops  - of course you can use any name you like
  • Unfortunately there's no way to combine those two functions(as long as you'd like to use different blob for holding build and release definitions)
  • You can easily version those JSON definitions by - instead of storing them in Blob Storage - calling a VSTS REST API for a repository and uploading a blob there

You shall not push - branch policies in VSTS

When working on a codebase with a team, you always want to make sure, that everything is kept clean and works smoothly. You have git-flow, you have code reviews - they ensure, that everyone can work without impacting others and the main branch is secured. There's one issue however - by default you cannot force team members to go through the whole process - creating a feature branch, pull request, code review. Fortunately VSTS allows you to set a branch policy, which will ensure, that no one breaks the rules.

Setting a branch policy

TO set-up a branch policy just go to Code->Branches page. Choose whichever branch you want and select Branch policies item.

You'll see a page, where you can choose to protect this particular branch. When you select the checkbox, you'll see different options to make sure it is secured. We'll go through each one to get a basic understanding what it gives us.

Minimum number of reviewers

It allows us to define what is the minimum number of reviewers to actually complete a pull request. What is important here is Allow users to approve their own changes checkbox - if you want to force, that someone has reviewed a PR, make sure it is not checked!

Check for linked items

Useful when working with VSTS issue tracker. Allows you to block a PR if a work item hasn't been linked to it.

Check for comment resolution

My favorite. Forces an author of a PR to make sure, that each comment has been reviewed and accepted. 

Build validation

Allows you to link a build definition to queue a build for a PR to make sure, that feature branch passes through the whole pipeline. No more broken builds!

Results

When a branch policy is set, let's try to do following thing - push a commit directly to a develop branch(or any other branch which is protected) and complete a pull request.

Pushing a commit directly to the protected branch will result in an error

In this case both build and approvals weren't finished

Summary

As you can see in VSTS you can easily set a branch policies, which will help you secure your main branch from broken features. What is more, they will ensure you, that each team member follows the same process and no change can affect other team members.