|
| 1 | +#!/usr/bin/env python |
| 2 | +""" |
| 3 | +Script to generate the CFN template for the library into a Lambda Layer from within the CodeBuild of the Layer Build. |
| 4 | +""" |
| 5 | +from datetime import datetime as dt |
| 6 | +from os import environ |
| 7 | +from json import dumps |
| 8 | +from argparse import ArgumentParser |
| 9 | +from ozone.templates.awslambdalayer import template |
| 10 | +import boto3 |
| 11 | + |
| 12 | +def get_artifact_location(): |
| 13 | + """ |
| 14 | + Retrieves the Destination bucket and path of the Layer from CodeBuild within the job |
| 15 | + """ |
| 16 | + job_id = environ['CODEBUILD_BUILD_ID'] |
| 17 | + client = boto3.client('codebuild') |
| 18 | + build_info = client.batch_get_builds( |
| 19 | + ids=[job_id] |
| 20 | + )['builds'][0] |
| 21 | + location = build_info['artifacts']['location'].strip('aws:arn:s3:::') |
| 22 | + bucket = location.split('/')[0] |
| 23 | + key = location.split('/', 1)[-1] |
| 24 | + return (bucket, key) |
| 25 | + |
| 26 | + |
| 27 | +if __name__ == '__main__': |
| 28 | + PARSER = ArgumentParser('Codebuild CFN template and params build') |
| 29 | + PARSER.add_argument( |
| 30 | + '--path', help='Path where CFN files are created', required=True |
| 31 | + ) |
| 32 | + ARGS = PARSER.parse_args() |
| 33 | + BUILD_DEST = get_artifact_location() |
| 34 | + LAYER_NAME = environ['LAYER_NAME'] |
| 35 | + PY_VERSION = environ['PY_VERSION'] |
| 36 | + DATE = dt.utcnow().isoformat() |
| 37 | + TPL = template(make_public=True, Runtimes=[PY_VERSION], Bucket=BUILD_DEST[0], Key=BUILD_DEST[1]) |
| 38 | + TPL.set_metadata({ |
| 39 | + 'Author': 'John Mille john@lambda-my-aws.io', |
| 40 | + 'Version': DATE, |
| 41 | + 'BuildBy': 'CodePipeline/CodeBuild', |
| 42 | + 'LayerName': LAYER_NAME |
| 43 | + }) |
| 44 | + TPL.set_description(f'Template for {LAYER_NAME} - {DATE}') |
| 45 | + with open(f'{ARGS.path}/layer_template.yml', 'w') as fd: |
| 46 | + fd.write(TPL.to_yaml()) |
| 47 | + template_config = { |
| 48 | + 'Parameters': |
| 49 | + { |
| 50 | + 'LayerName': LAYER_NAME |
| 51 | + }, |
| 52 | + 'Tags': { |
| 53 | + 'Name': LAYER_NAME |
| 54 | + } |
| 55 | + } |
| 56 | + with open(f'{ARGS.path}/layer_config.json', 'w') as fd: |
| 57 | + fd.write(dumps(template_config)) |
0 commit comments