Class: Morpheus::Cli::KeyPairs

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, Term::ANSIColor
Defined in:
lib/morpheus/cli/key_pairs.rb

Instance Method Summary collapse

Methods included from AccountsHelper

#find_account_by_id, #find_account_by_name, #find_account_from_options, #find_role_by_id, #find_role_by_name, #find_user_by_id, #find_user_by_username, #print_accounts_table, #print_green_success, #print_red_alert, #print_roles_table, #print_users_table

Methods included from CliCommand

accountScopeOptions, genericOptions, included

Constructor Details

#initializeKeyPairs

Returns a new instance of KeyPairs.



16
17
18
# File 'lib/morpheus/cli/key_pairs.rb', line 16

def initialize() 
  @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#add(args) ⇒ Object



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
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/morpheus/cli/key_pairs.rb', line 145

def add(args)
  # if args.count > 0
  #   puts "\nUsage: morpheus hosts add [options]\n\n"
  #   exit 1
  # end
   = nil
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus key-pairs add [options]"
    
    opts.on( '-a', '--account ACCOUNT', "Account Name" ) do |val|
       = val
    end

    opts.on( '', '--public-key-file FILENAME', "Public Key File" ) do |filename|
      if File.exists?(filename)
        options['publicKey'] = File.read(filename)
        options[:options] ||= {}
        options[:options]['publicKey'] = options['publicKey']
      else
        print_red_alert "File not found: #{filename}"
        exit 1
      end
    end

    opts.on( '', '--public-key TEXT', "Public Key Text" ) do |val|
      options['publicKey'] = val
      options[:options] ||= {}
      options[:options]['publicKey'] = options['publicKey']
    end

    opts.on( '', '--private-key-file FILENAME', "Private Key File" ) do |filename|
      if File.exists?(filename)
        options['privateKey'] = File.read(filename)
        options[:options] ||= {}
        options[:options]['privateKey'] = options['privateKey']
      else
        print_red_alert "File not found: #{filename}"
        exit 1
      end
    end

    opts.on( '', '--private-key TEXT', "Private Key Text" ) do |val|
      options['privateKey'] = val
      options[:options] ||= {}
      options[:options]['privateKey'] = options['privateKey']
    end

    Morpheus::Cli::CliCommand.genericOptions(opts,options)
  end
  optparse.parse(args)

  connect(options)
  
  begin

    # current user account by default
     = nil
    if !.nil?
       = ()
      exit 1 if .nil?
    end
     =  ? ['id'] : nil

    params = Morpheus::Cli::OptionTypes.prompt(add_key_pair_option_types, options[:options], @api_client, options[:params]) # options[:params] is mysterious

    if !params['publicKey']
      print_red_alert "publicKey is required"
      exit 1
    elsif !params['privateKey']
      print_red_alert "privateKey is required"
      exit 1
    end

    key_pair_payload = params.select {|k,v| ['name', 'publicKey', 'privateKey'].include?(k) }

    request_payload = {keyPair: key_pair_payload}
    response = @key_pairs_interface.create(, request_payload)
    print "\n", cyan, "Account #{key_pair_payload['name']} added", reset, "\n\n"
  rescue RestClient::Exception => e
    ::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
    exit 1
  end
end

#connect(opts) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/morpheus/cli/key_pairs.rb', line 20

def connect(opts)
  @access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials()
  if @access_token.empty?
    print red,bold, "\nInvalid Credentials. Unable to acquire access token. Please verify your credentials and try again.\n\n",reset
    exit 1
  end
  @api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)
  @accounts_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).accounts
  @key_pairs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).key_pairs
end

#details(args) ⇒ Object



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
135
136
137
138
139
140
141
142
143
# File 'lib/morpheus/cli/key_pairs.rb', line 94

def details(args)
  usage = "Usage: morpheus key-pairs details [name] [options]"
  if args.count < 1
    puts "\n#{usage}\n\n"
    exit 1
  end
   = nil
  name = args[0]
  options = {}
  params = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage
    Morpheus::Cli::CliCommand.accountScopeOptions(opts,options)
    Morpheus::Cli::CliCommand.genericOptions(opts,options)
  end
  optparse.parse(args)
  connect(options)
  begin
  
     = (options)
     =  ? ['id'] : nil

    # todo: key_pairs_response = @key_pairs_interface.list(account_id, {name: name})
    #       there may be response data outside of account that needs to be displayed

    # allow finding by ID since name is not unique!
    key_pair = ((name.to_s =~ /\A\d{1,}\Z/) ? find_key_pair_by_id(, name) : find_key_pair_by_name(, name) )
    exit 1 if key_pair.nil?

    if options[:json]
      print JSON.pretty_generate(key_pair)
      print "\n"
    else
      print "\n" ,cyan, bold, "Key Pair Details\n","==================", reset, "\n\n"
      print cyan
      puts "ID: #{key_pair['id']}"
      puts "Name: #{key_pair['name']}"
      puts "MD5: #{key_pair['md5']}"
      puts "Date Created: #{format_local_dt(key_pair['dateCreated'])}"
      #puts "Last Updated: #{format_local_dt(key_pair['lastUpdated'])}"
      print reset,"\n\n"

      # todo: show public key

    end
  rescue RestClient::Exception => e
    ::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
    exit 1
  end
