skip to Main Content

I have a CI/CD pipeline on Azure. I have set up a .yaml file and a variable called SerialNumber, set to 000000 directly in the Azure interface (not in the .yaml). I want it to be used inside of the pipeline and the updated, adding 1 on every iteration.

The .yaml looks like this:

variables:
  myPipelineVariable: $[variables.SerialNumber]

jobs:

- job: Update_Variable
  timeoutInMinutes: 0
  steps:
  - task: PowerShell@2
    name: "task1"
    displayName: this is task1
    inputs:

      targetType: 'inline'
      script: |
        echo "the value of the variable is : $(myPipelineVariable)"
        $newValue = [int]$(myPipelineVariable) + 1
        $formattedValue = "{0:D6}" -f $newValue  # Format the number with leading zeros
        Write-Host "##vso[task.setvariable variable=myPipelineVariable;isOutput=true]$formattedValue"
    enabled: true

the problem is if i save and run the pipeline the number in the Azure interface then doesn’t change, and the next time starts from 000000 again. I also tried inserting another job in the .yaml:

- job: Show_Variable
  timeoutInMinutes: 0
  steps:
  - task: PowerShell@2
    name: "task2"
    displayName: this is task2
    inputs:

      targetType: 'inline'
      script: |
        echo "the new value of the variable is : $(myPipelineVariable)"
    enabled: true

but it prints: 000000

how can i handle this operation to update the value of the variable inside of Azure, so that every build that i trigger uses it and then adds one to the number automatically?

2

Answers


  1. You cannot change variable that way. It will be only for execution and won’t be persisted.

    But the thing which you are looking for is a counter expression

    You can create a counter that is automatically incremented by one in each execution of your pipeline. When you define a counter, you provide a prefix and a seed. Here is an example that demonstrates this.

    variables:
      major: 1
      # define minor as a counter with the prefix as variable major, and seed as 100.
      minor: $[counter(variables['major'], 100)]
    
    steps:
    - bash: echo $(minor)
    

    Take a look on the documentation here

    Login or Signup to reply.
  2. Check this doc about variables in different jobs: Use outputs in a different job. Add a variable definition to the second job:

    - job: Show_Variable
      timeoutInMinutes: 0
      variables:
        # map the output variable from A into this job
        myPipelineVariable: $[ dependencies.Update_Variable.outputs['task1.myPipelineVariable'] ]
      steps:
      - task: PowerShell@2
        name: "task2"
        displayName: this is task2
        inputs:
    
          targetType: 'inline'
          script: |
            echo "the new value of the variable is : $(myPipelineVariable)"
        enabled: true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search