How to use cfnresponse - 10 common examples

To help you get started, we’ve selected a few cfnresponse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github linuxacademy / content-lambda-boto3 / CloudFormation / S3-Hosted-Website / index.py View on Github external
timeout, args=[event, context])
    t.start()

    try:
        bucket = event['ResourceProperties']['BucketName']
        repo_subdir = event['ResourceProperties']['RepoSubdir']
        repo_url = event['ResourceProperties']['RepoURL']
        repo_name = urlparse(repo_url).path.split('/')[-2]
        local_file = download_repo(repo_url)
        extract(local_file, '/tmp')
        upload_to_s3(bucket, f'/tmp/{repo_name}-master/{repo_subdir}')
        cfnresponse.send(event, context, cfnresponse.SUCCESS,
                         response_data, "CustomResourcePhysicalID")
    except Exception as e:
        print("Error: " + str(e))
        cfnresponse.send(event, context, cfnresponse.FAILED,
                         response_data, "CustomResourcePhysicalID")
    finally:
        # Cancel timer before exit
        t.cancel()
github quiltdata / quilt / lambdas / navigator_config / index.py View on Github external
def handler(event, context):
    """
    top-level handler for CloudFormation custom resource protocol
    """
    if event['RequestType'] == 'Delete':
        try:
            stackname = event['ResourceProperties']['StackName']
            # This is limited to the config bucket of the stack
            # by NavigatorInitRole (the only bucket it references
            # is ConfigBucket)
            config_bucket_name = event['ResourceProperties']['DestBucket']
        except KeyError as e:
            print('Could not find {} resource property.'.format(e.args[0]))
            print('Doing nothing and reporting success.')
            cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
            return

        try:
            cf_client = boto3.client('cloudformation')
            describe = cf_client.describe_stacks(StackName=stackname)
            status = describe['Stacks'][0]['StackStatus']

            if not status == 'DELETE_IN_PROGRESS':
                print('Stack is not deleting, so this resource is just getting '
                      'cleaned up. Doing nothing and reporting success.')
                cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
                return

            wipe_bucket(config_bucket_name)
            cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
            return
github jorgebastida / gordon / gordon / contrib / events / rule / rule.py View on Github external
def handler(event, context):
    properties = event['ResourceProperties']
    rule_name = properties['Name'][:64]  # Rule Names can't be longer than 64 characters.
    physical_resource_id = 'rule-{}'.format(rule_name)

    if event['RequestType'] == 'Delete':
        delete_rule(rule_name)
        send(event, context, SUCCESS)
        return

    # We don't check if RequestType is Create or Update, because we don't care
    # much... as regardless of what CF thinks.
    output = create_or_update_rule(
        rule_name=rule_name,
        role_arn=properties.get('RoleArn', ''),
        schedule_expression=properties.get('ScheduleExpression', ''),
        event_pattern=properties.get('EventPattern', ''),
        state=properties.get('State', 'ENABLED'),
        description=properties.get('Description', '')
    )

    send(event, context, SUCCESS, physical_resource_id=physical_resource_id, response_data={'Arn': output['RuleArn']})
github aws-quickstart / quickstart-git2s3 / functions / source / CreateSSHKey / lambda_function.py View on Github external
print(pub_key)
            # Encrypt private key
            kms = boto3.client('kms',region_name=event["ResourceProperties"]["Region"])
            enc_key = kms.encrypt(KeyId=event["ResourceProperties"]["KMSKey"],Plaintext=priv_key)['CiphertextBlob']
            f = open('/tmp/enc_key','wb')
            f.write(enc_key)
            f.close()
            # Upload priivate key to S3
            s3 = boto3.client('s3')
            s3.upload_file('/tmp/enc_key',event["ResourceProperties"]["KeyBucket"],'enc_key')
        else:
            pub_key = event['PhysicalResourceId']
        cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, pub_key)
    except:
        traceback.print_exc()
        cfnresponse.send(event, context, cfnresponse.FAILED, {}, '')
github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / functions / generate_emrname / lambda_function.py View on Github external
if event['RequestType'] == 'Create':
        phys_id = ''.join(random.choice(alnum) for _ in range(16))
    else:
        phys_id = event['PhysicalResourceId']
    try:
        if event['RequestType'] in ['Create', 'Update']:
            if 'Length' in event['ResourceProperties']:
                pw_len = int(event['ResourceProperties']['Length'])
            else:
                pw_len = 16
            response_data['EMRClusterName'] = generate_password(pw_len)
        cfnresponse.send(event, context, response_code, response_data, phys_id)
    except Exception as e:
        print(str(e))
        traceback.print_exc()
        cfnresponse.send(event, context, cfnresponse.FAILED, response_data, phys_id, str(e))
