TL;DR: No, it is not possible
First of all, you have typos in your docker-compose. Please copy the whole docker-compose next time. Here is mine corrected (I didn't want to edit your question) and extended to be testable:
version: '2.4'
x-base-template: &base-template
image: alpine
command: env
environment:
- FOO=BAR
x-custom-template-1: &custom-template1
<<: *base-template
environment:
- FOO2=BAR2
services:
service-1:
<<: *custom-template1
This setup will completely override the environment setting, so only FOO2
is set. I suppose that's why you are asking.
I don't know where you picked up the plus+
syntax, but I can't find anything about it. The only place I found the +
is in https://yaml.org/refcard.html, but there is no mention of arrays. That's for strings.
You cannot merge arrays, but you can use key: value
syntax for environment, and that can be merged this way:
version: '2.4'
x-base-environment: &base-environment
FOO: BAR
x-base-template: &base-template
image: alpine
command: env
environment: *base-environment # This is only necessary if you want variables in base-template
x-custom-template-1: &custom-template1
<<: *base-template
environment:
<<: *base-environment
FOO2: BAR2
services:
service-1:
<<: *custom-template1
The merging we use, the Merge Key Language-Independent Type, doesn't support nested merging. That means that the key is either picked from one object, or the other, no combination. And that's the intended design. It's friendly behaviour most of the time. The sad thing is, there is no yaml feature (or any I know of) that supports nested merging; the simple answer to your questions is, "No, it is not possible."
Sidenote: GitLab tried to solve this for their CI config with proprietary extends
, which supports
reverse deep merge based on the keys