Class: Morpheus::Cli::CypherCommand
- Inherits:
-
Object
- Object
- Morpheus::Cli::CypherCommand
- Includes:
- CliCommand
- Defined in:
- lib/morpheus/cli/cypher_command.rb
Instance Attribute Summary
Attributes included from CliCommand
Instance Method Summary collapse
- #connect(opts) ⇒ Object
- #get(args) ⇒ Object
- #handle(args) ⇒ Object
-
#initialize ⇒ CypherCommand
constructor
some appropriate aliases register_subcommands :read => :get, register_subcommands :write => :put register_subcommands :add => :put register_subcommands :delete => :remove register_subcommands :destroy => :destroy.
- #list(args) ⇒ Object
- #put(args) ⇒ Object
- #remove(args) ⇒ Object
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_id_list, #parse_list_options, #parse_list_subtitles, #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!
Constructor Details
#initialize ⇒ CypherCommand
some appropriate aliases register_subcommands :read => :get, register_subcommands :write => :put register_subcommands :add => :put register_subcommands :delete => :remove register_subcommands :destroy => :destroy
17 18 19 |
# File 'lib/morpheus/cli/cypher_command.rb', line 17 def initialize() # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance end |
Instance Method Details
#connect(opts) ⇒ Object
21 22 23 24 25 |
# File 'lib/morpheus/cli/cypher_command.rb', line 21 def connect(opts) @api_client = establish_remote_appliance_connection(opts) # @cypher_interface = @api_client.cypher @cypher_interface = @api_client.cypher end |
#get(args) ⇒ Object
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 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 217 218 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 |
# File 'lib/morpheus/cli/cypher_command.rb', line 112 def get(args) = {} params = {} value_only = false do_decrypt = false item_ttl = nil optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") # opts.on(nil, '--decrypt', 'Display the decrypted value') do # do_decrypt = true # end # opts.on(nil, '--metadata', 'Display metadata about the key, such as versions.') do # display_versions = true # end opts.on('-v', '--value', 'Print only the decrypted value.') do value_only = true end opts.on( '-t', '--ttl SECONDS', "Time to live, the lease duration before this key expires. Use if creating new key." ) do |val| item_ttl = val if val.to_s.empty? || val.to_s == '0' item_ttl = 0 else item_ttl = val end end (opts, , [:json, :yaml, :csv, :fields, :dry_run, :quiet, :remote]) opts. = "Read a cypher item and display the decrypted value." + "\n" + "[key] is required. This is the cypher key to read." + "\n" + "Use --ttl to specify a ttl if expecting cypher engine to automatically create the key." 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}\n#{optparse}" return 1 end connect() begin item_key = args[0] if item_ttl params["ttl"] = item_ttl end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.get(item_key, params) return 0 end json_response = @cypher_interface.get(item_key, params) if [:quiet] return 0 end if [:json] puts as_json(json_response, ) return 0 elsif [:yaml] puts as_yaml(json_response, ) return 0 elsif [:csv] puts records_as_csv([json_response], ) return 0 end cypher_item = json_response['cypher'] decrypted_value = json_response["data"] if value_only print cyan if decrypted_value.is_a?(Hash) puts as_json(decrypted_value) else puts decrypted_value.to_s end print reset return 0 end print_h1 "Cypher Key", [], print cyan # This response does contain cypher too though. if cypher_item.empty? puts_error "Cypher data not found in response" return 1 end description_cols = { #"ID" => 'id', "Key" => lambda {|it| it["itemKey"] }, "TTL" => lambda {|it| format_expiration_ttl(it["expireDate"]) }, "Expiration" => lambda {|it| format_expiration_date(it["expireDate"]) }, "Date Created" => lambda {|it| format_local_dt(it["dateCreated"]) }, "Last Access" => lambda {|it| format_local_dt(it["lastAccessed"]) } } if cypher_item["expireDate"].nil? description_cols.delete("Expires") end print_description_list(description_cols, cypher_item) print_h2 "Value", # print_h2 "Decrypted Value" if decrypted_value print cyan if decrypted_value.is_a?(String) # attempt to parse and render as_json if decrypted_value.to_s[0] == '{' && decrypted_value.to_s[-1] == '}' begin json_value = JSON.parse(decrypted_value) puts as_json(json_value) rescue => ex Morpheus::Logging::DarkPrinter.puts "Failed to parse cypher value '#{decrypted_value}' as JSON. Error: #{ex}" if Morpheus::Logging.debug? puts decrypted_value end else puts decrypted_value end else puts as_json(decrypted_value) end else puts "No data found." end print reset, "\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) return 1 end end |
#handle(args) ⇒ Object
27 28 29 |
# File 'lib/morpheus/cli/cypher_command.rb', line 27 def handle(args) handle_subcommand(args) end |
#list(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 54 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/morpheus/cli/cypher_command.rb', line 31 def list(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") # opts.on('--details', '--details', "Show more details." ) do # options[:details] = true # end (opts, , [:list, :query, :json, :yaml, :csv, :fields, :json, :dry_run, :remote]) opts. = "List cypher keys." + "\n" + "[key] is optional. This is the cypher key or path to search for." end optparse.parse!(args) connect() if args.count > 1 print_error Morpheus::Terminal.angry_prompt puts_error "wrong number of arguments, expected 0-1 and got #{args.count}\n#{optparse}" return 1 end item_key = args[0] begin params.merge!(()) @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.list(item_key, params) return 0 end json_response = @cypher_interface.list(item_key, params) if [:json] puts as_json(json_response, ) return 0 elsif [:yaml] puts as_yaml(json_response, ) return 0 elsif [:csv] puts records_as_csv([json_response], ) return 0 end cypher_data = json_response["data"] title = "Morpheus Cypher Key List" subtitles = [] subtitles += parse_list_subtitles() if item_key subtitles << "Key: #{item_key}" end print_h1 title, subtitles, cypher_keys = json_response["data"] ? json_response["data"]["keys"] : [] if cypher_keys.nil? || cypher_keys.empty? if item_key print cyan,"No cypher items found for '#{item_key}'.",reset,"\n" end else cypher_columns = { "KEY" => lambda {|it| it["itemKey"] }, # "LEASE REMAINING" => lambda {|it| # format_lease_remaining(it["expireDate"]) # }, "TTL" => lambda {|it| format_expiration_ttl(it["expireDate"]) }, "EXPIRATION" => lambda {|it| format_expiration_date(it["expireDate"]) }, "DATE CREATED" => lambda {|it| format_local_dt(it["dateCreated"]) }, "LAST ACCESS" => lambda {|it| format_local_dt(it["lastAccessed"]) } } print cyan print as_pretty_table(json_response["cypherItems"], cypher_columns, ) print reset print_results_pagination({size:cypher_keys.size,total:cypher_keys.size.to_i}) end print reset,"\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#put(args) ⇒ Object
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 300 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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
# File 'lib/morpheus/cli/cypher_command.rb', line 249 def put(args) = {} params = {} item_key = nil item_value = nil item_ttl = nil no_overwrite = nil optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key] [value]") # opts.on( '--key VALUE', String, "Key" ) do |val| # item_key = val # end opts.on( '-v', '--value VALUE', "Secret value" ) do |val| item_value = val end opts.on( '-t', '--ttl SECONDS', "Time to live, the lease duration before this key expires." ) do |val| item_ttl = val if val.to_s.empty? || val.to_s == '0' item_ttl = 0 else item_ttl = val end end # opts.on( '--no-overwrite', '--no-overwrite', "Do not overwrite existing keys. Existing keys are overwritten by default." ) do # params['overwrite'] = false # end (opts, , [:auto_confirm, :options, :payload, :json, :dry_run, :quiet, :remote]) opts. = "Create or update a cypher key." + "\n" + "[key] is required. This is the key of the cypher being created or updated." + "\n" + "[value] is required. This is the new value or value pairs being stored. Supports format foo=bar, 1-N arguments." + "\n" + "The --payload option can be used instead of passing [value] argument." end optparse.parse!(args) # if args.count < 1 # print_error Morpheus::Terminal.angry_prompt # puts_error "wrong number of arguments, expected 1-N and got #{args.count}\n#{optparse}" # return 1 # end connect() begin if args[0] item_key = args[0] end [:options] ||= {} [:options]['key'] = item_key if item_key # Key prompt v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'key', 'fieldLabel' => 'Key', 'type' => 'text', 'required' => true, 'description' => cypher_key_help}], [:options]) item_key = v_prompt['key'] payload = nil if [:payload] payload = [:payload] payload.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) || ['key','value'].include?(k)}) if [:options] && [:options].keys.size > 0 else # merge -O options into normally parsed options params.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) || ['key','value'].include?(k)}) if [:options] && [:options].keys.size > 0 # Value prompt value_is_required = false cypher_mount_type = item_key.split("/").first if ["secret"].include?(cypher_mount_type) value_is_required = true end # todo: read value from STDIN shall we? # cool, we got value as arguments like foo=bar if args.count > 1 # parse one and only arg as the value like password/mine mypassword123 if args.count == 2 && args[1].split("=").size() == 1 item_value = args[1] elsif args.count > 1 # parse args as key value pairs like secret/config foo=bar thing=myvalue value_arguments = args[1..-1] value_arguments_map = {} value_arguments.each do |value_argument| value_pair = value_argument.split("=") value_arguments_map[value_pair[0]] = value_pair[1] ? value_pair[1..-1].join("=") : nil end item_value = value_arguments_map end else # Prompt for a single text value to be sent as {"value":"my secret"} if value_is_required [:options]['value'] = item_value if item_value v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'value', 'fieldLabel' => 'Value', 'type' => 'text', 'required' => value_is_required, 'description' => "Secret value for this cypher"}], [:options]) item_value = v_prompt['value'] end end # construct payload # payload = { # 'cypher' => params # } # if value is valid json, then the payload IS the value if item_value.is_a?(String) && item_value.to_s[0] == '{' && item_value.to_s[-1] == '}' begin json_object = JSON.parse(item_value) item_value = json_object rescue => ex Morpheus::Logging::DarkPrinter.puts "Failed to parse cypher value '#{item_value}' as JSON. Error: #{ex}" if Morpheus::Logging.debug? raise_command_error "Failed to parse cypher value as JSON: #{item_value}" # return 1 end else # it is just a string if item_value.is_a?(String) payload = {"value" => item_value} elsif item_value.nil? payload = {} else item_value # great, a Hash I hope payload = item_value end end end # prompt for Lease [:options]['ttl'] = item_ttl if item_ttl v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'ttl', 'fieldLabel' => 'Lease (TTL in seconds)', 'type' => 'text', 'required' => false, 'description' => cypher_ttl_help}], [:options]) item_ttl = v_prompt['ttl'] if item_ttl # I would like this better as params... payload["ttl"] = item_ttl end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.create(item_key, payload) return end existing_cypher = nil json_response = @cypher_interface.list(item_key) if json_response["data"] && json_response["data"]["keys"] existing_cypher = json_response["data"]["keys"].find {|k| k == item_key } end if existing_cypher unless [:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to overwrite the cypher key #{item_key}?") return 9, "aborted command" end end json_response = @cypher_interface.create(item_key, payload) if [:json] puts as_json(json_response, ) elsif ![:quiet] print_green_success "Wrote cypher #{item_key}" # should print without doing get, because that can use a token. cypher_item = json_response['cypher'] get([item_key]) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#remove(args) ⇒ Object
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
# File 'lib/morpheus/cli/cypher_command.rb', line 408 def remove(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") (opts, , [:auto_confirm, :json, :dry_run, :quiet, :remote]) opts. = "Delete a cypher." + "\n" + "[key] is required. This is the key of a cypher." 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}\n#{optparse}" return 1 end connect() begin item_key = args[0] cypher_item = find_cypher_by_key(item_key) return 1 if cypher_item.nil? unless [:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the cypher #{item_key}?") return 9, "aborted command" end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.destroy(item_key, params) return end json_response = @cypher_interface.destroy(item_key, params) if [:json] puts as_json(json_response, ) elsif ![:quiet] print_green_success "Deleted cypher #{item_key}" # list([]) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) return 1 end end |