Module: Capistrano::OneTimeKey

Defined in:
lib/capistrano/one_time_key.rb,
lib/capistrano/one_time_key/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.add_key_to_host(capistrano_host, public_key) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/capistrano/one_time_key.rb', line 47

def self.add_key_to_host capistrano_host, public_key
  execute_on_remote capistrano_host, "mkdir -p ~/.ssh && \
    chmod 700 ~/.ssh && \
    touch ~/.ssh/authorized_keys && \
    chmod 600 ~/.ssh/authorized_keys && \
    echo '#{public_key}' >> ~/.ssh/authorized_keys"
end

.commentObject



16
17
18
# File 'lib/capistrano/one_time_key.rb', line 16

def self.comment
  @comment ||= "capistrano-otk-#{SecureRandom.hex(6)}"
end

.execute_on_remote(capistrano_host, command) ⇒ Object



59
60
61
# File 'lib/capistrano/one_time_key.rb', line 59

def self.execute_on_remote capistrano_host, command
  `echo "#{command}" | ssh #{capistrano_host.user}@#{capistrano_host.hostname}`
end

.generate_one_time_key!Object



25
26
27
# File 'lib/capistrano/one_time_key.rb', line 25

def self.generate_one_time_key!
  # This is a no-op because it's called everywhere.
end

.generate_private_key!Object



20
21
22
23
# File 'lib/capistrano/one_time_key.rb', line 20

def self.generate_private_key!
  `ssh-keygen -m PEM -f #{temporary_ssh_private_key_path} -N "" -C "#{comment}"`
  return temporary_ssh_private_key_path
end

.remove_key_from_host(capistrano_host, public_key) ⇒ Object



55
56
57
# File 'lib/capistrano/one_time_key.rb', line 55

def self.remove_key_from_host capistrano_host, public_key
  execute_on_remote capistrano_host, "sed -i.bak -e '/#{comment}$/d' -e '/^$/d' ~/.ssh/authorized_keys && rm ~/.ssh/authorized_keys.bak"
end

.temporary_ssh_private_key_pathObject



12
13
14
# File 'lib/capistrano/one_time_key.rb', line 12

def self.temporary_ssh_private_key_path
  File.join(tmpdir, "capistrano_key")
end

.tmpdirObject



8
9
10
# File 'lib/capistrano/one_time_key.rb', line 8

def self.tmpdir
  @dirname ||= Dir.mktmpdir
end

.use_one_time_key!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/capistrano/one_time_key.rb', line 29

def self.use_one_time_key!
  path = generate_private_key!

  public_key = File.read("#{path}.pub")

  on roles(:all) do |host|
    Capistrano::OneTimeKey.add_key_to_host host, public_key
  end

  at_exit do
    # remove dirname locally
    FileUtils.remove_entry Capistrano::OneTimeKey.tmpdir
    on roles(:all) do |host|
      Capistrano::OneTimeKey.remove_key_from_host host, public_key
    end
  end
end