How to dynamically override Docker's 'containerRegistry' attribute in Azure Pipeline?

Viewed 367

In my Azure Build Pipeline, I'm trying to override the container registry to push the Docker image depending on the environment I'm deploying to. To do so, I created a variable which is given a value in a PowerShell script (i.e. the environment to which I deploy). After that, I use that variable to override the container registry in a Docker step.

The problem is, even though the variable is correctly set, the container registry isn't overridden. So the Docker step uses the default registry which is not recognized as a service connection in Azure DevOps.

Here are the concerned steps in azure-pipeline.yml and the output of Docker Push step:

PowerShell script to calculate $registry variable

- powershell:
    if( $env:BUILD_SOURCEBRANCHNAME.Equals("develop") )
    {
      Write-Host "##vso[task.setvariable variable=registry]Docker Dev";
    }
    elseif ( $env:BUILD_SOURCEBRANCHNAME.Contains("release") )
    {
      Write-Host "##vso[task.setvariable variable=registry]Docker Staging";
    }
  displayName: 'Set environment configuration'

Docker push step

- task: Docker@2
  displayName: 'push API image to azure registry'
  inputs:
    containerRegistry: '$(registry)'
    repository: 'api.admin'
    command: 'push'
    tags: '$(version)'

Output

The push refers to repository [docker.io/library/api.admin]
2dce5cb1fcef: Preparing
3dac20cd9e05: Preparing
bc6688385ca5: Preparing
e5b3b5565ba6: Preparing
41c7377e2f9c: Preparing
06b99a66c400: Preparing
13cb14c2acd3: Preparing
06b99a66c400: Waiting
13cb14c2acd3: Waiting
denied: requested access to the resource is denied
##[error]denied: requested access to the resource is denied
##[error]The process '/usr/bin/docker' failed with exit code 1

Do you know if there is a way to dynamically override container registry in a Docker step in an Azure Pipeline?

1 Answers

I'd probably do something like this:

  1. remove powershell script step
  2. add another docker step
  3. add conditions to docker steps:
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/develop') }}:
docker 1 task

${{ if eq(variables['Build.SourceBranch'], 'refs/heads/release') }}:
docker 2 task

this way you can basically hardcode the registry, but only execute the step that is meant for that specific branch.

variables:
  ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/develop') }}:
    registry: regA
  ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/release') }}:
    registry: regB
Related