How to use the checkout keyword with dynamic parameters in Azure pipelines

When working with Azure Pipelines, the checkout keyword is typically used to reference a Git repository with a fixed name. For example in your Azure Pipeline you will add the following line:

- checkout: git://MyProject/MyRepository

While this works well for static scenarios, what if you’re working with multiple repositories? For instance, when automating tasks that iterate over a list of repositories, hardcoding each repository name becomes inefficient and error-prone.

Azure Pipelines offer a flexible solution to make repository names dynamic.

Dynamically specify the repository name

You can dynamically specify the repository name by using the value of a Pipeline parameter:

- checkout: git://MyProject/$

This makes the repositoryName a variable, allowing you to set its value dynamically. But what if you need to process multiple repositories? Let’s configure your Pipeline to make that possible.

Defining a list of repository names as defaults for the parameter

At the beginning of the Pipeline file you can define a list of repository names as default values to the new parameter. The type should be object since the default values form an array:

parameters:
    - name: repositoryNames
      type: object
      default:
        - repository1
        - repository2
      displayName: "The name of the repository"

Iterating through repositories in a loop

With the parameterized list in place, you can use a for loop to iterate over the repository names and dynamically set the checkout parameter for each repository by using an iteration with the each keyword. Here’s an example of how to do this:

jobs:
  - job: CheckoutRepositories
    displayName: "Checkout multiple repositories"
    steps:
      - $:
          - checkout: git://MyProject/$

I hope this will be useful to some of my readers :)

comments powered by Disqus