Home > Software engineering >  Source OS environment variables from a docker-compose.yaml
Source OS environment variables from a docker-compose.yaml

Time:03-16

I want to call a script in the same way it is called within a container. Therefore I have to set a couple of environment variables. Is there a way to export all listed environment variables of a docker-compose.yaml, so that they are available as variables in my shell for subsequent commands?

Let's assume I use this docker-compose.yaml:

version: "3.8"

services:
  my-service:
    image: some-image
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      var1: test
      var2: 1
      # var3: test # Some comment
    command: echo $var1 $var2 $var3

Using yq it is easy to parse the relevant variables, but I am unsure how to export each of those. Also special cases like comments might be an issue.

What I got so far: cat ~/docker-compose.yaml| yq .services.my-service.environment

Which will return:

var1: test
var2: 1
# var3: test # Some comment

CodePudding user response:

By using kislyuk/yq (instead of mikefarah/yq), which is a YAML wrapper for the JSON processor stedolan/jq, you could make use of jq's @sh function to piece together some export statements which you can then source from shell.

Example in bash:

$ source <(yq -r '
    .services."my-service".environment
    | to_entries[] | "export \(.key)=\(.value | @sh)"
  ' docker-compose.yaml)

$ echo $var1
test

$ echo $var2
1

$ echo $var3       # not fetched because it was commented out

In POSIX sh, as process substitution is undefined, you'd probably use a temporary file instead:

$ yq -r '
    .services."my-service".environment
    | to_entries[] | "export \(.key)=\(.value | @sh)"
  ' docker-compose.yaml > docker-compose.sh

$ cat docker-compose.sh
export var1='test'
export var2=1

$ . docker-compose.sh

$ echo $var1 $var2 $var3
test 1

Also, if your ultimate goal was to just execute in the given environment the command which is also stored in the YAML file, while the variables are NOT exported into the outer shell, then remove export, add the content of .command at the end of the script, and don't source but execute the script:

$ var1=old_value

$ yq -r '
    .services."my-service"
    | (.environment | to_entries[] | "\(.key)=\(.value | @sh)")
    , .command
  ' docker-compose.yaml | sh
test 1

$ echo $var1
old_value
  • Related