GitLab多YML导入Shell函数冲突问题求助
before_script Let's break down what's happening here and how to fix your split CI configuration without merging all files into one.
The Root Cause
Your issue stems from how GitLab CI handles global before_script definitions across multiple included YAML files. When you define a global before_script in both maven.yml and node.yml, the last included file's before_script replaces the earlier one—it doesn't append to it.
For example, if your include order in repo A's .gitlab-ci.yml is:
include: - project: 'B' file: '/top-level.yml' - project: 'B' file: '/maven.yml' - project: 'B' file: '/node.yml'
The global before_script from node.yml overwrites the one from maven.yml, leaving only the frontend_build function defined. That's exactly why java_build fails to find backend_build.
Fix 1: Use Job Templates (Recommended)
Instead of defining functions in global before_script, create reusable job templates in each specialized YAML file. Have your build jobs extend the relevant template to keep function definitions isolated—this avoids any cross-file overwrites.
Update
maven.ymlto define a template with the backend function:.maven-build-template: before_script: - | function backend_build { # Your existing backend build logic here }Update
node.ymlsimilarly for the frontend:.node-build-template: before_script: - | function frontend_build { # Your existing frontend build logic here }Modify
top-level.ymlto have each build job extend its matching template:stages: - build java_build: stage: build extends: .maven-build-template script: - backend_build node_build: stage: build extends: .node-build-template script: - frontend_build
Now each job runs its own isolated before_script, so both functions are available exactly where they're needed.
Fix 2: Merge Scripts with References
If you prefer to keep using global scripts, use GitLab's !reference tag to safely combine function definitions from multiple files without overwriting.
Update
maven.ymlto store the backend function as a reusable anchor:.backend-function: script: - | function backend_build { # Your backend logic here }Update
node.ymlfor the frontend function:.frontend-function: script: - | function frontend_build { # Your frontend logic here }Add a global
before_scriptintop-level.ymlthat references both blocks:before_script: - !reference [.backend-function, script] - !reference [.frontend-function, script] stages: - build java_build: stage: build script: - backend_build node_build: stage: build script: - frontend_build
This merges both function definitions into the global before_script, making them available to all jobs without overwriting each other.
Why This Works
GitLab CI treats global before_script as a single, replaceable block when included from multiple files. By either isolating functions to job templates or explicitly merging script references, you avoid the overwrite behavior that's breaking your Java build.
内容的提问来源于stack exchange,提问作者Venkata Surya Lolla

