def handler()

in src/lambda.d/nexus3-purge/index.py [0:0]


def handler(event, context):

    def cfn_error(message=None):
        logger.error("| cfn_error: %s" % message)
        cfn_send(event, context, CFN_FAILED, reason=message)

    try:
        logger.info(event)

        # cloudformation request type (create/update/delete)
        request_type = event['RequestType']
        
        # extract resource properties
        props = event['ResourceProperties']
        old_props = event.get('OldResourceProperties', {})

        if request_type == "Create":
            physical_id = f"nexus.on.aws.{str(uuid4())}"
        else:
            physical_id = event.get('PhysicalResourceId', None)
            if not physical_id:
                cfn_error("invalid request: request type is '%s' but 'PhysicalResourceId' is not defined" % request_type)
                return
        if request_type == "Delete":
            # resource properties (all required)
            cluster_name  = props['ClusterName']
            role_arn      = props['RoleArn']
            # "log in" to the cluster
            subprocess.check_call([ 'aws', 'eks', 'update-kubeconfig',
                '--role-arn', role_arn,
                '--name', cluster_name,
                '--kubeconfig', kubeconfig
            ])

            object_type         = props['ObjectType']
            object_name         = props['ObjectName']
            object_namespace    = props['ObjectNamespace']
            json_path           = props['JsonPath']
            timeout_seconds     = props['TimeoutSeconds']
            relase              = props['Release']

            output = wait_for_purge(['get', '-n', object_namespace, object_type, object_name, "-o=jsonpath='{{{0}}}'".format(json_path)], int(timeout_seconds))
            logger.info(f"The resource {object_type}/{object_name} has been purged.")

            try:
                kubectl(['delete', '-n', object_namespace, 'pvc', '-l', f'release={relase}'])
                logger.info(f'The PVC of helm relese {relase} is purged.')
            except Exception as e:
                error = str(e)
                if 'NotFound' in error or b'i/o timeout' in error:
                    logger.warn(f"Got error '{error}'', cluster/resource might have been purged.")
                else:
                    raise
        cfn_send(event, context, CFN_SUCCESS, physicalResourceId=physical_id)
    except KeyError as e:
        cfn_error(f"invalid request. Missing key {str(e)}")
    except subprocess.CalledProcessError as exc:
        errMsg = f'the cmd {exc.cmd} returns {exc.returncode} with stdout {exc.output} and stderr {exc.stderr}'
        logger.error(errMsg)
        cfn_error(errMsg)
    except Exception as e:
        logger.exception(e)
        cfn_error(str(e))