Gitlab CICD:在 gitlab-ci.yml 中使用函数

Gitlab CICD: use functions inside gitlab-ci.yml

我有一个 .gitlab-ci.yml 文件,它允许需要为每个步骤执行相同的功能。我有以下内容并且有效。

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"

鉴于它始终是相同的 curl 命令,我想使用一个我声明一次并且可以在每个步骤中使用的函数。类似于以下代码段的内容。

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"

如何在 .gitlab-ci.yml 文件中使用这样的函数。

您可以将 include!reference 一起使用,例如:

  • functions.yml
.send_message:
  script:  
  - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'
  • .gitlab-ci.yml
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"

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

您还可以使用顶部定义的常规旧 bash 函数:

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")
  - send_bearer () { terraform validate; curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE " https://api.teams.com/v1/messages; }

...

validate:
  stage: validate
  script:
    - send_bearer $msg
  variables:
    msg: "Example1"

plan:
  stage: plan
  script:
    - send_bearer $msg
  variables:
    msg: "Example2"