Search code examples
dockerazure-devopsazure-pipelinesazure-pipelines-yaml

Azure pipelines Docker@2 containerRegistry


In azure pipelines, I have a variable that's declared as follows

variables:
  - name: acr_svc_conn

In my pipeline, I set this value as shown

- bash: |
    echo "##vso[task.setvariable variable=acr_svc_conn;]$ACR"

When I try to use this in my Docker@2 task as shown

- task: Docker@2
  inputs:
    containerRegistry: '$(acr_svc_conn)'
    command: 'login'
  displayName: Login to ACR

I get this error

##[error]Docker registry service connection not specified.
##[error]Unhandled: Docker registry service connection not specified.

Any thoughts? I've tried combinations of ${{ variable.acr_svc_conn }} and variables['acr_svc_conn'] and nothing has worked. Of course, when I hardcode the connection name it works, but I'd like to see if it can be done dynamically.


Solution

  • Service connections are protected resources, i.e. only specific users and pipelines within the project can access them. This means their values must be known at compile time, so that the service connections can be authorized (or not) before a specific pipeline runs.

    Having said that, you won't be able to change the value of a variable used as a service connection after the pipeline starts like this:

    echo "##vso[task.setvariable variable=acr_svc_conn;]$ACR"
    

    And the error you're getting makes sense if variable acr_svc_conn is empty by default:

    ##[error]Docker registry service connection not specified.
    ##[error]Unhandled: Docker registry service connection not specified.
    

    Workaround

    Specify all the possible values for the service connections in variables and/or variable templates and then use template expressions to get/set the right variables or template.

    Example:

    parameters:
      - name: azureRegion
        displayName: 'Azure Region'
        type: string
        default: eastus
        values:
          - eastus
          - westeurope
    
    variables:
      - template: /pipelines/variables/${{ parameters.azureRegion }}-variables.yaml
    
    steps:
      - task: Docker@2
        inputs:
          containerRegistry: '${{ variables.acr_svc_conn }}'
          command: 'login'
        displayName: Login to ACR
    
      # other tasks here
    

    /pipelines/variables/eastus-variables.yaml

    # East US specific variables
    
    variables:
      - name: acr_svc_conn
        value: my-eastus-container-registry
      
      # other variables
    

    /pipelines/variables/westeurope-variables.yaml

    # West-Europe specific variables
    
    variables:
      - name: acr_svc_conn
        value: my-westeurope-container-registry
      
      # other variables