GitLab CI/CDのテンプレートとextendsで重複を解消!保守性を高めるyaml設計
はじめに
GitLab CI/CDの.gitlab-ci.yml
ファイルで、ジョブの記述が重複してしまい、保守性に課題を感じたことはありませんか?
この記事では、テンプレートとextends
を活用して重複を解消し、より効率的で保守性の高いyaml設計にする方法を紹介します。
課題:重複した記述による保守性の低下
例えば、以下のようにartifacts
の設定などが重複している場合を考えてみましょう。
collect_artifact_tag:
stage: post_stage
script:
- echo $CI_COMMIT_BRANCH
needs:
- build
- test
- diff-check
- lint-cppcheck
artifacts:
name: "collect_artifact"
expire_in: 7 days
paths:
- mybinary
- runlog.log
- cppcheck_result.txt
- cloc_diff.txt
- diff.txt
rules:
- if: '$CI_COMMIT_TAG'
collect_artifact_else:
stage: post_stage
script:
- echo $CI_COMMIT_BRANCH
needs:
- build
- test
- diff-check
- lint-cppcheck
artifacts:
name: "collect_artifact"
expire_in: 7 days
paths:
- mybinary
- runlog.log
- cppcheck_result.txt
- cloc_diff.txt
- diff.txt
rules:
- if: '$CI_COMMIT_TAG == null'
この例では、artifacts
のpaths
やneeds
などが重複しており、変更があった場合に複数箇所修正する必要があります。
解決策:テンプレートとextendsの活用
このような重複を解消するために、テンプレートとextends
を活用します。
-
テンプレートの定義
共通の設定をテンプレートとして定義します。
.template_collect_artifact: stage: post_stage script: - echo $CI_COMMIT_BRANCH needs: - build - test - diff-check - lint-cppcheck artifacts: name: "collect_artifact" expire_in: 7 days paths: - mybinary - runlog.log - cppcheck_result.txt - cloc_diff.txt - diff.txt
-
テンプレートの拡張
extends
を使用して、テンプレートを拡張し、必要な箇所のみ上書きします。collect_artifact_tag: extends: .template_collect_artifact artifacts: expire_in: 1 month rules: - if: '$CI_COMMIT_TAG' collect_artifact_else: extends: .template_collect_artifact artifacts: expire_in: 1 week rules: - if: '$CI_COMMIT_TAG == null || $CI_COMMIT_TAG == ""'
まとめ
テンプレートとextends
、変数を活用することで、GitLab CI/CDの.gitlab-ci.yml
ファイルの重複を減らし、保守性を向上させることができます。ぜひ、これらのテクニックを活用して、より効率的なCI/CDパイプラインを構築してください。