LoginSignup
5
4

More than 5 years have passed since last update.

google-api-ruby-clientを使ってGoogleComputeEngineのApiを叩いてみる

Posted at

けっこう難しかったので

require "google/api_client"

key_path = "DLしたp12キーをpemに変換したファイルのフルパス"
passphrase = "鍵のパスフレーズ"
user = "サービスアカウントのメールアドレス"
project_id = "プロジェクトID"
zone = "インスタンスを配置したzone"

client = Google::APIClient.new(:application_name => "")
key = Google::APIClient::KeyUtils.load_from_pem(key_path, passphrase)

client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience             => 'https://accounts.google.com/o/oauth2/token',
  :scope                => "https://www.googleapis.com/auth/compute",
  :issuer               => user,
  :signing_key          => key
)

client.authorization.fetch_access_token!
compute = client.discovered_api("compute")

result = client.execute(
  :api_method => compute.instances.list,
  :parameters => { "project" => project_id, "zone" => zone }
)

p JSON.parse(result.response.body)

# 起動中のインスタンスの配列を取る
body = JSON.parse(result.response.body)
p body["items"].select { |i| i["status"] == "RUNNING" }.map { |i| i["networkInterfaces"].first["accessConfigs"].first["natIP"] }
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4