Class: Sakura2ssh::SakuraCli

Inherits:
Thor
  • Object
show all
Defined in:
lib/sakura2ssh/cli.rb

Instance Method Summary collapse

Instance Method Details

#updateObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sakura2ssh/cli.rb', line 19

def update
  conf = YAML.load_file(options[:conf])

  ssh_config_path = conf['ssh_config']
  unless ssh_config_path
    raise "not defined 'ssh_config'.please set it."
  end
  access_token = conf['apikey']['access_token']
  access_token_secret = conf['apikey']['access_token_secret']
  user = conf['user']

  client = HTTPClient.new
  entry = ""
  ZONES.each do |zone|
    uri_prefix = "https://secure.sakura.ad.jp/cloud/zone/#{zone}/api/cloud/1.1/"
    client.set_auth(uri_prefix, access_token, access_token_secret)
    url = URI.join(uri_prefix, 'server').to_s
    puts "request to -> #{url}"
    res=nil
    begin
      timeout( options[:timeout].to_i ) {
        res = client.get(url)
      }
    rescue Exception => e
      puts "  #{e}"
      next
    end
    if res == nil
      puts "  response is empty."
    elsif res.status_code.to_i != 200
      puts "  an occurred error processing your request. (#{res.status_code})"
    else
      result = ""
      json = JSON.parse(res.content)
      json['Servers'].each do |server|
        host = server['Name']
        host_suffix = ".#{server['Zone']['Name']}"
        comment = server['Zone']['Description'] + " " + server['Zone']['Region']['Name']
        server = server['Interfaces'].first['UserIPAddress'] # FIXME: Error Handling #.map{|net| net['UserIPAddress']}
        if server == nil
          server = ""
        end
        # Display
        result += "Host \#{host} \#{host}\#{host_suffix}\n  HostName \#{server}\n  TCPKeepALive yes\n  StrictHostKeyChecking no\n" # .split("\n").map{|a|a.lstrip}.join('')
        if user != nil
          result += "  User #{user}\n"
        end
      end
      puts result
      entry += result
    end
  end
  puts "write to result -> #{ssh_config_path} "
  open( ssh_config_path , "w" ){|f| f.write(entry)}
end