LoginSignup
2
1

More than 3 years have passed since last update.

[Circle CI] steps型のparameterを利用して、ブランチごとにビルドの細部の処理を変える

Last updated at Posted at 2020-12-10

複数ブランチでCircle CIのビルドを実行するとき、大まかな処理は同じだが、ブランチごとに細部のビルド処理を切り替えたいことが多々ある。「そういうときは、Circle CIのsteps型parameterで実現ですると良いかも」、という話。
(Circle CIのsteps型のparameterはC/C++で例えると、関数型ポインタのリスト)

状況

master/developにプッシュしたとき、大まかに以下の処理をCircle CIに実行させたいとする。

  1. Setup
  2. ビルド
  3. デプロイ
  4. 後始末(Slack通知、アーティファクト保存など)

ただし、masterとdevelopでは、細部の処理には違いを付ける。

  • develop
    • Debug構成でビルドする
    • デプロイ先は外部から見えない環境にする
  • master
    • Release構成でビルドする
    • デプロイ先は外部から見える環境にする

steps型のparameterでブランチごとに処理を切り替える

Circle CIでは、jobに対して自分で定義した引数を渡すことができる。引数には型があり、steps型が指定でき、workflowから、jobにstepのリストを渡すことができる1。これを利用して、ブランチごとにビルドの細部の処理を切り替える例を示す。

.circleci/config.yml
version: 2.1

jobs:
  build:
    parameters:
      build_steps:
        type: steps
        default: # default値の指定の例を示したかっただけ。workflowから指定しているので意味はない。
          - build_debug
          - deploy_to_internal_env
    executor: foobar
    steps:
      - setup
      steps: << parameters.build_steps >>
      - post_steps

workflows:
  version: 2
  internal_release:
    jobs:
      - build:
          filters:
            branches:
              only:
                - develop
          build_steps:
            - build_debug
            - deploy_to_internal_env
  release:
    jobs:
      - build:
          filters:
            branches:
              only:
                - develop
          build_steps:
            - build_release
            - deploy_to_public_env

他の実現方法について

ブランチごとにビルドの細部の処理を切り替える方法はいろいろある。

まず、思いつくのは環境変数CIRCLE_BRANCHでブランチ名を取得して、if/elseで処理を切り替える方法だ。ただ、ときに分岐が複雑になりすぎるなどして、可読性が落ちることがある。後、1つのブランチに対してビルドを実行するトリガーが複数あり、トリガーに応じて細部の処理を切り替えたいケースには、きれいには対応できない。

他には、buildやdeployの部分を別jobにして、developのときとreleaseのに実行するJobを分ける方法もある2。これだと、「ビルド前の準備 -> ビルド -> デプロイ -> 後始末」という流れは別々にメンテンナスしないといけない。

steps型のparameterを使うことで他の方法よりきれいにビルド処理を書けるかも、ということ。


  1. https://circleci.com/docs/2.0/reusing-config/#parameter-types 

  2. 具体的には、build_debug, build_release Jobを定義して、developのworkflowではbuild_debug、releaseのworkflowではbuild_releaseを実行させる 

2
1
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
2
1