Skip to content

Commit

Permalink
Refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiguangwang committed Apr 29, 2018
1 parent ce9c313 commit b701deb
Showing 1 changed file with 25 additions and 26 deletions.
51 changes: 25 additions & 26 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@
# Temp dir of Lambda runtime
CERTBOT_DIR = '/tmp/certbot'

def call_certbot(email, domains):
def rm_tmp_dir():
if os.path.exists(CERTBOT_DIR):
try:
shutil.rmtree(CERTBOT_DIR)
except NotADirectoryError:
os.remove(CERTBOT_DIR)

def obtain_certs(email, domains):
certbot_args = [
# Override directory paths so script doesn't have to be run as root
'--config-dir', CERTBOT_DIR,
Expand All @@ -29,25 +36,24 @@ def call_certbot(email, domains):
]
return certbot.main.main(certbot_args)

def publish_certs_to_s3(bucket, prefix):
# /tmp/certbot
# ├── live
# │ └── [domain]
# │ ├── README
# │ ├── cert.pem
# │ ├── chain.pem
# │ ├── fullchain.pem
# │ └── privkey.pem
def upload_certs(s3_bucket, s3_prefix):
client = boto3.client('s3')

# /tmp/certbot
# ├── live
# │ └── [domain]
# │ ├── README
# │ ├── cert.pem
# │ ├── chain.pem
# │ ├── fullchain.pem
# │ └── privkey.pem
cert_dir = os.path.join(CERTBOT_DIR, 'live')
for dirpath, _dirnames, filenames in os.walk(cert_dir):
for filename in filenames:
local_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(local_path, cert_dir)
key = os.path.join(prefix, relative_path)
print(f'Uploading: {local_path} => s3://{bucket}/{key}')
client.upload_file(local_path, bucket, key)
s3_key = os.path.join(s3_prefix, relative_path)
print(f'Uploading: {local_path} => s3://{s3_bucket}/{s3_key}')
client.upload_file(local_path, s3_bucket, s3_key)

def guarded_handler(event, context):
# Input parameters
Expand All @@ -56,21 +62,14 @@ def guarded_handler(event, context):
s3_bucket = event['s3_bucket'] # The S3 bucket to publish certificates
s3_prefix = event['s3_prefix'] # The S3 key prefix to publish certificates

call_certbot(email, domains)
publish_certs_to_s3(s3_bucket, s3_prefix)
obtain_certs(email, domains)
upload_certs(s3_bucket, s3_prefix)

return f'Certs published successfully.'

def cleanup():
if os.path.exists(CERTBOT_DIR):
try:
shutil.rmtree(CERTBOT_DIR)
except NotADirectoryError:
os.remove(CERTBOT_DIR)
return 'Certificates obtained and uploaded successfully.'

def lambda_handler(event, context):
try:
cleanup()
rm_tmp_dir()
return guarded_handler(event, context)
finally:
cleanup()
rm_tmp_dir()

0 comments on commit b701deb

Please sign in to comment.