CodeBuild Local で CodeBuild の処理をローカル実行
こんにちは、かたいなかです。
CodeBuild はビルドを自動化するのにとても便利ですが、一度正しく処理を組み立てるまでに毎回 GitHub 等にコードをプッシュしながらトライアンドエラーを繰り返すのはなかなか大変です。
そこで今回は、CodeBuild での処理を手元で試せる CodeBuild Local の使い方をご紹介します。
実際にやってみる
今回は、Rails のアプリケーションを使用していきます。
また、今回のソースコードはこちらのリポジトリにあります。
buildspec.yml を作成
まず、CodeBuild に実行させたい処理を記述する buildspec.yml を用意します。
1 2 3 4 5 6 7 8 9 | version: 0.2phases: install: commands: - bundle install build: commands: - bundle exec rspec |
今回はbundle installとbundle exec rspecを実行させます。
ビルド環境のイメージのビルド
CodeBuildの公式イメージは公開リポジトリには置かれていないため、こちらのリポジトリから自分でビルドする必要があります。
今回はビルド環境として、Ruby の公式イメージを使うので、以下のコマンドを作業用ディレクトリで実行します。
1 2 3 4 5 | $ git clone https://github.com/aws/aws-codebuild-docker-images.git$ cd aws-codebuild-docker-images$ cd ubuntu/ruby/2.5.1$ docker build -t aws/codebuild/ruby:2.5.1 .$ docker run -it --entrypoint sh aws/codebuild/ruby:2.5.1 -c bash |
CodeBuildLocal のヘルパースクリプトを設置
先程の CodeBuild の公式イメージのリポジトリに CodeBuild Local を実行するためのヘルパースクリプトがありますので、プロジェクトのルートディレクトリで以下のコマンドを実行しヘルパースクリプトを設置します。
1 | $ curl https://raw.githubusercontent.com/aws/aws-codebuild-docker-images/master/local_builds/codebuild_build.sh > codebuild_build.sh |
ヘルパースクリプト
ヘルパースクリプトはCodeBuildのDockerイメージを直接使うのに比べ、オプションを渡すのを簡単にしてくれます。
ヘルパースクリプトでは以下のようなオプションを使用できます。
| オプション | 説明 | |
|---|---|---|
| -i <イメージ> | 必須 | ビルド環境として用いるイメージを指定します |
| -a <ディレクトリ> | 必須 | ビルドのアーティファクトを出力するディレクトリを指定します |
| -s <ディレクトリ> | ビルドのソースとなるディレクトリを指定します。デフォルトではワーキングディレクトリがソースディレクトリとなります。 | |
| -c | ホストから AWS の認証情報を渡します | |
| -b <ビルド定義ファイルの場所> | ビルド定義ファイルの場所を指定します。デフォルトではソースディレクトリの buildspec.yml が使用されます |
|
| -e <環境変数ファイル> | 環境変数を定義したファイルを指定します。 環境変数のファイルではそれぞれの行で VAR=VAL のように環境変数を指定します。 |
|
| -h | ヘルプを表示します |
実行してみる
今回はシンプルに、ビルド環境のDockerイメージとアーティファクトの出力先のみ指定して実行してみます。
1 | $ ./codebuild_build.sh -i aws/codebuild/ruby:2.5.1 -a artifact |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | ## 省略agent_1 | [Container] 2018/09/04 05:43:52 Entering phase INSTALLagent_1 | [Container] 2018/09/04 05:43:52 Running command bundle install ## bundle install 実行## bundle installの出力がたくさん## 省略agent_1 | [Container] 2018/09/04 05:44:57 Phase complete: INSTALL Success: trueagent_1 | [Container] 2018/09/04 05:44:57 Phase context status code: Message:## 省略agent_1 | [Container] 2018/09/04 05:44:57 Entering phase BUILDagent_1 | [Container] 2018/09/04 05:44:57 Running command bundle exec rspec ## rspec実行agent_1 | No examples found.agent_1 |agent_1 |agent_1 | Finished in 0.00025 seconds (files took 0.06969 seconds to load)agent_1 | 0 examples, 0 failuresagent_1 |agent_1 |agent_1 | [Container] 2018/09/04 05:44:57 Phase complete: BUILD Success: trueagent_1 | [Container] 2018/09/04 05:44:57 Phase context status code: Message:## 省略 |
上のように出力され、手元で buildspec.yml による処理が実行されたことが分かります。
まとめ
CodeBuildLocal を使用することで簡単にローカルでビルドを実行することができました。
buildspec.yml を書くときの強い味方になりそうですね!!!
参考
- aws-codebuild-docker-images
今回ヘルパースクリプトや公式イメージのビルドに使用したリポジトリ