Speee DEVELOPER BLOG

Speee開発陣による技術情報発信ブログです。 メディア開発・運用、スマートフォンアプリ開発、Webマーケティング、アドテクなどで培った技術ノウハウを発信していきます!

vagrant-googleを日本で一番詳しく解説

こんにちは。ランチコンダクターです。
今回はVagrant Google Compute Engine (GCE) Providerのvagrant-googleの紹介をさせていただきます。

vagrant-googleとは

前回はvagrant-awsについて紹介しましたvagrant-awsは、vagrantのUIを使ってAWS上のインスタンスを操作するというものでした。
今回紹介するvagrant-googleは、vagrant-awsGCP版になります。

vagrant-googleを使う際の事前準備

前回のvagrant-awsでは事前準備を省いてしまいましたが、GCPについてはWeb上の情報が少ないので事前準備についてもしっかり書いていきます。

サービスアカウントの作成

以下URLからサービスアカウントの作成を行う(ProjectIDについては個人のIDに変更してください) https://console.developers.google.com/project/[ProjectID]/apiui/credential

  • "新しいクライアントIDを作成"をクリック

  • "Service account"を選択し、、"クライアントIDを作成"をクリック

  • p12ファイルのダウンロードが始まるので保存を行う(あとで使用する)
  • メールアドレス(xxxxx-xxxxx@developer.gserviceaccount.com)をとっておく(あとで使用する)

Google Cloud SDKのインストール

以下のコマンドの実行

$ curl https://dl.google.com/dl/cloudsdk/release/install_google_cloud_sdk.bash | bash

GoogleCloud SDKインストール時の質問について

# Google Cloud SDKのインストール先(/usr/localをオススメします)
Directory to extract under (this will create a directory google-cloud-sdk) (/Users/hogehoge):

# Google Cloud SDK の改善に協力しますか?
Do you want to help improve the Google Cloud SDK (Y/n)?

# インストールする SDK の選択(GCE のみ使用の場合は [4] を選択する)
This will install all the core command line tools necessary for working with
the Google Cloud Platform.
.....
  [1]  Java
  [2]  Python and PHP
  [3]  Go
  [4]  No App Engine (you can install App Engine tools later)
Please enter your numeric choice (4):

# 環境変更のためのシェル設定ファイル(zshの場合は"/Users/username/.zshrc"等が良い)
Enter path to an rc file to update, or leave blank to use
[/Users/hogehoge/.bash_profile]:

# 環境変数 PATH を変更するか(変更した方が良い)
Modify profile to update your $PATH? (Y/n)?

# 保管を有効にするか(有効にする方が良い)
Modify profile to enable bash completion? (Y/n)?

設定後、zshであれば.zshrcに以下が追加されているはずです。

# The next line updates PATH for the Google Cloud SDK.
source '/usr/local/google-cloud-sdk/th.zsh.inc'

# The next line enables bash completion for gcloud.
source '/usr/local/google-cloud-sdk/completion.zsh.inc'
  • インストール後、使用するGoogleアカウントにログインを行う
$ gcloud auth login

Google Compute Engineのインスタンスの作成

ここでGCE(Google Compute Engine)のインスタンスの作成を行います。
理由としてはvagrant-googleを使用する際に必要な秘密鍵の取得のためです。

  • 項目の入力、選択を行い、作成をクリック

  • SSHの横のボタンをクリック

  • "gcloudコマンドを表示"をクリック

  • 表示されているコマンドをコピーする

  • ターミナルに貼り付けを行い、SSHにて接続
# SSH接続を行う
gcloud compute --project "project_id" ssh --zone "asia-east1-a" "my-instance"
  • 接続に成功すると"~/.ssh"に"google_compute_engine"というファイルができているので、 確認を行う
# ~/.ssh/ディレクトリに以下のファイルが生成されているのか確認
$ ls ~/.ssh/ | grep google
google_compute_engine
google_compute_engine.pub

vagrant-googleプラグイン

vagrant plugin install vagrant-google
# ダミー用のBoxの追加
vagrant box add gce https://github.com/mitchellh/vagrant-google/raw/master/google.box

実行

Vagrantfileサンプル

Vagrant.configure("2") do |config|
  config.vm.box = "gce"
  config.vm.provider :google do |provider, override|
    # ProjectID
    provider.google_project_id = "project_id_000"
    # アカウントのEmailの作成(サービスアカウント作成時に保存したもの)
    provider.google_client_email = "000000000-xxxxxxx@developer.gserviceaccount.com"
    # 秘密鍵のパス(サービスアカウント作成時にダウンロードしたもの)
    provider.google_key_location = "~/xxxx/xxxx.p12"

    # zoneの入力
    provider.zone = "asia-east1-b"
    provider.zone_config "asia-east1-b" do |zone1f|
        # インスタンス名(デフォルトはi-yyyyMMddhhとなる)→ 2014/11/02 20:00に作成した場合はi-2014110220
        # インスタンス名がそのままホスト名になる(同じProject内のインスタンスはインスタンス名で名前解決できる)
        zone1f.name = "testing-vagrant"
        # OSイメージ名
        zone1f.image = "debian-7-wheezy-v20141021"
        # インスタンスタイプ
        zone1f.machine_type = "f1-micro"
        # zone
        zone1f.zone = "asia-east1-b"
        # カスタム メタデータ
        zone1f.metadata = {'custom' => 'metadata', 'testing' => 'foobarbaz'}
        # タグ
        zone1f.tags = ['web', 'app1']
    end
    # ネットワーク
    # provider.network = "vagrant"

    # ダミー Box の指定
    override.vm.box = "gce"
    override.vm.box_url = "https://github.com/mitchellh/vagrant-google/raw/master/google.box"

    # ユーザー名
    override.ssh.username = "yumaiwasaki"
    # これは基本的にこのまま使用する
    override.ssh.private_key_path = "~/.ssh/google_compute_engine"
  end
