File: key_pair.rb

package info (click to toggle)
ruby-fog-openstack 1.1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,784 kB
  • sloc: ruby: 47,937; makefile: 5; sh: 4
file content (56 lines) | stat: -rw-r--r-- 1,461 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
require 'fog/openstack/models/model'

module Fog
  module OpenStack
    class Compute
      class KeyPair < Fog::OpenStack::Model
        identity  :name

        attribute :fingerprint
        attribute :public_key
        attribute :private_key
        attribute :user_id
        attribute :id

        attr_accessor :public_key

        def destroy
          requires :name

          service.delete_key_pair(name)
          true
        end

        def save
          requires :name

          data = if public_key
                   service.create_key_pair(name, public_key, user_id).body['keypair']
                 else
                   service.create_key_pair(name, nil, user_id).body['keypair']
                 end
          new_attributes = data.reject { |key, _value| !['fingerprint', 'public_key', 'name', 'private_key', 'user_id'].include?(key) }
          merge_attributes(new_attributes)
          true
        end

        def write(path = "#{ENV['HOME']}/.ssh/fog_#{Fog.credential}_#{name}.pem")
          if writable?
            split_private_key = private_key.split(/\n/)
            File.open(path, "w") do |f|
              split_private_key.each { |line| f.puts line }
              f.chmod 0600
            end
            "Key file built: #{path}"
          else
            "Invalid private key"
          end
        end

        def writable?
          !!(private_key && ENV.key?('HOME'))
        end
      end
    end
  end
end