Class: Cloudcost::ApiConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudcost/api_connection.rb

Overview

Connecting to and accessing the cloudscale.ch API

Constant Summary collapse

API_URL =
"https://api.cloudscale.ch"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_token, options = {}) ⇒ ApiConnection

Returns a new instance of ApiConnection.



13
14
15
16
17
# File 'lib/cloudcost/api_connection.rb', line 13

def initialize(api_token, options = {})
  @api_url = options[:api_url] || API_URL
  @api_token = api_token
  @connection = new_connection
end

Instance Attribute Details

#connectionObject

Returns the value of attribute connection.



11
12
13
# File 'lib/cloudcost/api_connection.rb', line 11

def connection
  @connection
end

Instance Method Details

#get_resource(resource, options = {}) ⇒ Object



19
20
21
22
23
24
# File 'lib/cloudcost/api_connection.rb', line 19

def get_resource(resource, options = {})
  path = "v1/#{resource}"
  path += "?tag:#{options[:tag]}" if options[:tag]
  response = @connection.get(path: path, expects: [200])
  JSON.parse(response.body, symbolize_names: true)
end

#get_servers(options = {}) ⇒ Object



26
27
28
29
30
31
# File 'lib/cloudcost/api_connection.rb', line 26

def get_servers(options = {})
  servers = get_resource("servers", options)
  servers = servers.reject { |server| server[:tags].key?(options[:missing_tag].to_sym) } if options[:missing_tag]
  servers = servers.select { |server| /#{options[:name]}/.match? server[:name] } if options[:name]
  servers
end

#get_volumes(options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cloudcost/api_connection.rb', line 42

def get_volumes(options = {})
  volumes = get_resource("volumes", options)
  volumes = volumes.reject { |volume| volume[:tags].key?(options[:missing_tag].to_sym) } if options[:missing_tag]
  volumes = volumes.select { |volume| /#{options[:name]}/.match? volume[:name] } if options[:name]
  volumes = volumes.select { |volume| /#{options[:type]}/.match? volume[:type] } if options[:type]
  unless options[:attached].nil?
    volumes = volumes.select do |volume|
      (volume[:servers].size.positive?) == options[:attached]
    end
  end
  volumes
end

#set_server_tags(uuid, tags) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/cloudcost/api_connection.rb', line 33

def set_server_tags(uuid, tags)
  @connection.patch(
    path: "v1/servers/#{uuid}",
    body: { tags: tags }.to_json,
    headers: { "Content-Type": "application/json" },
    expects: [204]
  )
end