viratpuar
viratpuar

Reputation: 554

Use shell script function under multiple Gitlab projects gitlab-ci.yml files

I have multiple gitlab projects and I want to create one template which would be useful under multiple projects.

I have 2 files under one project

function.sh
function.yml

Problem: under the function.yml when I use default keyword with before-script , there would be possibility that wherever this template would be in use the default keyword would be overridden and the function can't be useful. what would be the better way to write an function.yml so it would be useful.

current function.yml

default:
  before_script: source scripts/functions.sh

Now I want to include function.yml file under other gitlab.yml files where they would directly use the function in the yml files.

For example.

include:
  - local: template/function.yml

stages:
  - testproject

testproject:
  stage: testproject
  script:
    - echoFunction "This is a pattern derived from the other yml file" #function call from function.yml file

Upvotes: 0

Views: 216

Answers (1)

ha36d
ha36d

Reputation: 1127

You can reduce complexity and duplicated configuration in your GitLab CI/CD configuration files by using:

  • extends
  • !reference

Note: There is a third solution named YAML-specific features like anchors (&), aliases (*), and map merging (<<), but they cannot be used when using include keyword.

Example for extends:

function.yml

.default:
  before_script:
    - source scripts/functions.sh

.gitlab-ci.yml

include:
  - local: template/function.yml

stages:
  - testproject

testproject:
  stage: testproject
  extends: .default
  script:
    - echoFunction "This is a pattern derived from the other yml file" #function call from function.yml file

Example for !reference:

function.yml

.default:
  before_script:
    - source scripts/functions.sh

.gitlab-ci.yml

include:
  - local: template/function.yml

stages:
  - testproject

testproject:
  stage: testproject
  before_script:
      - !reference [.default, before_script]
  script:
    - echoFunction "This is a pattern derived from the other yml file" #function call from function.yml file

Upvotes: 1

Related Questions