Carpe Diem

備忘録

TerraformでHerokuをセットアップ

概要

Terraformというオーケストレーションツールを使います。本当ならAWSで試したいのですが無料枠をすでに使いきっていたので今回はHerokuで。

環境

  • OSX 10.10.2
  • Terraform 0.3.7

インストール

バイナリパッケージを直接ダウンロードしてPATHを通します。

https://www.terraform.io/downloads.html

から自分のシステムに合ったバイナリを以下のようにダウンロードしてください。

$ wget https://dl.bintray.com/mitchellh/terraform/terraform_0.3.7_darwin_amd64.zip

解凍して移動します。~/terraform/usr/local/terraformあたりがいいと思います。今回は後者で。

$ unzip terraform_0.3.7_darwin_amd64.zip -d terraform
$ sudo mv terraform /usr/local/

PATHを設定します。.bash_profileに以下を追記してください。

export PATH=$PATH:/usr/local/terraform/

反映します。

$ source .bash_profile

ちゃんと通っているか確認します。

$ terraform version
Terraform v0.3.7

設定ファイル作成

heroku.tfという以下のファイルを作成します。emailapp_keyは自分のHerokuアカウントのものを使用してください。

# Configure the Heroku provider
provider "heroku" {
    email = "XXXXX@example.com"
    api_key = "XXXXXXXX-XXXX-XXXXXXXXXXXXXXXXXXXXXX"
}
 
# Configure a Heroku app
resource "heroku_app" "default" {
    name = "terraform-test01"
    region = "us"
    stack= "cedar"
    config_vars {
        API_ENV = "development"
    }
}
 
# Configure a Heroku domain
resource "heroku_domain" "default" {
    app = "terraform-test01"
    hostname = "www.example.com"
}

設定ファイルの内容は以下の3つです。上2つは必須です。

名前 説明
アクセス情報 TerraformからHerokuにアクセスするための情報
アプリ情報 作成するアプリ情報。アプリケーションの名前、リージョン、利用するStack、環境変数など設定
ドメイン情報 アプリに割り当てるドメイン情報。自分のドメインを取得していない人は省略で。

計画・実行

terraform planでdry-runすることができます。

$ terraform plan
Refreshing Terraform state prior to plan...


The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

+ heroku_app.default
    all_config_vars.#:     "" => "<computed>"
    config_vars.#:         "" => "1"
    config_vars.0.#:       "" => "1"
    config_vars.0.API_ENV: "" => "development"
    git_url:               "" => "<computed>"
    heroku_hostname:       "" => "<computed>"
    name:                  "" => "terraform-test01"
    region:                "" => "us"
    stack:                 "" => "cedar"
    web_url:               "" => "<computed>"

+ heroku_domain.default
    app:      "" => "terraform-test01"
    cname:    "" => "<computed>"
    hostname: "" => "www.example.com"

問題なさそうなので実行します。

$ terraform apply

以下のように新しいアプリが作成されました。
ドメインは特に指定せずに実行しました。

f:id:quoll00:20150323214133p:plain

実際に作ったアプリにアクセスしてみます。

http://terraform-test01.herokuapp.com/

f:id:quoll00:20150323214313p:plain

まだ中身がないのでHerokuのTopですね。お疲れ様でした。

ソース