class Chef::Knife::CloudstackKeypairCreate

Public Instance Methods

run() click to toggle source
# File lib/chef/knife/cloudstack_keypair_create.rb, line 44
def run
  $stdout.sync = true

  validate!

  options = {}
  if locate_config_value(:publickey) != nil
    options['publickey'] = locate_config_value(:publickey)
    mode = 'register'
    if locate_config_value(:name) != nil
      options['name'] = locate_config_value(:name)
    end
  else
    mode = 'create'
    if locate_config_value(:name) != nil
      keypair_name = locate_config_value(:name)
    end
  end

  case mode
  when 'register'
    response = connection.register_ssh_key_pair(options['publickey'], options['name'])
    sshkeypair = response['registersshkeypairresponse']['keypair']

    sshkeypair_list = [
      ui.color('Name', :bold),
      ui.color('Fingerprint', :bold),
      ui.color('Private Key', :bold)
    ]

    sshkeypair_list << sshkeypair['name'].to_s
    sshkeypair_list << sshkeypair['fingerprint'].to_s
    sshkeypair_list << sshkeypair['privatekey'].to_s
    puts ui.list(sshkeypair_list, :columns_across, 3)
  when 'create'
    response = connection.create_ssh_key_pair(keypair_name,options)
    sshkeypair = response['createsshkeypairresponse']['keypair']

    if locate_config_value(:outfile) != nil
      output = locate_config_value(:outfile)
      File.open(output,'w'){|f|
        f.print sshkeypair['privatekey'].to_s
      }
    else
      sshkeypair_list = [
        ui.color('Private Key', :bold)
      ]
      sshkeypair_list << sshkeypair['privatekey'].to_s
      puts ui.list(sshkeypair_list, :columns_across, 3)
    end
  else
    puts 'Error. Missing Keypair Name (-k) option.'
  end

end