やりたいこと
Google Compute Engine APIを使ってインスタンス一覧をRubyで取得したい
おおまかな手順は以下
認証に必要なJSONを取得
まずは認証に必要な権限を得るべく設定して、JSONをダウンロードする
- GCPのターミナル画面を開く
- 左メニューより「IAMと管理」をクリック
- さらに左メニューより「サービス アカウント」をクリック
- 上の「サービス アカウントの作成」で作成
するとサービス アカウント一覧に追加されるので右の「︙」メニューより「キーの作成」でJSONをダウンロードする
これは大切に持っておく
Rubyで叩く
流石に生で叩くのはキツいのでGoogle公式のgoogle/google-api-ruby-clientライブラリを使う。
Gemfileを用意して以下を追加
gem 'google-api-client'
以下をindex.rbとかで作る gce-api.json はさっきダウンロードしたJSONファイルと対応しておく
require 'googleauth' require 'googleauth/stores/file_token_store' require 'google/apis/compute_v1' scope = ['https://www.googleapis.com/auth/compute.readonly'] client = Google::Apis::ComputeV1::ComputeService.new client.authorization = Google::Auth::ServiceAccountCredentials.make_creds( json_key_io: File.open('gce-api.json'), scope: scope ) ips = [] result = client.list_instances('YOUR_PROJECT_NAME', 'asia-east1-b') result.items.each do |item| p item end
list_instancesの第一引数にはプロジェクト名、第二引数にはリージョン(複数指定不可)が必要
- API自体の公式ドキュメントはhttps://cloud.google.com/compute/docs/reference/rest/v1/instances/list
- google-api-ruby-clientのソースはhttps://raw.githubusercontent.com/google/google-api-ruby-client/master/generated/google/apis/compute_v1/service.rb
- フィルタリングとか高度な参考例が見たければGoogle Cloud Platform Blog: Filtering and formatting fun with gcloud, GCP’s command line interfaceを見て
マジでやってる人が少なすぎてつらみだった
ちなみにitem.status
で起動中かどうか、 item.network_interfaces[0].access_configs[0].nat_ip
でグローバルIPを取得できる