iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0

過去的幾篇介紹了許多與 GitLab CI/CD Components 相關的內容,像是 inputsComponents以及對應的 Catalog 平台等等,這是在 GitLab 16 中很重要的一個改變,而到了 GitLab 17,則開始一個新的功能稱為 GitLab CI/CD steps,這個功能在官網上的描述是,讓 CI/CD 的每個步驟,更加的可以被重複使用,每個工作可以是由一個一個的 Step 組合在一起,像是一塊一塊的積木,來堆疊出需要的功能。
目前這個功能還標示為「實驗(Experiment)」,在還變更為正式版前,請先不要在正式環境中使用。

GitLab CI/CD steps 使用初體驗

第一個範例,使用官方手冊的範例並稍加調整為可以執行的狀態(對,目前官方手冊上的範例是無法執行的):

first_step_job:
  variables:
    CI_SAY_HI_TO: "Sally"
  run:
    - name: hello_step_use_script
      script: 'echo "hello from step"'
    - name: say_hi
      step: gitlab.com/gitlab-org/ci-cd/runner-tools/echo-step@v5
      inputs:
        echo: "hello, ${{job.CI_SAY_HI_TO}}"

這個範例執行後,可以在 job 看到以下執行結果

Using effective pull policy of [always] for container registry.gitlab.com/gitlab-org/step-runner:v0
Using docker image sha256:bc81d28214953dfb4140a8506d0a59eb5d29a4cd6f83443d5808efd202ab724f for registry.gitlab.com/gitlab-org/step-runner:v0 with digest registry.gitlab.com/gitlab-org/step-runner@sha256:ac478fd1a98088102a37ed2e3b0f634d521a91cc510e0b0148d8e7edeb4ea933 ...
Running step "hello_step_use_script"
hello from step
Running step "say_hi"
hello, Sally

主要的執行成果是:

Running step "hello_step_use_script"
hello from step
Running step "say_hi"
hello, Sally

如何使用

從範例 CI/CD YAML 中可以看到 run 底下有兩個段落,name 分別是 hello_step_use_scriptsay_hi,這兩個 run 底下的段落,也就是 steps 功能的兩種使用方法:scriptstephello_step_use_script 使用的是過去常用的 script 的方法,而 say_hi 則是使用預定義的 step,並依據該 step 定義的 inputs 規格,進行使用。

回到手冊上關於 run 的段落,這邊提到 step,所支援的欄位:

  • name: step 的名稱
  • script: 以 shell command 執行的字串(文件中提到支援 array,但實際實用會發生 .gitlab-ci.yml 格式錯誤)
  • step: 定義使用什麼預定義的 step 來執行。
  • env: 當使用 step 時,定義在什麼環境上使用。
  • inputs: 根據使用的預定義 step所需要的 inputs 參數進行設定。
    在使用上,每個 step 中,可以選擇使用 scriptstep 來執行,但這兩者不能同時存在。

第一個 step hello_step_use_scriptscript 的段落使用 'echo "hello from step"' 因此畫面中以 shell 執行,透過 echo 印出 "hello from step"

第二個 step say_hi,其使用的預定義 step 為 https://gitlab.com/gitlab-org/ci-cd/runner-tools/echo-step@v5,直接查看 Source Code 中的 step.yml 的內容:

spec:
  inputs:
    echo:
      type: string
  outputs:
    echo:
      type: string
---
exec:
  work_dir: "${{ step_dir }}"
  command:
    - ./bin/echo
    - --output-file
    - "${{ output_file }}"
    - --echo
    - "${{ inputs.echo }}"

這邊主要先注意格式,與 components 一樣的,上半部同樣是做 step 的規格定義 在這邊有之前 components 已經見過的spec:inputs 以及尚未使用過的spec:outputs。下半部則是 step 的執行細節,根據inputs 的參數內容,執行。至於執行細節及 outputs的部分,會在接下來的章節深入說明,今天先淺嚐知道有這樣的內容。

總結

GitLab 在 16 版引入 Components,而 17 版進一步推出 Steps,看起來兩者的精神是一致的:將複雜的 CI/CD 拆解成可重複利用的積木單元。透過 script 與 step 的使用方式,使用者可以更靈活地組合流程,並逐步累積一套可被重用的 CI/CD 積木。我是墨嗓(陳佑竹),期待這次的內容能帶給你實用的啟發與幫助。

參考範例

參考連結


上一篇
Day09 - 發布 CI/CD Components 到 GitLab Catalog
下一篇
Day11 - 建立自己的 Step
系列文
GitLab CI 2025:深入玩轉流水線與實戰紀錄11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言