LoginSignup
2
2

More than 5 years have passed since last update.

ConoHa APIをRubyから呼ぶ

Last updated at Posted at 2015-07-17

前回Safari用機能拡張を作ったのですが、ふと思い立って今回はRubyで書いてみることにしました。

今回は細かい部分は省略してコードだけ。

Tokenを取得する

ポイントとしてはhttpで通信することですかね。

require 'net/https'
require 'uri'
require 'json'

....

    def GetToken(username, password, region)
      tenantId = username.gsub("gncu","gnct")
      url = "https://identity." + region + ".conoha.io/v2.0/tokens"
      uri = URI.parse(url)
      https = Net::HTTP.new(uri.host, uri.port)
      https.use_ssl = true
      #https.set_debug_output $stderr
      req = Net::HTTP::Post.new(uri.request_uri)
      req["Content-Type"] = "application/json"
      req.body = '{ "auth": { "passwordCredentials": { "username": "'+ username +'", "password": "'+ password + '"}, "tenantName": "'+ tenantId +'" } }'
      res = https.request(req)
      if res.code == "200"
        json = JSON.parse(res.body)
        json["access"]["token"]
      else
        nil
      end
    end

真ん中あたりの「#https.set_debug_output $stderr」はコメントを解除すると通信状態の詳細が表示されます。デバッグに非常に便利です。

参考:ConoHa API トークン発行

サーバー状態を取得する

取得したAPIトークンをreq[X-Auth-Token]にて引き渡します。

require 'net/https'
require 'uri'
require 'json'

....

    def GetServers(region, token)
      url = "https://compute." + region + ".conoha.io/v2/" + token["tenant"]["id"] + "/servers/detail"
      uri = URI.parse(url)
      https = Net::HTTP.new(uri.host, uri.port)
      https.use_ssl = true
      #https.set_debug_output $stderr
      req = Net::HTTP::Get.new(uri.request_uri)
      req["Accept"] = "application/json"
      req["X-Auth-Token"] = token["id"]
      res = https.request(req)
      if res.code == "200"
          json = JSON.parse(res.body)
          json
      else
          nil
      end
    end

参考:ConoHa API VM一覧詳細取得

応用編

一回コツがわかってしまえばAPIをいじって何ができるかを考えるのは楽しいですね。

ということで、自分以外に使う人がいるか疑問ですがこのコードを応用してAlfred2用のWorkflowを作ってみました。Conohaとコマンドを打つとサーバー一覧が表示されます。選択するとコントロールパネルが開きます。

スクリーンショット 2015-07-17 23.52.34.png

まだざっくり作っただけのテスト段階ですが、興味のある人はどうぞ。

2
2
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
2
2