Posted on Leave a comment

Pass secrets as ENV variables on docker build – Azure devops

Sometimes you may need not to store your environmental variables on your Dockerfile as they could contain secret values. Especially when using source control you do not want to commit your .env files that they may contain secrets and other sensitive information.

Using the below procedure you can inject secret values as ENV variables on your Dockerfile during the build. Its important to know that you cannot use –env-file with docker build command as it be only used with docker run.

docker run | Docker Documentation

docker build | Docker Documentation

On docker build you can pass –build-arg values in order to set build-time variables. These values don’t persist in the intermediate or final images like ENV values do. You must add --build-arg for each build argument.

In my scenario I wanted to commit an ENV variable permanently on the image but I wanted to avoid storing this value on source control. In more details I wanted to have the APP_KEY as ENV variable inside the container.

The first step was to set this as a secret on the Azure Devops pipeline.

Then you will need to create an ARG definition on the Dockerfile which value will be taken from the Devops pipeline run. Then this value will be passed to the ENV variable APP_KEY.

ARG APP_KEY
ENV APP_KEY=$APP_KEY

In the Docker command you will need to pass as –build-arg the values that you need (in my case APP_KEY)

    - task: Docker@2
      displayName: build docker image
      inputs:
        containerRegistry: 'registry'
        command: 'build'
        Dockerfile: '$(Pipeline.Workspace)/s/myapp/docker/Dockerfile'
        buildContext: '$(Pipeline.Workspace)/s/myapp'
        arguments: '-t image.azurecr.io/app-uat:${{parameters.dockertag}} --build-arg APP_KEY=$(APP_KEY)'
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.