Home > Software engineering >  How to inject a secret variable into a Docker container inside an Azure DevOps pipeline?
How to inject a secret variable into a Docker container inside an Azure DevOps pipeline?

Time:12-09

So I've managed to finally get my Docker container running inside my Azure DevOps pipeline using below command. However I need access to a protected secret variable that I store in a variable library in Azure DevOps. This is a constant tripping point for me. Protected variables are just treated differently, this also happens when using them as env vars inside scripts.

This is my inline script to start my container:

  - task: Bash@3
    inputs:
      targetType: 'inline'
      script: |
        #!/bin/bash
        docker run --rm --name ${BUILD_BUILDNUMBER} --env RTF_API_KEY=$API_KEY \
        --mount type=bind,source="$BUILD_SOURCESDIRECTORY",target="/root/" \
        ${REGISTRY_ENDPOINT}/${REGISTRY_PATH}/${{variables.image}}:${{variables.tag}} /root/build_scripts/my-script.sh

Everything works fine, except for when I try downloading something from my local Artifactory server, I kept getting an unauthorized response. I assumed that the variable RTF_API_KEY was missing or empty, so I temporarily "unprotected" the variable and it worked straight away.

So the question is, how can I inject a protected variable into my container? I know it is possible to hand over a variable file to Docker, but I'm trying to avoid that.

Any suggestion greatly appreciated!

CodePudding user response:

Secret variables are encrypted at rest with a 2048-bit RSA key. Secrets are available on the agent for tasks and scripts to use.

Unlike a normal variable, they are not automatically decrypted into environment variables for scripts. You need to explicitly map secret variables. Refer to this doc.

That's the reason for

I kept getting an unauthorized response.

To resolve this, you need to map the secret variable.

Modify your script as below:

task: Bash@3
  inputs:
    targetType: 'inline'
    script: |
      #!/bin/bash
              docker run --rm --name ${BUILD_BUILDNUMBER} --env RTF_API_KEY=$API_KEY \
              --mount type=bind,source="$BUILD_SOURCESDIRECTORY",target="/root/" \
              ${REGISTRY_ENDPOINT}/${REGISTRY_PATH}/${{variables.image}}:${{variables.tag}} /root/build_scripts/my-script.sh
            env:
             API_KEY: $(API_KEY) # the recommended way to map to an env variable
  • Related