gitlabgitlab-ci

Gitlab CICD: use functions inside gitlab-ci.yml


I have a .gitlab-ci.yml file which allows needs to execute the same function for every step. I have the following and this works.

image:
  name: hashicorp/terraform

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")

stages:
  - validate
  - plan

validate:
  stage: validate
  script:
    - terraform validate
    - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'
  variables:
    msg: "Example1"

plan:
  stage: plan
  script:
    - terraform validate
    - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'
  variables:
    msg: "Example2"

Given it is always the same curl command, I wanted to use a function which I declare once and can use in every step. Something along the lines of below snippet.

image:
  name: hashicorp/terraform

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")

.send_message: &send_message
  script:  
  - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'

stages:
  - validate
  - plan

validate:
  stage: validate
  script:
    - terraform validate
    - &send_message
  variables:
    msg: "Example1"

plan:
  stage: plan
  script:
    - terraform validate
    - &send_message
  variables:
    msg: "Example2"

How could I use such a function in a .gitlab-ci.yml file.


Solution

  • you can used include with !reference such as:

    .send_message:
      script:  
      - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'
    
    include:
      - local: functions.yml
    
    default:
      image:
        name: hashicorp/terraform
      before_script: 
        - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")
    
    stages:
      - validate
      - plan
    
    validate:
      stage: validate
      script:
        - terraform validate
        - !reference [.send_message, script]
      variables:
        msg: "Example1"
    
    plan:
      stage: plan
      script:
        - terraform validate
        - !reference [.send_message, script]
      variables:
        msg: "Example2"
    

    ref: https://docs.gitlab.com/ee/ci/yaml/yaml_optimization.html#reference-tags