Created
April 8, 2011 04:34
-
-
Save khamanaka/909296 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# NIFTY Cloud API - DescribeInstances | |
# Author:: Kei HAMANAKA <kei.hamanaka (at) gmail.com> | |
# License:: Distributes under the same terms as Ruby | |
require 'uri' | |
require 'time' | |
require 'net/https' | |
require 'cgi' | |
require 'openssl' | |
ACCESS_KEY = "" | |
SECRET_ACCESS_KEY = "" | |
class NIFTYCloud | |
REQUEST_URI_BASE = URI.parse('https://cp.cloud.nifty.com/api/') | |
SIGNATURE_VERSION = 0 | |
API_VERSION = 1.5 | |
TIME_STAMP = Time.now.utc.iso8601 | |
ACTION_NAME = "DescribeInstances" | |
def initialize(access_key, secret_access_key) | |
@access_key = access_key | |
@secret_access_key = secret_access_key | |
end | |
def describe_instances | |
request(create_path) | |
end | |
private | |
def request(path) | |
https = Net::HTTP.new(REQUEST_URI_BASE.host, REQUEST_URI_BASE.port) | |
https.use_ssl = true | |
https.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
https.start do |request| | |
response = request.get(path) | |
response.body | |
end | |
end | |
def create_path | |
[REQUEST_URI_BASE.path, create_parameters].join("?") | |
end | |
def create_parameters | |
signature = create_signature(ACTION_NAME, @secret_access_key, TIME_STAMP) | |
create_params(@access_key, SIGNATURE_VERSION, signature, | |
API_VERSION, TIME_STAMP, ACTION_NAME | |
).join("&") | |
end | |
def create_signature(action_name, secret_access_key, time_stamp) | |
signature = action_name + time_stamp.to_s | |
base64(digest_hmac_sha1(secret_access_key, signature)) | |
end | |
def digest_hmac_sha1(secret_access_key, value) | |
OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret_access_key, value) | |
end | |
def base64(value) | |
[ value ].pack('m').strip! | |
end | |
def create_params(access_key, signature_version, signature, | |
api_version, time_stamp, action_name) | |
params = { | |
"AccessKeyId" => access_key, | |
"Action" => action_name, | |
"SignatureVersion" => signature_version, | |
"Signature" => signature, | |
"Version" => api_version, | |
"Timestamp" => time_stamp | |
} | |
encode_params(params) | |
end | |
def encode_params(params) | |
params.collect do |k, v| | |
encoded = (CGI.escape(k.to_s) + | |
"=" + CGI.escape(v.to_s)) | |
encoded = encoded.gsub('+', '%20') | |
encoded = encoded.gsub('%7E', '~') | |
end | |
end | |
end | |
niftycloud = NIFTYCloud.new(ACCESS_KEY, SECRET_ACCESS_KEY) | |
puts niftycloud.describe_instances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment