ponadto
ponadto

Reputation: 722

docker compose YAML file: Re-using variables passed to the entrypoint as arguments

I have the following docker-compose.yml file:

version: '3'


services:

  service1:
    image: same_image:latest
    command: >
      --arg1 1000
      --arg2 2000
      --arg3 whatever

  service2:
    image: another_image:latest
    command: >
      --arg1 1000
      --arg2 2000
      --arg3 something_else
      --arg4 additional_argument

So I'm passing argX arguments to the two entrypoints in the two docker containers, and values of two of those arguments (arg1 and arg2) are shared.

My question: how can I define those two variables in such a way that I can re-use them when passing them as arguments to the entrypoints?

I tried:

version: '3.4'

x-common-variables: &common-variables
  arg1: 1000
  arg2: 2000
 

services:

  service1:
    image: same_image:latest
    command: >
      --arg1 *common-variables.arg1
      --arg2 *common-variables.arg2
      --arg3 whatever

  service2:
    image: another_image:latest
    command: >
      --arg1 *common-variables.arg1
      --arg2 *common-variables.arg2
      --arg3 something_else
      --arg4 additional_argument

but those arguments are not being "unpacked" properly by the YAML parser.

Upvotes: 1

Views: 753

Answers (1)

Mafor
Mafor

Reputation: 10681

I think your best option is providing arg1 and arg2 in the .env file:

.env

arg1=1000
arg2=2000

docker-file.yaml

version: '3.4'

services:

  service1:
    image: same_image:latest
    command: >
      --arg1 $arg1
      --arg2 $arg2
      --arg3 whatever
  service2:
    image: another_image:latest
    command: >
      --arg1 $arg1
      --arg2 $arg2
      --arg3 something_else
      --arg4 additional_argument

With extension fields the solution would be more complex. First of all you couldn't use the shell form (i.e. string) of the command field: YAML aliases cannot be injected into string fields. You would need to use command in the list form:

version: '3.4'

x-common-variables: 
  - &arg1 "1000"
  - &arg2 "2000"

services:

  service1:
    image: same_image:latest
    command: 
      - --arg1 
      - *arg1
      - --arg2 
      - *arg2
      - --arg3 
      - whatever

  service2:
    image: another_image:latest
    command: 
      - --arg1 
      - *arg1
      - --arg2 
      - *arg2
      - --arg3 
      - something_else
      - --arg4 
      - additional_argument

Upvotes: 3

Related Questions