5

I want to use Azure Pipelines to build a Docker image, then run tests inside the built image with a container job.

The image should use the build id as the tag (or a combination of the build id, commit hash and branch name). If I used a static tag as value (e.g. build), having two two pipelines run in parallell could result in an unwanted race condition.

The build step is easy enough - login, build and push to Docker Hub.

However, when specifying the test job to use a container, I'm unable to use a variable.

Here is an example that works, but it doesn't use a private registry.

variables:
  - group: dockerCredentials
    # contains: dockerUsername, dockerPassword
  - name: imageName
    value: azure-pipelines-test
  - name: dockerRegistry
    value: krsb
  - name: fullImageName
    value:

jobs:
- job: build
  pool:
    vmImage: 'Ubuntu-16.04'
  steps:
  - script: |
      docker login -u $(dockerUsername) -p $(dockerPassword)
      docker build -t '$(dockerRegistry)/$(imageName):$(build.buildId)' .
      docker push '$(dockerRegistry)/$(imageName):$(build.buildId)'
    displayName: 'docker build'

- job: test
  dependsOn:
  - build
  pool:
    vmImage: ubuntu-16.04
  container:
    image: $[ format('{0}/{1}:{2}', variables['dockerRegistry'], variables['imageName'], variables['build.buildId']) ]
    endpoint: docker-hub-registry
  steps:
  - script: printenv

If I want to use a private registry, I don't specify container as a string, but use this syntax instead (Docker hub credentials is specified in the endpointยน):

# ...
  container:
    image: image-name:tag
    endpoint: docker-hub-registry

When I use this syntax, I cannot use the $[ variables['name'] ] syntax, this is not expanded and when the pipeline runs it outputs an error:

##[command]/usr/bin/docker pull $[ format('{0}:{1}', variables['imageName'], variables['build.buildId']) ]
"docker pull" requires exactly 1 argument.

Same goes if I use $(imageName):$(build.buildId).

Is it possible to use a variable in the image name?

  • I tested this pipeline and it works perfectly well - for docker hub and for private ACR. What private registry are you using? Also, in build job, you're using `docker login` directly and in test job you're using `docker-hub-registry` Service Connection - make sure they match and the pipeline tries to pull the image from the same registry it was pushed to. โ€“ qbik Apr 20 '21 at 04:13
  • This question was posted a couple of years ago, so it might be that this has been implemented. I am not using Azure DevOps now so I don't have any way to test that. If it works, then good โ€“ I do believe it's a feature that can speed up a pipeline. โ€“ Kristoffer Bakkejord Apr 22 '21 at 13:45

0 Answers0