Class: Morpheus::Cli::LibraryResourceSpecsCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/library_resource_specs_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_refresh_interval, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_payload, #parse_query_options, #print, #print_error, #puts, #puts_error, #raise_command_error, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Instance Method Details

#_get(id, options) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 82

def _get(id, options)

  begin
    resource_spec = find_resource_spec_by_name_or_id(id)
    if resource_spec.nil?
      return 1
    end
    @resource_specs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @resource_specs_interface.dry.get(resource_spec['id'])
      return
    end
    json_response = @resource_specs_interface.get(resource_spec['id'])
    resource_spec = json_response['specTemplate']
    instances = json_response['instances'] || []
    servers = json_response['servers'] || []
    if options[:json]
      puts as_json(json_response, options, 'specTemplate')
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, 'specTemplate')
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['specTemplate']], options)
      return 0
    end

    print_h1 "Resource Spec Details"
    print cyan
    detemplateion_cols = {
      "ID" => lambda {|it| it['id'] },
      "Name" => lambda {|it| it['name'] },
      "Type" => lambda {|it| format_resource_spec_type(it['templateType']) },
      "Source" => lambda {|it| it['source'] },
      #"Owner" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Created By" => lambda {|it| it['createdBy'] },
      "Updated By" => lambda {|it| it['updatedBy'] },
      "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
    }
    print_detemplateion_list(detemplateion_cols, resource_spec)

    print_h2 "Content"

    puts resource_spec['content']

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#add(args) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 136

def add(args)
  options = {}
  params = {'templateType' => 'bash', 'templatePhase' => 'provision'}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val
    end
    opts.on('--type [kubernetes|helm|terraform]', String, "Spec Template Type.") do |val|
      params['templateType'] = val
    end
    # opts.on('--phase [provision|start|stop]', String, "Template Phase. Default is 'provision'") do |val|
    #   params['templatePhase'] = val
    # end
    opts.on('--category VALUE', String, "Category") do |val|
      params['category'] = val
    end
    opts.on('--template TEXT', String, "Contents of the template.") do |val|
      params['template'] = val
    end
    opts.on('--file FILE', "File containing the template. This can be used instead of --template" ) do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        params['template'] = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        exit 1
      end
      # use the filename as the name by default.
      if !params['name']
        params['name'] = File.basename(full_filename)
      end
    end
    # opts.on('--enabled [on|off]', String, "Can be used to disable it") do |val|
    #   options['enabled'] = !(val.to_s == 'off' || val.to_s == 'false')
    # end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create a new spec template." + "\n" +
                  "[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  # support [name] as first argument
  if args[0]
    params['name'] = args[0]
  end
  if !params['name']
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # todo: prompt?
      payload = {'specTemplate' => params}
    end
    @resource_specs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @resource_specs_interface.dry.create(payload)
      return
    end
    json_response = @resource_specs_interface.create(payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      resource_spec = json_response['specTemplate']
      print_green_success "Added spec template #{resource_spec['name']}"
      _get(resource_spec['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#connect(opts) ⇒ Object



10
11
12
13
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 10

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @resource_specs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).library_resource_specs
end

#get(args) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 64

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



15
16
17
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 15

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 19

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List resource spec templates."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  begin
    # construct payload
    params.merge!(parse_list_options(options))
    @resource_specs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @resource_specs_interface.dry.list(params)
      return
    end
    # do it
    json_response = @resource_specs_interface.list(params)
    render_result = render_with_format(json_response, options, 'specTemplates')
    return 0 if render_result
    resource_specs = json_response['specTemplates']
    title = "Morpheus Library - Resource Spec Templates"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if resource_specs.empty?
      print cyan,"No resource specs found.",reset,"\n"
    else
      print_resource_specs_table(resource_specs, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove(args) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 301

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :auto_confirm])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 127
  end
  connect(options)

  begin
    resource_spec = find_resource_spec_by_name_or_id(args[0])
    if resource_spec.nil?
      return 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete spec template '#{resource_spec['name']}'?", options)
      return false
    end

    # payload = {
    #   'specTemplate' => {id: resource_spec["id"]}
    # }
    # payload['specTemplate'].merge!(resource_spec)
    payload = params
    @resource_specs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @resource_specs_interface.dry.destroy(resource_spec["id"])
      return
    end

    json_response = @resource_specs_interface.destroy(resource_spec["id"])
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Deleted spec template #{resource_spec['name']}"
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update(args) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/morpheus/cli/library_resource_specs_command.rb', line 219

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val
    end
    # opts.on('--code VALUE', String, "Code") do |val|
    #   params['code'] = val
    # end
    # opts.on('--detemplateion VALUE', String, "Detemplateion") do |val|
    #   params['detemplateion'] = val
    # end
    opts.on('--type [bash|powershell]', String, "Template Type") do |val|
      params['templateType'] = val
    end
    opts.on('--phase [start|stop]', String, "Template Phase") do |val|
      params['templatePhase'] = val
    end
    opts.on('--category VALUE', String, "Category") do |val|
      params['category'] = val
    end
    opts.on('--template TEXT', String, "Contents of the template.") do |val|
      params['template'] = val
    end
    opts.on('--file FILE', "File containing the template. This can be used instead of --template" ) do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        params['template'] = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        exit 1
      end
    end
    # opts.on('--enabled [on|off]', String, "Can be used to disable it") do |val|
    #   options['enabled'] = !(val.to_s == 'off' || val.to_s == 'false')
    # end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Update a spec template." + "\n" +
                  "[name] is required. This is the name or id of a spec template."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    resource_spec = find_resource_spec_by_name_or_id(args[0])
    if resource_spec.nil?
      return 1
    end
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      payload = {'specTemplate' => params}
    end
    @resource_specs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @resource_specs_interface.dry.update(resource_spec["id"], payload)
      return
    end
    json_response = @resource_specs_interface.update(resource_spec["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Updated spec template #{resource_spec['name']}"
      _get(resource_spec['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end