在上一篇內容中,初步認識了 GitLab CI/CD Steps 這個目前實驗中的功能,在今天的內容中,會建立出一個自己的 CI/CD Step。
要建立自己的 step 應該要有哪些要件呢? 最重要的是需要有一個 step.yml
檔案,其格式上半部為定義 step 的規格,同樣以 ---
間隔,下半部為這個 step 的實作。
首先先建立 step.yml
,其內容如下:
spec:
inputs:
who:
type: string
default: step
---
exec:
command:
- bash
- -c
- echo 'hello ${{inputs.who}}'
這邊描述的上半部是宣告了,這個 step 有一個輸入,參數名稱為 who
其型別為 string,預設值為文字 step
。下半部 exec
的部分,在於實作該 step 的動作。
以內容中的:
command:
- bash
- -c
- echo 'hello ${{inputs.who}}'
其在執行時,假設 input 的參數 who 維持預設值 step,則在系統中等同以下指令:
bash -c "echo hello step"
也就是 YAML 檔案中command
底下所帶入的 string Array,分別是:
bash
這個指令-c
參數echo 'hello step'
echo 'hello step'
因此實際執行後,畫面中會印出 hello step
字樣顯示。接下來回到 .gitlab-ci.yml
來使用這個新建立的 step
:
hello-step:
run:
- name: hello_step_job
step: .
- name: hello_my_step_job
step: .
inputs:
who: "my step"
一樣是使用 run:step
的方式,這邊 step: .
的意思是,使用本地端同資料夾的 step,也就是剛剛建立的 step.yml
宣告的內容。
第一個 name 為 hello_step_job
的 step,使用預設值,因此畫面中會輸出: hello step
,第二個 name 為 hello_my_step_job
的 step,輸入參數 who
數值為 my step
,因此,畫面中會輸出 hello my step
,完整的輸出內容如下:
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_job"
hello step
Running step "hello_my_step_job"
hello my step
從輸出的畫面中還可以看到另外一個關鍵因素,在這邊使用了一個 docker image為 registry.gitlab.com/gitlab-org/step-runner:v0
,這也是整個 step
元件很重要的一環,這邊所有的 command 都是在這個 container 中執行。這邊 step 上所執行的指令,都是以這個 container 的系統環境為主。
這一篇的內容,主要在介紹怎麼建立自己的 step,以及其主要的結構,但可能會發現,目前的執行都只是在 step 中執行完畢。如果 step 執行後的結果,需要傳遞給其他的 step時,該怎麼處理?在 GitLab CI/CD step 中還定義了 outputs
這部分就是用來定義 step 輸出給外部使用用的,其實作的內容會在接下來的內容繼續描述。我是墨嗓(陳佑竹),期待這次的內容能帶給你實用的啟發與幫助。