0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GitLab CI/CDのテンプレートとextendsで重複を解消!保守性を高めるyaml設計

Posted at

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'

この例では、artifactspathsneedsなどが重複しており、変更があった場合に複数箇所修正する必要があります。

解決策:テンプレートとextendsの活用

このような重複を解消するために、テンプレートとextendsを活用します。

  1. テンプレートの定義

    共通の設定をテンプレートとして定義します。

    .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
    
  2. テンプレートの拡張

    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パイプラインを構築してください。


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?