Class: Cloudcost::ApiConnection

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

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.



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

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.



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

def connection
  @connection
end

Instance Method Details

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



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

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



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

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

#set_server_tags(uuid, tags) ⇒ Object



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

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