Docker stack deploy ability to pass env variables into the deploy yaml?

I run a docker swarm and i use gitlab ci to do the build and deployment of the images, the biggest headache i face is incrementing the image version numbers in the deployment yaml.

So for example if i do a deploy on gitlab and build the relevant image like this:

docker build --no-cache --platform linux/amd64 -t myregistry/myimage:$CI_COMMIT_TAG -f docker/php-backend/Dockerfile .

I am creating the image version number by using the git tag, which works fine. I then transfer the latest deploy.yaml file to the server and make it run:

sudo docker stack deploy --with-registry-auth -c live-deploy.yaml my-stack-name

The issue here is, inside my live-deploy.yaml i have to manually update the image name with the new version that was built.

Is there a way (and so far i can’t find it) to pass a variable into the yaml from the command line when deploying so it knows what version number to use? A bit like passing in environment variables with docker compose.

>Solution :

You can play with environment variables to acheive this automation. Example follows:

Sample docker-compose/stack file :-

 version: '3.3'
    restart: always
    image: ${MyImageName}
      - 5000:5000

And when you want to deploy something pass env value along with the imperative command… your command modifies to :-

MyImageName=myregistry/myimage:$CI_COMMIT_TAG docker stack deploy --with-registry-auth -c live-deploy.yaml my-stack-name

You can even keep the image name constant and just have a variable just for the tag if that is the degree of automation required.

Leave a Reply