Skip to content

Instantly share code, notes, and snippets.

@RogerWebb
Created February 2, 2023 21:29
Show Gist options
  • Save RogerWebb/99e93ae29bbe36e612ed9da62c62e54f to your computer and use it in GitHub Desktop.
Save RogerWebb/99e93ae29bbe36e612ed9da62c62e54f to your computer and use it in GitHub Desktop.
Deploy AWS Chalice Project via Docker and Serverless Application Model
import boto3, json, os, shutil, subprocess
from argparse import ArgumentParser
"""
Big Chalice Deployer deployes Chalice Apps using the "chalice package ..." command and
modifies the resulting sam.json template to make use of the Docker deployment process
instead of the default, s3 based, process. Additionally, the ability to delete the
resulting SAM App is available via the CLI.
Usage:
Place bigchalice.py in the parent folder to your Chalice Project and use the following:
Deploy:
python bigchalice.py deploy <project>
Delete:
python bigchalice.py delete <project>
Dry Run (Produce the modified SAM Project (zip and sam.json), but do not deploy:
python bigchalice.py deploy <project> --dry-run
LICENSE:
Copyright 2023 Roger Webb and Kiosk Creative LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class BigChaliceDeployer:
def __init__(self, chalice_project, region=None, dry_run=False):
# Config
self.chalice_project = chalice_project
self.region = region if region is not None else boto3.session.Session().region_name
self.dry_run = dry_run
# Paths
self.curdir = os.path.realpath(os.path.dirname(__file__))
self.chalice_project_path = os.path.join(self.curdir, self.chalice_project)
self.chalice_package_path = os.path.join(self.curdir, 'dist')
self.chalice_deployment_zip_path = os.path.join(self.chalice_package_path, 'deployment.zip')
self.chalice_sam_json_in_path = os.path.join(self.chalice_package_path, 'sam.json')
self.chalice_sam_json_out_path = os.path.join(self.chalice_package_path, 'sam.image.json')
self.chalice_samconfig_toml_out_path = os.path.join(self.chalice_package_path, 'samconfig.toml')
self.chalice_docker_build_path = os.path.join(self.chalice_package_path, 'docker-build')
self.chalice_dockerfile_path = os.path.join(self.chalice_docker_build_path, 'Dockerfile')
self.cloudformation_stack_name = self.chalice_project # For delete operation
def clean(self):
print("Cleaning up any previous builds...")
try:
shutil.rmtree(self.chalice_package_path)
except Exception as e:
print(e)
def deploy(self):
# Clean Up (ie Delete) Previous Build
self.clean()
# Build Chalice Package using CLI (chalice package /path/to/dist)
self.build_chalice_package()
# Transform sam.json, changing Zip config to Image
self.transform_chalice_package()
# Generate and Write samconfig.toml
self.generate_samconfig()
# Generate and Write Dockerfile
self.generate_dockerfile()
# Execute "sam build" and "sam deploy" commands, publishing the Stack
if not self.dry_run:
self.local_build()
self.deploy_sam_application()
def build_chalice_package(self):
print("Building Chalice Deployment Package...")
os.chdir(self.chalice_project_path)
cmd = "chalice package {}".format(self.chalice_package_path)
print(cmd)
subprocess.call(cmd, shell=True)
os.chdir(self.curdir)
def transform_chalice_package(self):
print("Transforming Chalice SAM Template (Swapping Zip Package for ECR Image)...")
print("Extracting Chalice Package...")
os.chdir(self.chalice_package_path)
cmd = "unzip {} -d {}".format(self.chalice_deployment_zip_path, self.chalice_docker_build_path)
print(cmd)
subprocess.call(cmd, shell=True)
print("Updating APIHandler in SAM Tempate to switch from Zip to Image PackageType with Docker Properties...")
with open(self.chalice_sam_json_in_path, 'r') as fp:
sam_template = json.load(fp)
api_handler = sam_template['Resources']['APIHandler']
# Remove Zip Package Related Properties
del api_handler["Properties"]["Runtime"]
del api_handler["Properties"]["Handler"]
del api_handler["Properties"]["CodeUri"]
api_handler["Properties"]["PackageType"] = "Image"
api_handler["Metadata"] = {
"DockerTag": "chalice-{}".format(self.chalice_project),
"DockerContext": self.chalice_docker_build_path,
"Dockerfile": "Dockerfile"
}
sam_template['Resources']['APIHandler'] = api_handler
print("Writing updated SAM Template to {}...".format(self.chalice_sam_json_out_path))
with open(self.chalice_sam_json_out_path, 'w') as fp:
fp.write(json.dumps(sam_template, indent=4))
def generate_dockerfile(self):
with open(self.chalice_dockerfile_path, 'w') as fp:
fp.write('FROM public.ecr.aws/lambda/python:3.8\nCOPY . ${LAMBDA_TASK_ROOT}\nCMD [ "app.app" ]')
def generate_samconfig(self):
samconfig = "version = 0.1\n[default]\n[default.deploy]\n[default.deploy.parameters]\n"
samconfig += 'stack_name = "{}"\nregion = "{}"\ncapabilities = "CAPABILITY_IAM"\n'.format(self.chalice_project, self.region)
#samconfig += "image_repositories = []\n"
with open(self.chalice_samconfig_toml_out_path, 'w') as fp:
fp.write(samconfig)
def local_build(self):
os.chdir(self.chalice_package_path)
cmd = "sam build -t {}".format(self.chalice_sam_json_out_path)
print(cmd)
subprocess.call(cmd, shell=True)
os.chdir(self.curdir)
def deploy_sam_application(self):
os.chdir(self.chalice_package_path)
# Deploy SAM Application
cmd = "sam deploy --resolve-image-repos --resolve-s3"
print(cmd)
subprocess.call(cmd, shell=True)
os.chdir(self.curdir)
def delete_sam_application(self):
os.chdir(self.chalice_package_path)
# Deploy SAM Application
cmd = "sam delete {}".format(self.cloudformation_stack_name)
print(cmd)
subprocess.call(cmd, shell=True)
os.chdir(self.curdir)
# Command Line Interface
if __name__ == "__main__":
ap = ArgumentParser()
ap.add_argument("command", choices=["deploy", "delete"])
ap.add_argument("chalice_project")
ap.add_argument("--region")
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
deployer = BigChaliceDeployer(args.chalice_project, region=args.region, dry_run=args.dry_run)
if args.command == "deploy":
deployer.deploy()
elif args.command == "delete":
deployer.delete_sam_application()
else:
print("ERROR! INVALID COMMAND")
print("DONE!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment