Search code examples
azuredockerazure-devopsyamlcicd

Custom BuildNumber to be used in docker task in Azure Devops pipeline


In my main pipeline I defined the BuildNumber/Build Name of the pipeline run:

name: $(Date:yyyyMMdd).$(Rev:r)_Bugfix_for_workitem_$(work_item)
appendCommitMessageToRunName: false


Then I used this template 
steps:         
    - ${{ if ne(parameters.ContainerRegistry, '') }}:
        - task: Docker@2
          displayName: 'Docker Build'
          inputs:
              command: build
              containerRegistry: ${{parameters.ContainerRegistry}}
              dockerfile: ${{parameters.DockerFile}}
              buildContext: $(Build.SourcesDirectory)
              repository: ${{parameters.Repository}}
              arguments: --build-arg FEED_ACCESSTOKEN=$(VSS_NUGET_ACCESSTOKEN)
              tags: |                
                  latest
                  $(Build.BuildNumber) --- #This is working
                  echo "$(echo $(Build.BuildNumber) | cut -d'_' -f1)"  --- Not working , ##[error]ERROR: invalid tag "***.azurecr.io/:echo \"$(echo 20231116.1_Generic_for_workitem_$(work_item) | cut -d'_' -f1)\"": invalid reference format

In the third tag, my goal is to only extract the Date and revision number like 20231116.1 and strip the remaining names Bugfix_for_workitem$(work_item) and use it as a tags in the docker task.

The problem is that seems like the docker task cannot execute directly a shell command. If I use this line in a shell command or task, its able to strip of the name. echo "$(echo $(Build.BuildNumber) | cut -d'_' -f1)"


Solution

  • From looking at the input tags in the Docker@2 task, the Default Value is $(Build.BuildId). I am afraid that the tag should be a string rather than shell command.

    If you want to custom tag, you can set variables in scripts and then use it in the following docker task.

    example

    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          echo "##vso[task.setvariable variable=customBuildNumber;]"$(echo $(Build.BuildNumber) | cut -d'_' -f1)""
    
    - task: Docker@2
              displayName: 'Docker Build'
              inputs:
                  command: build
                  containerRegistry: ${{parameters.ContainerRegistry}}
                  dockerfile: ${{parameters.DockerFile}}
                  buildContext: $(Build.SourcesDirectory)
                  repository: ${{parameters.Repository}}
                  arguments: --build-arg FEED_ACCESSTOKEN=$(VSS_NUGET_ACCESSTOKEN)
                  tags: |  
                    $(customBuildNumber)              
    

    Hope it can help.