Python cfnresponse.send() Examples
The following are 30
code examples of cfnresponse.send().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cfnresponse
, or try the search function
.
Example #1
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): response_code = cfnresponse.SUCCESS response_data = {} print(event) 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['MasterUserPassword'] = 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))
Example #2
Source File: password-policy.py From aws-baseline with Apache License 2.0 | 6 votes |
def handler(event, context): print(event) try: resource_properties = event['ResourceProperties'] request_type = event['RequestType'] if request_type in ['Create', 'Update']: update_parameters = {key: cast_type(resource_properties[key]) for key, cast_type in password_policy_keys.items()} print(update_parameters) response = iam.update_account_password_policy(**update_parameters) print(response) elif request_type is 'Delete': iam.delete_account_password_policy() cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "") except Exception as e: print(e) cfnresponse.send(event, context, cfnresponse.FAILED, {}, "")
Example #3
Source File: lambda_function.py From quickstart-redhat-openshift with Apache License 2.0 | 6 votes |
def lambda_handler(event, context): try: print(json.dumps(event)) print(event['RequestType']) print('Getting AnsibleConfigServer instance...') print event["ResourceProperties"]["StackName"] print event["ResourceProperties"]["AnsibleConfigServer"] if event['RequestType'] == 'Delete': print("Run unsubscribe script") ssm = boto3.client('ssm') instanceID = event["ResourceProperties"]["AnsibleConfigServer"] response = ssm.send_command(Targets=[{"Key":"instanceids","Values":[instanceID]}], DocumentName="AWS-RunShellScript", Parameters={"commands":["python unsubscribe.py %s" %(event["ResourceProperties"]["StackName"])], "executionTimeout":["600"], "workingDirectory":["/root"]}, Comment="Execute script in ansible server to unsubscribe nodes from RH subscription", TimeoutSeconds=120) print(response) except Exception as e: print(e) traceback.print_exc() cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, '')
Example #4
Source File: resource.py From aws-cloudformation-templates with Apache License 2.0 | 6 votes |
def handler(event, context): print("Received request:", json.dumps(event, indent=4)) action = event["RequestType"] stack = event["ResourceProperties"]["StackName"] resources = int(event["ResourceProperties"]["ResourceCount"]) try: log(stack, action, 1) if action == "Create": log(stack, "ResourceCount", resources) cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "{} metrics".format(stack)) except Exception as e: cfnresponse.send(event, context, cfnresponse.FAILED, { "Data": str(e), }, "{} metrics".format(stack))
Example #5
Source File: main.py From connect-integration-examples with Apache License 2.0 | 6 votes |
def handler(event, context): try: if event['RequestType'] == 'Create': # Test Integration print 'Getting all pets' response = requests.get(event['ResourceProperties']['IntegrationEndpoint']) print "Status code: " + str(response.status_code) if response.status_code != 200: raise Exception('Error: Status code received is not 200') elif event['RequestType'] == 'Update': pass elif event['RequestType'] == 'Delete': pass cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, '') except: print traceback.print_exc() cfnresponse.send(event, context, cfnresponse.FAILED, {}, '')
Example #6
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS reason = None physical_id = None try: service_name = event['ResourceProperties']['ServiceName'] if 'CustomSuffix' in event['ResourceProperties'].keys(): custom_suffix = event['ResourceProperties']['CustomSuffix'] else: custom_suffix = None if event['RequestType'] != 'Delete': physical_id = create_role(service_name, custom_suffix) else: physical_id = event['PhysicalResourceId'] delete_role(physical_id) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED reason = str(e) finally: timer.cancel() cfnresponse.send(event, context, status, {'Arn': physical_id}, physical_id, reason)
Example #7
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): response_code = cfnresponse.SUCCESS response_data = {} print(event) 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']: response_data['EMRCidr'] = get_cidrs( int(event['ResourceProperties']['CidrSize']), int(event['ResourceProperties']['Qty']), event['ResourceProperties']['VpcId'] )[0] 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))
Example #8
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): response_code = cfnresponse.SUCCESS response_data = {} print(event) 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['DBName'] = 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))
Example #9
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): response_code = cfnresponse.SUCCESS response_data = {} print(event) 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']: response_data['AvailabilityZones'] = get_azs(int(event['ResourceProperties']['Qty'])) 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))
Example #10
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS reason = None physical_id = None try: service_name = event['ResourceProperties']['ServiceName'] if 'CustomSuffix' in event['ResourceProperties'].keys(): custom_suffix = event['ResourceProperties']['CustomSuffix'] else: custom_suffix = None if event['RequestType'] != 'Delete': physical_id = create_role(service_name, custom_suffix) else: physical_id = event['PhysicalResourceId'] delete_role(physical_id) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED reason = str(e) finally: timer.cancel() cfnresponse.send(event, context, status, {'Arn': physical_id}, physical_id, reason)
Example #11
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 6 votes |
def handler(event, context): response_code = cfnresponse.SUCCESS response_data = {} print(event) 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))
Example #12
Source File: custom-resource-handler.py From aws-cdk-examples with Apache License 2.0 | 5 votes |
def handler(event, context): import logging as log import cfnresponse log.getLogger().setLevel(log.INFO) # This needs to change if there are to be multiple resources in the same stack physical_id = 'TheOnlyCustomResource' try: log.info('Input event: %s', event) # Check if this is a Create and we're failing Creates if event['RequestType'] == 'Create' and event['ResourceProperties'].get('FailCreate', False): raise RuntimeError('Create failure requested') # Do the thing message = event['ResourceProperties']['Message'] attributes = { 'Response': 'Hello "%s"' % message } cfnresponse.send(event, context, cfnresponse.SUCCESS, attributes, physical_id) except Exception as e: log.exception(e) # cfnresponse's error message is always "see CloudWatch" cfnresponse.send(event, context, cfnresponse.FAILED, {}, physical_id)
Example #13
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS reason = None physical_id = None try: data = s3_client.get_object(Bucket=event['ResourceProperties']['Bucket'], Key=event['ResourceProperties']['Key'])['Body'].read() try: bot = json.loads(data) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) raise Exception('Intent json is malformed') if event['RequestType'] != 'Delete': create_bot(bot) physical_id = bot['name'] else: delete_bot(event['PhysicalResourceId']) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED reason = str(e) finally: timer.cancel() cfnresponse.send(event, context, status, {}, physical_id, reason)
Example #14
Source File: deploy-policies.py From aws-baseline with Apache License 2.0 | 5 votes |
def enable_service_control_policies(event, context): RequestType = event["RequestType"] if RequestType == CREATE and not scp_enabled(): r_id = root_id() print('Enable SCP for root: {}'.format(r_id)) o.enable_policy_type(RootId=r_id, PolicyType=SCP) cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, 'SCP')
Example #15
Source File: deploy-policies.py From aws-baseline with Apache License 2.0 | 5 votes |
def exception_handling(function): def catch(event, context): try: function(event, context) except Exception as e: print(e) print(event) cfnresponse.send(event, context, cfnresponse.FAILED, {}) return catch
Example #16
Source File: lambda_function.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def handler(event, context): print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS physical_resource_id = 'PVCleanup' data = {} reason = None try: if event['RequestType'] == 'Delete': print('Removing any orphaned EBS volumes...') tag_name = 'tag:kubernetes.io/cluster/%s' % event['ResourceProperties']['ClusterId'] response = boto_throttle_backoff( ec2_client.describe_volumes, Filters=[{'Name': tag_name, 'Values': ['owned']}] )['Volumes'] for volume in response: print('deleting volume %s' % volume['VolumeId']) boto_throttle_backoff(ec2_client.delete_volume, VolumeId=volume['VolumeId']) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) reason = str(e) status = cfnresponse.FAILED finally: if event['RequestType'] == 'Delete': try: wait_message = 'waiting for events for request_id %s to propagate to cloudwatch...' % context.aws_request_id while not logs_client.filter_log_events( logGroupName=context.log_group_name, logStreamNames=[context.log_stream_name], filterPattern='"%s"' % wait_message )['events']: print(wait_message) time.sleep(5) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) time.sleep(120) cfnresponse.send(event, context, status, data, physical_resource_id, reason)
Example #17
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #18
Source File: lambda_function.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def lambda_handler(event,context): try: if event['RequestType'] == 'Delete': s3 = boto3.client('s3') # Delete KeyBucket contents print 'Getting KeyBucket objects...' s3objects = s3.list_objects_v2(Bucket=event["ResourceProperties"]["KeyBucket"]) if 'Contents' in s3objects.keys(): print 'Deleting KeyBucket objects %s...' % str([{'Key':key['Key']} for key in s3objects['Contents']]) s3.delete_objects(Bucket=event["ResourceProperties"]["KeyBucket"],Delete={'Objects':[{'Key':key['Key']} for key in s3objects['Contents']]}) # Delete Output bucket contents and versions print 'Getting OutputBucket objects...' objects=[] versions=s3.list_object_versions(Bucket=event["ResourceProperties"]["OutputBucket"]) while versions: if 'Versions' in versions.keys(): for v in versions['Versions']: objects.append({'Key':v['Key'],'VersionId': v['VersionId']}) if 'DeleteMarkers'in versions.keys(): for v in versions['DeleteMarkers']: objects.append({'Key':v['Key'],'VersionId': v['VersionId']}) if versions['IsTruncated']: versions=s3.list_object_versions(Bucket=event["ResourceProperties"]["OutputBucket"],VersionIdMarker=versions['NextVersionIdMarker']) else: versions=False if objects != []: s3.delete_objects(Bucket=event["ResourceProperties"]["OutputBucket"],Delete={'Objects':objects}) cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, '') except: print traceback.print_exc() cfnresponse.send(event, context, cfnresponse.FAILED, {}, '')
Example #19
Source File: lambda_function.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def lambda_handler(event,context): try: if event['RequestType'] == 'Create': # Generate keys new_key = rsa.generate_private_key(backend=crypto_default_backend(), public_exponent=65537, key_size=2048) priv_key = new_key.private_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PrivateFormat.PKCS8, crypto_serialization.NoEncryption() ) pub_key = new_key.public_key().public_bytes( crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH ) print(priv_key) 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, {}, '')
Example #20
Source File: custom-resource-handler.py From aws-cdk-examples with Apache License 2.0 | 5 votes |
def main(event, context): import logging as log import cfnresponse log.getLogger().setLevel(log.INFO) # This needs to change if there are to be multiple resources in the same stack physical_id = 'TheOnlyCustomResource' try: log.info('Input event: %s', event) # Check if this is a Create and we're failing Creates if event['RequestType'] == 'Create' and event['ResourceProperties'].get('FailCreate', False): raise RuntimeError('Create failure requested') # Do the thing message = event['ResourceProperties']['Message'] attributes = { 'Response': 'You said "%s"' % message } cfnresponse.send(event, context, cfnresponse.SUCCESS, attributes, physical_id) except Exception as e: log.exception(e) # cfnresponse's error message is always "see CloudWatch" cfnresponse.send(event, context, cfnresponse.FAILED, {}, physical_id)
Example #21
Source File: custom-resource-handler.py From aws-cdk-examples with Apache License 2.0 | 5 votes |
def main(event, context): import logging as log import cfnresponse log.getLogger().setLevel(log.INFO) # This needs to change if there are to be multiple resources # in the same stack physical_id = 'TheOnlyCustomResource' try: log.info('Input event: %s', event) # Check if this is a Create and we're failing Creates if event['RequestType'] == 'Create' and event['ResourceProperties'].get('FailCreate', False): raise RuntimeError('Create failure requested') # Do the thing message = event['ResourceProperties']['Message'] attributes = { 'Response': 'You said "%s"' % message } cfnresponse.send(event, context, cfnresponse.SUCCESS, attributes, physical_id) except Exception as e: log.exception(e) # cfnresponse's error message is always "see CloudWatch" cfnresponse.send(event, context, cfnresponse.FAILED, {}, physical_id)
Example #22
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS reason = None physical_id = None try: if event['RequestType'] != 'Delete': data = s3_client.get_object(Bucket=event['ResourceProperties']['Bucket'], Key=event['ResourceProperties']['Key'])['Body'].read() try: slots = json.loads(data) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) raise Exception('Intent json is malformed') if type(slots) != list: raise Exception('JSON must be a list of one of more Slots') for s in slots: create_custom_slot_type(s) physical_id = ','.join([s['name'] for i in slots]) else: for s in event['PhysicalResourceId'].split(','): delete_custom_slot_type(s) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED reason = str(e) finally: timer.cancel() cfnresponse.send(event, context, status, {}, physical_id, reason)
Example #23
Source File: resource.py From formica with MIT License | 5 votes |
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")
Example #24
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #25
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #26
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #27
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #28
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Example #29
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() print('Received event: %s' % json.dumps(event)) status = cfnresponse.SUCCESS reason = None physical_id = None try: if event['RequestType'] != 'Delete': data = s3_client.get_object(Bucket=event['ResourceProperties']['Bucket'], Key=event['ResourceProperties']['Key'])['Body'].read() try: intents = json.loads(data) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) raise Exception('Intent json is malformed') if type(intents) != list: raise Exception('JSON must be a list of one of more Intents') for i in intents: create_intent(i) physical_id = ','.join([i['name'] for i in intents]) else: for i in event['PhysicalResourceId'].split(','): delete_intent(i) except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED reason = str(e) finally: timer.cancel() cfnresponse.send(event, context, status, {}, physical_id, reason)
Example #30
Source File: lambda_function.py From aws-servicebroker with Apache License 2.0 | 5 votes |
def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)