end

#handle(args) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/morpheus/cli/key_pairs.rb', line 31

def handle(args)
  usage = "Usage: morpheus key-pairs [list,add,update,remove] [name]"
  if args.empty?
    puts "\n#{usage}\n\n"
    exit 1
  end

  case args[0]
    when 'list'
      list(args[1..-1])
    when 'details'
      details(args[1..-1])
    when 'add'
      add(args[1..-1])
    when 'update'
      update(args[1..-1])
    when 'remove'
      remove(args[1..-1])
    else
      puts "\n#{usage}\n\n"
      exit 127
  end
end

#list(args) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/morpheus/cli/key_pairs.rb', line 55

def list(args)
  options = {}
  params = {}
   = nil
  optparse = OptionParser.new do|opts|
    Morpheus::Cli::CliCommand.accountScopeOptions(opts,options)
    Morpheus::Cli::CliCommand.genericOptions(opts,options)
  end
  optparse.parse(args)
  connect(options)
  begin

     = (options)
     =  ? ['id'] : nil

    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end

    json_response = @key_pairs_interface.list(, params)
    key_pairs = json_response['keyPairs']
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print "\n" ,cyan, bold, "Morpheus Key Pairs\n","==================", reset, "\n\n"
      if key_pairs.empty?
        puts yellow,"No key pairs found.",reset
      else
        print_key_pairs_table(key_pairs)
      end
      print reset,"\n\n"
    end
  rescue RestClient::Exception => e
    ::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
    exit 1
  end
end

#remove(args) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/morpheus/cli/key_pairs.rb', line 284

def remove(args)
  usage = "Usage: morpheus key-pairs remove [name]"
  if args.count < 1
    puts "\n#{usage}\n\n"
    exit 1
  end
   = nil
  name = args[0]
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage

    opts.on( '-a', '--account ACCOUNT', "Account Name or ID" ) do |val|
       = val
    end

    Morpheus::Cli::CliCommand.genericOptions(opts,options)
  end
  optparse.parse(args)
  connect(options)
  begin
    # current user account by default
     = nil
    if !.nil?
       = ()
      exit 1 if .nil?
    end
     =  ? ['id'] : nil
    # allow finding by ID since name is not unique!
    key_pair = ((name.to_s =~ /\A\d{1,}\Z/) ? find_key_pair_by_id(, name) : find_key_pair_by_name(, name) )
    exit 1 if key_pair.nil?
    exit unless Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the key pair #{key_pair['name']}?")
    @key_pairs_interface.destroy(, key_pair['id'])
    # list([])
    print "\n", cyan, "Key Pair #{key_pair['name']} removed", reset, "\n\n"
  rescue RestClient::Exception => e
    ::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
    exit 1
  end
end

#update(args) ⇒ Object



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

def update(args)
  usage = "Usage: morpheus hosts update [name] [options]"
  if args.count < 1
    puts "\n#{usage}\n\n"
    exit 1
  end
   = nil
  name = args[0]
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage

    opts.on( '-a', '--account ACCOUNT', "Account Name" ) do |val|
       = val
    end

    Morpheus::Cli::CliCommand.genericOptions(opts,options)
  end
  optparse.parse(args)

  connect(options)
  
  begin

     = nil 
    if !.nil?
       = ()
      exit 1 if .nil?
       = ['id']
    end

    key_pair = ((name.to_s =~ /\A\d{1,}\Z/) ? find_key_pair_by_id(, name) : find_key_pair_by_name(, name) )
    exit 1 if key_pair.nil?

    #params = Morpheus::Cli::OptionTypes.prompt(update_key_pair_option_types, options[:options], @api_client, options[:params]) # options[:params] is mysterious
    params = options[:options] || {}

    if params.empty?
      puts "\n#{usage}\n\n"
      option_lines = update_key_pair_option_types.collect {|it| "\t-O #{it['fieldName']}=\"value\"" }.join("\n")
      puts "\nAvailable Options:\n#{option_lines}\n\n"
      exit 1
    end

    key_pair_payload = params.select {|k,v| ['name'].include?(k) }
    request_payload = {keyPair: key_pair_payload}
    response = @key_pairs_interface.update(, key_pair['id'], request_payload)
    print "\n", cyan, "Key Pair #{key_pair_payload['name'] || key_pair['name']} updated", reset, "\n\n"
  rescue RestClient::Exception => e
    ::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
    exit 1
  end
end