|
8 | 8 | from shutil import copy, copyfile |
9 | 9 | from tempfile import mkdtemp |
10 | 10 |
|
| 11 | +import botocore |
11 | 12 | import boto3 |
12 | 13 | import pip |
13 | 14 | import yaml |
|
18 | 19 | log = logging.getLogger(__name__) |
19 | 20 |
|
20 | 21 |
|
| 22 | +def cleanup_old_versions(src, keep_last_versions): |
| 23 | + """Deletes old deployed versions of the function in AWS Lambda. |
| 24 | +
|
| 25 | + Won't delete $Latest and any aliased version |
| 26 | +
|
| 27 | + :param str src: |
| 28 | + The path to your Lambda ready project (folder must contain a valid |
| 29 | + config.yaml and handler module (e.g.: service.py). |
| 30 | + :param int keep_last_versions: |
| 31 | + The number of recent versions to keep and not delete |
| 32 | + """ |
| 33 | + if keep_last_versions <= 0: |
| 34 | + print("Won't delete all versions. Please do this manually") |
| 35 | + else: |
| 36 | + path_to_config_file = os.path.join(src, 'config.yaml') |
| 37 | + cfg = read(path_to_config_file, loader=yaml.load) |
| 38 | + |
| 39 | + aws_access_key_id = cfg.get('aws_access_key_id') |
| 40 | + aws_secret_access_key = cfg.get('aws_secret_access_key') |
| 41 | + |
| 42 | + client = get_client('lambda', aws_access_key_id, aws_secret_access_key, |
| 43 | + cfg.get('region')) |
| 44 | + |
| 45 | + response = client.list_versions_by_function( |
| 46 | + FunctionName=cfg.get("function_name") |
| 47 | + ) |
| 48 | + versions = response.get("Versions") |
| 49 | + if len(response.get("Versions")) < keep_last_versions: |
| 50 | + print("Nothing to delete. (Too few versions published)") |
| 51 | + else: |
| 52 | + version_numbers = [elem.get("Version") for elem in |
| 53 | + versions[1:-keep_last_versions]] |
| 54 | + for version_number in version_numbers: |
| 55 | + try: |
| 56 | + client.delete_function( |
| 57 | + FunctionName=cfg.get("function_name"), |
| 58 | + Qualifier=version_number |
| 59 | + ) |
| 60 | + except botocore.exceptions.ClientError as e: |
| 61 | + print("Skipping Version {}: {}".format(version_number, |
| 62 | + e.message)) |
| 63 | + |
| 64 | + |
21 | 65 | def deploy(src, local_package=None): |
22 | 66 | """Deploys a new function to AWS Lambda. |
23 | 67 |
|
|
0 commit comments