tofucodes diary

にほんごのほう

BitbucketのコードをHerokuに自動デプロイする方法が超簡単だった

最近仕事が暇すぎて業務時間中に個人プロジェクトのコード書いてコミットしてたりしたんですが

プライベートレポジトリじゃないんでGithubのContribution activity(草の下の方とかに出るやつ)を同僚や上司に見られたらあまり良くないよなぁと思い

GithubのオープンレポジトリからBitbucketのプライベートレポジトリに移行しました。

元々はGithubのレポジトリとHerokuを連携させて自動デプロイの設定をしてたのですが

BitbucketとHerokuの自動デプロイ連携を今回やってみたので備忘録的なやつ。

(まさかこの直後にGithubがプライベートレポジトリを無料解放するとは、この時の僕は知る由もなかった...)

blog.github.com

ではGithubのプライベートレポジトリが無料になったこの時代に、BitbucketとHerokuの自動デプロイ設定をしていきましょう。

ゴール

bitbucketにコミットすると自動的にpipelineがアプリケーションをビルドしてHerokuにデプロイする。

f:id:tofucodes:20190115225929p:plain
bitbucketのpipeline画面

f:id:tofucodes:20190115225940p:plain
pipeline #4の詳細画面

f:id:tofucodes:20190115230218p:plain
Heroku管理画面のactivity履歴

手順

  1. bitbucket-pipelines.yml の作成
  2. レポジトリに環境変数の設定

1. bitbucket-pipelines.yml の作成

f:id:tofucodes:20190115233442p:plain
bitbucketのUI上でpipeline作成

参考までにこちらが私の bitbucket-pipelines.yml です。

image: php:7.1.3

pipelines:
  default:
    - step:
        name: Deploy to production
        deployment: production
        caches:
          - composer
        script:
          - apt-get update && apt-get install -y unzip git
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install
          - git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_APP_NAME.git HEAD
  • bitbucketのデフォルトのPHPバージョンは7.1.1でしたが僕のプロジェクトにはPHP7.1.3が必要だったので7.1.3にしてます。
  • それが原因か不明ですが、以下のようなエラーになるのでapt-getでgitもインストールしてます。
+ git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_APP_NAME.git HEAD
bash: git: command not found

2. レポジトリの環境変数を設定

f:id:tofucodes:20190115234702p:plain
bitbucketのUI上で環境変数の設定

試してませんが、Repositoryの環境変数ではなくて、その下にあるDeploymentsの変数の方でも動作するかもしれません(し、そちらの方が適切かもしれません)

Deploymentsの変数の説明

Variables that can only be used in deployments to a specific environment.

HEROKU_API_KEYの作成方法は公式ドキュメントを参照で。

devcenter.heroku.com