1
|
require 'hammer_cli'
|
2
|
require 'json'
|
3
|
require 'csv'
|
4
|
|
5
|
module HammerCLICsv
|
6
|
class CsvCommand
|
7
|
class ComputeResourcesCommand < BaseCommand
|
8
|
command_name 'compute-resources'
|
9
|
desc 'import or export compute resources'
|
10
|
|
11
|
ORGANIZATIONS = 'Organizations'
|
12
|
LOCATIONS = 'Locations'
|
13
|
DESCRIPTION = 'Description'
|
14
|
PROVIDER = 'Provider'
|
15
|
URL = 'URL'
|
16
|
|
17
|
def export
|
18
|
CSV.open(option_file || '/dev/stdout', 'wb', {:force_quotes => true}) do |csv|
|
19
|
csv << [NAME, ORGANIZATIONS, LOCATIONS, DESCRIPTION, PROVIDER, URL]
|
20
|
@api.resource(:compute_resources).call(:index, {:per_page => 999999})['results'].each do |compute_resource|
|
21
|
compute_resource = @api.resource(:compute_resources).call(:show, {'id' => compute_resource['id']})
|
22
|
|
23
|
name = compute_resource['name']
|
24
|
organizations = export_column(compute_resource, 'organizations', 'name')
|
25
|
locations = export_column(compute_resource, 'locations', 'name')
|
26
|
description = compute_resource['description']
|
27
|
provider = compute_resource['provider']
|
28
|
url = compute_resource['url']
|
29
|
csv << [name, organizations, locations, description, provider, url]
|
30
|
end
|
31
|
end
|
32
|
end
|
33
|
|
34
|
def import
|
35
|
@existing = {}
|
36
|
@api.resource(:compute_resources).call(:index, {:per_page => 999999})['results'].each do |compute_resource|
|
37
|
@existing[compute_resource['name']] = compute_resource['id'] if compute_resource
|
38
|
end
|
39
|
|
40
|
thread_import do |line|
|
41
|
create_compute_resources_from_csv(line)
|
42
|
end
|
43
|
end
|
44
|
|
45
|
def create_compute_resources_from_csv(line)
|
46
|
count(line[COUNT]).times do |number|
|
47
|
name = namify(line[NAME], number)
|
48
|
params = {
|
49
|
'compute_resource' => {
|
50
|
'name' => name,
|
51
|
'url' => line[URL],
|
52
|
'provider' => line[PROVIDER]
|
53
|
}
|
54
|
}
|
55
|
if !@existing.include? name
|
56
|
print "Creating compute resource '#{name}'..." if option_verbose?
|
57
|
id = @api.resource(:compute_resources).call(:create, params)['id']
|
58
|
else
|
59
|
print "Updating compute resource '#{name}'..." if option_verbose?
|
60
|
id = @existing[name]
|
61
|
params['id'] = id
|
62
|
@api.resource(:compute_resources).call(:update, params)
|
63
|
end
|
64
|
|
65
|
|
66
|
|
67
|
|
68
|
|
69
|
|
70
|
print "done\n" if option_verbose?
|
71
|
end
|
72
|
rescue RuntimeError => e
|
73
|
raise "#{e}\n #{line}"
|
74
|
end
|
75
|
end
|
76
|
end
|
77
|
end
|