github moduspwnens / boa-chat / boa-nimbus / lambda / SwaggerTemplatePresetFunction / index.py View on Github external
for each_key in replacements_map.keys():
            each_value = replacements_map[each_key]
            
            dest_file_content = dest_file_content.replace(each_key, each_value)
        
        s3_client.put_object(
            Bucket = resource_props["OutputBucket"],
            Key = get_s3_key_for_physical_resource_id(physical_resource_id),
            Body = dest_file_content
        )
        
        response_data["OutputBucket"] = resource_props["OutputBucket"]
        response_data["OutputKey"] = get_s3_key_for_physical_resource_id(physical_resource_id)

    cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, None)

    return {}
github PaloAltoNetworks / TransitGatewayDeployment / prerequisites / lambda package / TransitGatewayInitialiseLambda.py View on Github external
result = cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
        logger.info("Got response to cfnsend {} ".format(result))

    elif event['RequestType'] == 'Update':
        print("Update something")

    elif event['RequestType'] == 'Delete':
        print("Got Delete event")
        try:
            res = delete_route(fromTGWRouteTable, vnetroutecidr)
            res1 = delete_route(VPC0_route_table_id, defroutecidr)
            result = cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")

        except Exception as e:
            print("Errory trying to delete something")
            cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
github nordcloud / cfn-encrypt / cfn_encrypt / get_ssm_value.py View on Github external
)

            ret_value = None
            if event["ResourceProperties"].get("Version") is not None:
                for param in response["Parameters"]:
                    if param["Version"] == int(event["ResourceProperties"].get("Version")):
                        ret_value = param
                        break
            else:
                ret_value = response["Parameters"][-1]

            if ret_value is None:
                raise LookupError("Parameter not found")
            logger.info("Successfully retrieved parameter {}".format(name))

            cfnresponse.send(event, context, cfnresponse.SUCCESS,
                             json.loads(json.dumps(ret_value, default=date_2_string)),
                             name + str(ret_value["Version"]), noEcho=True)
        else:
            cfnresponse.send(event, context, cfnresponse.SUCCESS, None, name, noEcho=True)

    except Exception as ex:
        logger.error("Faild get parameter value: %s", name)
        logger.debug("Stack trace %s", traceback.format_exc())
        if event["RequestType"] in ["Create", "Update"]:
            cfnresponse.send(event, context, cfnresponse.FAILED, None, "0", noEcho=True)
        else:
            cfnresponse.send(event, context, cfnresponse.SUCCESS, None, "0", noEcho=True)
github cyberark / cyberark-aws-auto-onboarding / src / aws_environment_setup / aws_environment_setup.py View on Github external
if not pvwa_session_id:
                return cfnresponse.send(event, context, cfnresponse.FAILED,
                                        "Failed to connect to PVWA, see detailed error in logs", {}, physical_resource_id)

            is_safe_created = create_safe(pvwa_integration_class, request_unix_safe_name, request_unix_cpm_name, request_pvwa_ip,
                                          pvwa_session_id, 1)
            if not is_safe_created:
                return cfnresponse.send(event, context, cfnresponse.FAILED,
                                        f"Failed to create the Safe {request_unix_safe_name}, see detailed error in logs",
                                        {}, physical_resource_id)

            is_safe_created = create_safe(pvwa_integration_class, request_windows_safe_name, request_windows_cpm_name,
                                          request_pvwa_ip, pvwa_session_id, 1)

            if not is_safe_created:
                return cfnresponse.send(event, context, cfnresponse.FAILED,
                                        f"Failed to create the Safe {request_windows_safe_name}, see detailed error in logs",
                                        {}, physical_resource_id)

            if not create_session_table():
                return cfnresponse.send(event, context, cfnresponse.FAILED,
                                        "Failed to create 'Sessions' table in DynamoDB, see detailed error in logs",
                                        {}, physical_resource_id)

            #  Creating KeyPair Safe
            is_safe_created = create_safe(pvwa_integration_class, request_key_pair_safe, "", request_pvwa_ip, pvwa_session_id)
            if not is_safe_created:
                return cfnresponse.send(event, context, cfnresponse.FAILED,
                                        f"Failed to create the Key Pairs safe: {request_key_pair_safe}, " \
                                        "see detailed error in logs",
                                        {}, physical_resource_id)
github theserverlessway / formica / docs / examples / custom-resource / resource.py View on Github external
def handler(event, context):
    print(event)
    response_data = {}
    response_data['Data'] = 'DataResponse'
    response_data['Reason'] = 'SomeTestReason'
    cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, "CustomResourcePhysicalID")

cfnresponse

Send a response object to a custom resource by way of an Amazon S3 presigned URL

Apache-2.0
Latest version published 3 months ago

Package Health Score

58 / 100
Full package analysis

Similar packages