/
aws-keys.rb
46 lines (38 loc) · 1.01 KB
/
aws-keys.rb
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
module AwsKeys
class KeyNotFoundException < Exception; end
class Key
attr_accessor :id, :secret
def initialize (id, secret)
@id = id
@secret = secret
end
end
PATHS = [".ec2"]
PATHS.push(File.expand_path("~/.ec2")) if ENV["HOME"]
PATHS.push("/etc/ec2")
def self.find_key_path (type)
PATHS.each do |path|
key_path = File.join(path, "#{type}.creds")
return key_path if File.exists? key_path
end
return
end
def self.key_path (type)
find_key_path(type) || find_key_path("all")
end
def self.keys (type)
path = key_path(type)
return unless path
data = File.read(path)
# Explicitly match with regex, to make sure our data is right
re = /AWSAccessKeyId=([A-Z0-9]+)\nAWSSecretKey=([^\n]+)\n?$/
return Key.new($1, $2) if data =~ re
return
end
# Raises an exception if the keys can't be found
def self.keys! (type)
k = keys(type)
raise KeyNotFoundException.new("Could not find key of type: #{type}") unless k
k
end
end