
Gitlab自動建置參數
.gitlab-ci.yml 檔案是 GitLab CI/CD (持續整合/持續交付) 的核心設定檔。它位於專案的根目錄,用來定義你的自動化建置、測試和部署流程。這個檔案使用 YAML 語法,易於閱讀和撰寫。
.gitlab-ci.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| image: python:3.11.9 # 官方基礎鏡像
stages: # CI/CD 管線的階段 (Stages),只有當前一個階段的所有 jobs 都成功完成時,才會進入下一個階段。 - build - test - deploy
build: # 執行任務 stage: build script: # 一系列命令腳本 - pip install -r requirements.txt
test: stage: test script: # 啟用 程式碼覆蓋率 (Code Coverage) 報告 - pytest --cov=my_package
deploy: stage: deploy script: - docker build -t my-image . - docker push my-registry/my-image only: - main # 指定這個 job 只會在 main 分支 (branch) 的提交或合併請求時執行
|
參數解釋
image: 指定工作執行的 Docker image。
- 變數 (Variables)
定義: 流程中使用的變數。
1 2
| variables: DB_PASSWORD: mysecretpassword
|
- 階段 (Stages)
定義: 指定流程中的階段,每個階段中的工作會依序執行。
1 2 3 4 5
| stages: - build - test - security - deploy
|
1 2 3 4
| Include: - template: Security/SAST.gitlab-ci.yml - template: Security/Dependency-Scanning.gitlab-ci.yml - template: Security/DAST.gitlab-ci.yml
|
靜態程式分析(SAST)
檢查程式中潛在漏洞,涵蓋單元測試,要求入口與斷言
組件分析 (Dependency Scanning)
分析依賴,識別有漏洞的庫和框架
動態應用安全測試(DAST)
發現運行中的安全漏洞
1 2 3 4 5 6 7 8
| build: stage: build script: - make build artifacts: 儲存工作產生的檔案。 name: paths: expire_in:
|
- 條件 (Conditions)
定義: 控制工作執行的條件。
1 2 3 4 5 6
| deploy_job: stage: deploy script: - kubectl apply -f ./kubernetes only: - main
|
1 2 3 4 5
| before_script: 在工作開始前執行的指令。 after_script: 在工作結束後執行的指令。 allow_failure: 允許工作失敗而不中斷整個流水線。 >覆蓋 >>添加
|
完整範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| image: node:latest
stages: - build - test - deploy
build_job: stage: build script: - npm install - npm run build
test_job: stage: test script: - npm test
deploy_job: stage: deploy script: - docker login -u $DOCKER_USER -p $DOCKER_PASSWORD - docker push $REGISTRY_IMAGE:$CI_COMMIT_REF_NAME only: - main variables: DOCKER_USER: your_docker_user DOCKER_PASSWORD: your_docker_password REGISTRY_IMAGE: your_registry/your_image
|