Class: Dev::Certificate

Inherits:
Object show all
Defined in:
lib/firespring_dev_commands/certificate.rb

Overview

Class contains methods for requesting a certificate from route53. You must have a hosted zone defined for the desired domain

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(domains, email) ⇒ Certificate

Returns a new instance of Certificate.



7
8
9
10
11
# File 'lib/firespring_dev_commands/certificate.rb', line 7

def initialize(domains, email)
  @domains = Array(domains)
  @email = email
  raise 'No certificate domains specified' if domains.empty?
end

Instance Attribute Details

#domainsObject

Returns the value of attribute domains.



5
6
7
# File 'lib/firespring_dev_commands/certificate.rb', line 5

def domains
  @domains
end

#emailObject

Returns the value of attribute email.



5
6
7
# File 'lib/firespring_dev_commands/certificate.rb', line 5

def email
  @email
end

Instance Method Details

#requestObject

Request the certificate using the route53 docker image Certificate is stored in /etc/letsencrypt



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
# File 'lib/firespring_dev_commands/certificate.rb', line 15

def request
  puts
  puts 'Getting SSL Certs For:'
  puts domains.join("\n")
  puts
  puts 'This process can take up to 10 minutes'
  puts
  puts Time.now

  # TODO: Really should use the docker api for this
  cmd = %w(docker run -it --rm --name certbot)
  cmd << '-e' << 'AWS_ACCESS_KEY_ID'
  cmd << '-e' << 'AWS_SECRET_ACCESS_KEY'
  cmd << '-e' << 'AWS_SESSION_TOKEN'
  cmd << '-v' << '/etc/letsencrypt:/etc/letsencrypt'
  cmd << 'certbot/dns-route53:latest'
  cmd << 'certonly'
  cmd << '-n'
  cmd << '--agree-tos'
  cmd << '--dns-route53'
  cmd << '-d' << domains.join(',')
  cmd << '--email' << email
  cmd << '--server' << 'https://acme-v02.api.letsencrypt.org/directory'
  puts cmd.join(' ')
  Dev::Common.new.run_command(cmd)
end

#save(dest_dir) ⇒ Object

Saves the latest version of the certificate into the given dest_dir



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/firespring_dev_commands/certificate.rb', line 43

def save(dest_dir)
  raise "directory #{dest_dir} must be an existing directory" unless File.directory?(dest_dir)

  domain = domains.first.sub(/^\*\./, '') # Need to strip off the '*.' if this is a wildcard cert
  directories = Dir.glob("/etc/letsencrypt/live/#{domain}*/")
  no_suffix = directories.delete("/etc/letsencrypt/live/#{domain}/")
  biggest_suffix = directories.max
  source_dir = biggest_suffix || no_suffix
  raise "unable to determine certificate directory for #{domain}" unless source_dir

  FileUtils.cp("#{source_dir}privkey.pem", dest_dir, verbose: true)
  FileUtils.cp("#{source_dir}cert.pem", dest_dir, verbose: true)
  FileUtils.cp("#{source_dir}chain.pem", dest_dir, verbose: true)
  FileUtils.cp("#{source_dir}fullchain.pem", dest_dir, verbose: true)
end