Search code examples
powershellazure-devopsyaml

Azure DevOps YAML Pipelines - Scheduled Trigger Parameters


In Azure DevOps YAML pipelines, you can create scheduled triggers. However, can each schedule have its own set of parameter values? Such a thing could maybe look like this:

parameters:
- name: myParam
  displayName: My Parameter
  type: string
  default: option-a
  values:
  - option-a
  - option-b

schedules:
- cron: "0 5 * * *"
  displayName: "Midnight CT Daily"
  branches:
    include:
    - master
  parameters:
  - myParam: option-b
  always: true

Solution

  • Unfortunately, the YAML schema for the schedules.cron object does not have any properties that allow input of specific parameters.

    https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/schedules?view=azure-pipelines

    https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/schedules-cron?view=azure-pipelines

    However, I was able to get around this issue by leveraging the display name of the schedules. From there, you can leverage PowerShell or Bash to read the $(Build.CronSchedule.DisplayName) variable and use that as input instead. You could even delimit this value to parse out multiple values.

    parameters:
    - name: food
      type: string
      default: roast-beef
      values:
      - apple
      - banana
      - roast-beef
      - yogurt
    
    schedules:
    - cron: "0 5 * * *"
      displayName: "apple"
      branches:
        include:
        - master
      always: true
    - cron: "0 7 * * *"
      displayName: "banana;yogurt"
      branches:
        include:
        - master
      always: true
    
    stages:
    - stage: mealtime
      jobs:
      - deployment: snack
        environment: kitchen
        strategy:
          runOnce:
            deploy:
              steps:
              - pwsh: |
                  $targetFoods = @("${{ parameters.food }}")
                  
                  if ("$(Build.Reason)" -eq "Schedule") {
                    $targetFoods = "$(Build.CronSchedule.DisplayName)".Split(";")
                  }
                  
                  Write-Host "Foods to eat: $targetFoods"
                  Write-Host "##vso[task.setvariable variable=foods;]$targetFoods"
                displayName: Set Variables
    
              - pwsh: |
                  $(foods) | ForEach-Object { Write-Host "Eating: $_"; $_ | Eat-PsFood }
                displayName: Eat Food