end

上記のVagrantfileを使用してインスタンスの操作を行う

# インスタンスの起動
$ vagrant up --provider=google
Bringing machine 'default' up with 'google' provider...
==> default: HandleBoxUrl middleware is deprecated. Use HandleBox instead.
==> default: This is a bug with the provider. Please contact the creator
==> default: of the provider you use to fix this.
==> default: Warning! The Google provider doesn't support any of the Vagrant
==> default: high-level network configurations (`config.vm.network`). They
==> default: will be silently ignored.
==> default: Launching an instance with the following settings...
==> default:  -- Name:      i-2014103019
==> default:  -- Type:      f1-micro
==> default:  -- Disk size: 10 GB
==> default:  -- Image:     debian-7-wheezy-v20141021
==> default:  -- Zone:      asia-east1-b
==> default:  -- Network:   default
==> default:  -- Metadata:  '{"custom"=>"metadata", "testing"=>"foobarbaz"}'
==> default:  -- Tags:      '["web", "app1"]'
==> default: Waiting for instance to become "ready"...
==> default: Machine is booted and ready for use!
==> default: Waiting for SSH to become available...
==> default: Machine is ready for SSH access!
==> default: Rsyncing folder: /Users/yumaiwasaki/.ghq/github.com/yuma-iwasaki/vagrant-google-example/ => /vagrant

# インスタンスへSSH接続
$ vagnrant ssh

# インスタンスの破棄
$ vagrant destroy

小ネタ

vagrant haltについて

vagrant haltコマンドが使えません。
なぜかというとGCEにはインスタンスの停止がないため、実装できないからです。

vagrant-googleで起動していないインスタンスへのSSH接続

SSH接続を行いたいインスタンス名にローカルのファイルの中を書き換えることにより、SSH接続が可能になります。

# 書き換え
$ echo 'インスタンス名' > .vagrant/machines/default/google/id
# インスタンスにSSH接続
$ vagrant ssh

エラーについて

`build_excon_response': The resource 'projects/project_id_000/zones/us-central1-b/disks/my-instance' already exists (Fog::Errors::Error)

もう既に存在しているインスタンス名のため、インスタンスの起動に失敗します。 インスタンス名の変更を行い、もう一度実行することで解決されます。 ※ デフォルトのインスタンス名はyyyyMMddhhとなるのでインスタンス名は必ず入れといた方が良いです。

Bringing machine 'default' up with 'google' provider...
==> default: HandleBoxUrl middleware is deprecated. Use HandleBox instead.
==> default: This is a bug with the provider. Please contact the creator
==> default: of the provider you use to fix this.
==> default: Warning! The Google provider doesn't support any of the Vagrant
==> default: high-level network configurations (`config.vm.network`). They
==> default: will be silently ignored.
==> default: Launching an instance with the following settings...
==> default:  -- Name:      testing-vagrant
==> default:  -- Type:      f1-micro
==> default:  -- Disk size: 10 GB
==> default:  -- Image:     centos-6-v20141021
==> default:  -- Zone:      asia-east1-b
==> default:  -- Network:   default
==> default:  -- Metadata:  '{"custom"=>"metadata", "testing"=>"foobarbaz"}'
==> default:  -- Tags:      '["web", "app1"]'
==> default: Waiting for instance to become "ready"...
==> default: Machine is booted and ready for use!
==> default: Waiting for SSH to become available...
==> default: Machine is ready for SSH access!
==> default: Rsyncing folder: /Users/yumaiwasaki/.ghq/github.com/yuma-iwasaki/vagrant-google-example/ => /vagrant
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

mkdir -p '/vagrant'

Stdout from the command:



Stderr from the command:

sudo: sorry, you must have a tty to run sudo

現状、centos-6-v20141021などでインスタンスの起動を行う際にフォルダ同期でエラーが起こります。
回避策についてはsudoできるスナップショットの作成を行うなどしかないと思われます。
(あれば教えてください) ※AWSではUser Dataを使うことにより回避ができるのですが

実用について

使用用途としては、vagrant-awsのように、コード化されたインフラのテストに使うことがメインだと思います。
vagrant-awsの時にも書きましたが、
AWSインスタンス起動 → Chef or Puppet or Ansibleを実行 → serverspecにてテストというフローを繰り返し実行していくフローを自作するのはそれなりの手間がかかります。
このフローをVagrantfileで管理でき、かつ簡単に自動化できるので、 GCPを使って自動化したい人にはもってこいのVagnratプラグインなので、ぜひ使ってみるといいと思います。

最後に

今回もVagrantプラグインの紹介をさせていただきました。
vagrant-googleの機能はvagrant-awsと比べるとぶっちゃけ機能は少ないです。
ただ今後GCPが普及していくにつれて良くなっていくと思います。(流行るのを待つのみ)

GCEの東京のゾーンができれば日本でGCPが流行るんじゃないかと思っているので、
できるのを楽しみにしてます!
GCPを盛り上げていきましょう!!
Googleの手先ではありません