0

Is there a way to set a variable from a file in the docker compose?

The following does not work in compose (however it does if you attach to the container):

version: '2'
services:
  foo:
    image: busybox
    command:
      - /bin/sh
      - -c
      - |
          echo "hello" > id #this file will be supplied by a volume-from
          ls
          cat id
          TEST=$(cat id)   #This line does not work
          echo TEST

The error which is produced is:

ERROR: Invalid interpolation format for "command" option in service "foo":
scipsycho
  • 527
  • 2
  • 4
  • 13
dbones
  • 4,415
  • 3
  • 36
  • 52
  • Docker compose allows env_file and environment keywords. Is this what you want? [Reference docs. ](https://docs.docker.com/compose/compose-file/compose-file-v2/#env_file) – Light.G Oct 13 '18 at 04:53
  • Why have you tagged `bash`? You appear to be using `/bin/sh`, not `bash`. – cdarke Oct 13 '18 at 06:56
  • https://stackoverflow.com/questions/52664673/how-to-get-port-of-docker-compose-from-env-file/52664919#52664919 – lvthillo Oct 13 '18 at 07:19
  • @cdarke i try an use sh instead of bash as not all distro's have bash (alpine uses ash), but they all tend to support sh – dbones Nov 07 '18 at 15:32
  • 1
    Possible duplicate of [How can I escape a $ dollar sign in a docker compose file?](https://stackoverflow.com/questions/40619582/how-can-i-escape-a-dollar-sign-in-a-docker-compose-file) – kenorb Feb 16 '19 at 13:47

1 Answers1

1

you have to change a bit your config file.

version: '2'
services:
  foo:
    image: busybox
    command:
      - /bin/sh
      - -c
      - |
          echo "hello" > id 
          ls
          cat id
          TEST=$$(cat id)
          echo TEST

I checked against Docker Version Docker version 18.06.0-ce and Docker compose version docker-compose version 1.20.0-rc2,

https://github.com/docker/docker.github.io/blob/master/compose/compose-file/index.md#variable-substitution

You can use a $$ (double-dollar sign) when your configuration needs a literal dollar sign. This also prevents Compose from interpolating a value, so a $$ allows you to refer to environment variables that you don’t want processed by Compose.

Adiii
  • 54,482
  • 7
  • 145
  • 148