Module: Ec2Select

Defined in:
lib/ec2_select.rb

Defined Under Namespace

Classes: NoEctwoFile

Constant Summary collapse

ECTWOS_FILE =
File.expand_path('~/.ec2-select')

Instance Method Summary collapse

Instance Method Details

#cert(profile) ⇒ Object



36
37
38
# File 'lib/ec2_select.rb', line 36

def cert(profile)
  "#{pempath}/cert-#{profile}.pem"
end

#pempathObject



17
18
19
# File 'lib/ec2_select.rb', line 17

def pempath
  ENV['EC2_PEMFILES'] ? File.expand_path(ENV['EC2_PEMFILES']) : File.expand_path('~/.ec2')
end

#private_key(profile) ⇒ Object



32
33
34
# File 'lib/ec2_select.rb', line 32

def private_key(profile)
  "#{pempath}/pk-#{profile}.pem"
end

#rewrite(profile) ⇒ Object



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
# File 'lib/ec2_select.rb', line 40

def rewrite(profile)
  # Validation
  if profile !~ /[A-Za-z0-9\.\-_~+=]/
    raise "Uh Oh!  Profile can only have valid filename characters!"
  end
  if !File.exist? private_key(profile)
    raise "Private key #{private_key(profile)} does not exist!"
  end
  if !File.exist? cert(profile)
    raise "Cert #{cert(profile)} does not exist!"
  end

  # Content
  content = "# Dynamically created by ec2-select\n"
  content << "# Currently PROFILE=#{profile}\n\n"
  content << case shell
  when /bash|.?sh/
    "export EC2_PRIVATE_KEY=\"#{private_key(profile)}\"\n" +
    "export EC2_CERT=\"#{cert(profile)}\"\n"
  when /.?csh/
    "setenv EC2_PRIVATE_KEY \"#{private_key(profile)}\"\n" +
    "setenv EC2_CERT \"#{cert(profile)}\"\n"
  else
    $stderr.puts "Unknown shell `#{shell}'"
    exit 1
  end
  

  File.open(ECTWOS_FILE, 'w') {|f| f.write(content) }

  "IMPORTANT!!! You need re-source if you want to use #{profile}\n" +
  "in this terminal session!  This should do the trick:\n" +
  "\n  source #{ECTWOS_FILE}\n\n" +
  "Any new terminal sessions will use this profile as long as you\n" +
  "have 'source #{ECTWOS_FILE}' in your ~/.profile or\n" +
  "~/.bashrc, ~/.bash_profile (or similar)."
end

#rewrite_or_show(profile = nil) ⇒ Object



7
8
9
10
# File 'lib/ec2_select.rb', line 7

def rewrite_or_show(profile=nil)
  return show if profile.nil?
  rewrite(profile) unless profile.nil?
end

#shellObject



21
22
23
24
25
26
27
28
29
30
# File 'lib/ec2_select.rb', line 21

def shell
  unless const_defined? 'SHELL'
    begin
      require File.expand_path('~/.ec2-select')
    rescue LoadError
      const_set("SHELL", 'bash')
    end
  end
  SHELL
end

#showObject



12
13
14
15
# File 'lib/ec2_select.rb', line 12

def show
  current = ENV['EC2_PRIVATE_KEY'].gsub(/.*pk-(.*)\.pem$/, '\\1')
  "Your current profile is: #{current}"
end