Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (29.3k points)

I want to add a volume to my service, but only if the final user gave a folder for it. Otherwise, no volume should be mounted, for the already-prepared image has valid data in a default folder.

That is, I want to do something like; pseudocode:

services:

  my_awesome_service:

    volumes:

      if ${VARIABLE} => ${VARIABLE}:/app/folder

Is establishing such a conditional statement doable and definable in a docker-compose file? The only way I see to make this possible is to first define a base docker-compose file, which does not have the volume mount, and the call on a second docker-compose file only if the $VARIABLE is defined. This is fine for a single or few conditions but gets nasty if there are many.

Any solution?

1 Answer

0 votes
by (50.2k points)

I don’t think the docker compose format will support conditional statements.

But to resolve the issue we have 2 approaches

Pass a list-like variable to the docker compose like this

docker-compose.yaml:

command: ${COMMAND_PARAMS}

bash:

#!/bin/bash

if test -z $CONDITION; then

  params="-param1 ${MIPARAM1}"

else

  params="-param1 ${MIPARAM1} -param2 ${MIPARAM2}"

fi

COMMAND_PARAMS=$params docker-compose up

Then it will help you to resolve the problem or else you can also use this way. 
second approach
Prepare the default folder in the docker image in a folder named something like folder_defaults, then have the volume always defined in docker-compose.yml. But we have a final script which checks the docker image that checks whether the volume folder is empty. If it is empty then ln -s to the folder_defaults; otherwise, leave it as it is.
Example:-
if [ -z "$(ls -A /a/folder)" ]; then
  do something... using /a/folder_defaults
fi
In these two ways, you can solve this problem.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...