けっこう難しかったので
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"] }