Python cfnresponse.SUCCESS Examples

The following are 27 code examples of cfnresponse.SUCCESS(). 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: password-policy.py    From aws-baseline with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: lambda_function.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
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: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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['CidrBlocks'] = get_cidrs(
                int(event['ResourceProperties']['CidrSize']),
                int(event['ResourceProperties']['Qty']),
                event['ResourceProperties']['VpcId']
            )
        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 #7
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: main.py    From connect-integration-examples with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: resource.py    From aws-cloudformation-templates with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: resource.py    From formica with MIT License 5 votes vote down vote up
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 #12
Source File: deploy-policies.py    From aws-baseline with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: lambda_function.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: lambda_function.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: lambda_function.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: custom-resource-handler.py    From aws-cdk-examples with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: custom-resource-handler.py    From aws-cdk-examples with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: custom-resource-handler.py    From aws-cdk-examples with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: ses_domain_identity.py    From aws-cf-verified-ssl-certificate with Apache License 2.0 4 votes vote down vote up
def lambda_handler(event, context):

    response_data = {}
    try:
        print 'Event: '
        print str(event)
        print 'Context: '
        print str(context)

        request_type = event['RequestType']
        print 'Type: ' + request_type

        stack_id = event['StackId']
        stack_name = stack_id.split('/')[1]
        print 'Stack: ' + stack_name

        domain = event['ResourceProperties']['Domain']
        print 'Domain: ' + domain
        response_data['Domain'] = domain

        region = event['ResourceProperties']['Region']
        print 'Region: ' + region

        ses = boto3.client('ses', region_name=region)

        if request_type == 'Create':

            domain_identity = ses.verify_domain_identity(Domain=domain)
            response_data['VerificationToken'] = domain_identity['VerificationToken']

        elif request_type == 'Update':

            oldDomain = event['OldResourceProperties']['Domain']
            if oldDomain != domain:
                try:
                    ses.delete_identity(Identity=oldDomain)
                except Exception as e:
                    print e

            domain_identity = ses.verify_domain_identity(Domain=domain)
            response_data['VerificationToken'] = domain_identity['VerificationToken']

        elif request_type == 'Delete':
            ses.delete_identity(Identity=domain)

        print response_data

        cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
    except Exception as e:
        print 'Exception occured: ' + str(e)
        cfnresponse.send(event, context, cfnresponse.FAILED, response_data)
        raise e 
Example #26
Source File: ses_wait_for_verification_and_create_rule_set.py    From aws-cf-verified-ssl-certificate with Apache License 2.0 4 votes vote down vote up
def execute(self):
        response_data = {}
        try:
            if self.request_type in ['Create', 'Update']:
                self.wait_for_ses_domain_verification()

                email_address = 'admin@' + self.domain
                response_data['EmailAddress'] = email_address
                response_data['Domain'] = self.domain
                
                if self.request_type == 'Create':
                    result = self.ses.describe_active_receipt_rule_set()
                    rule_exists = False
                    rule_names = []

                    if 'Metadata' in result and 'Name' in result['Metadata']:
                        self.rule_set_name = result['Metadata']['Name']
                        rule_names = map(lambda rule: rule['Name'], result['Rules'])
                        rule_exists = self.rule_name in rule_names
                    else:
                        self.ses.create_receipt_rule_set(RuleSetName=self.rule_set_name)
                        self.ses.set_active_receipt_rule_set(RuleSetName=self.rule_set_name)

                    if not rule_exists:
                        self.create_rule(email_address, rule_names)


            elif self.request_type == 'Delete':
                result = self.ses.describe_active_receipt_rule_set()
                if 'Metadata' in result and 'Name' in result['Metadata']:
                    print 'Active rule set exists'
                    active_rule_set_name = result['Metadata']['Name']
                    rule_names = map(lambda rule: rule['Name'], result['Rules'])
                    rule_exists = self.rule_name in rule_names
                    if rule_exists:
                        print 'Rule ' + self.rule_name + ' exists. Deleting it...'
                        self.ses.delete_receipt_rule(RuleSetName=active_rule_set_name, RuleName=self.rule_name)

                    if active_rule_set_name == self.rule_set_name:
                        print 'RuleSet was created by stack. Deleting it...'
                        self.ses.set_active_receipt_rule_set()
                        self.ses.delete_receipt_rule_set(RuleSetName=active_rule_set_name)

            cfnresponse.send(self.event, self.context, cfnresponse.SUCCESS, response_data)
        except Exception as e:
            print 'Exception occured: ' + str(e)
            cfnresponse.send(self.event, self.context, cfnresponse.FAILED, response_data)
            raise e 
Example #27
Source File: deploy-policies.py    From aws-baseline with Apache License 2.0 4 votes vote down vote up
def handler(event, context):
    RequestType = event["RequestType"]
    Properties = event["ResourceProperties"]
    LogicalResourceId = event["LogicalResourceId"]
    PhysicalResourceId = event.get("PhysicalResourceId")
    Policy = Properties["Policy"]
    Attach = Properties["Attach"] == 'true'

    print('RequestType: {}'.format(RequestType))
    print('PhysicalResourceId: {}'.format(PhysicalResourceId))
    print('LogicalResourceId: {}'.format(LogicalResourceId))
    print('Attach: {}'.format(Attach))

    parameters = dict(
        Content=Policy,
        Description="Baseline Policy - {}".format(LogicalResourceId),
        Name=LogicalResourceId,
    )

    policy_id = PhysicalResourceId
    paginator = o.get_paginator('list_policies')
    policies = [policy['Id'] for page in paginator.paginate(Filter=SCP) for policy in
                page['Policies']
                if policy['Name'] == LogicalResourceId]
    if policies:
        policy_id = policies[0]
    if RequestType == CREATE:
        print('Creating Policy: {}'.format(LogicalResourceId))
        response = with_retry(o.create_policy,
                              **parameters, Type=SCP
                              )
        policy_id = response["Policy"]["PolicySummary"]["Id"]
        if Attach:
            with_retry(o.attach_policy, PolicyId=policy_id, TargetId=root_id())
    elif RequestType == UPDATE:
        print('Updating Policy: {}'.format(LogicalResourceId))
        with_retry(o.update_policy, PolicyId=policy_id, **parameters)
    elif RequestType == DELETE:
        print('Deleting Policy: {}'.format(LogicalResourceId))
        # Same as above
        if re.match('p-[0-9a-z]+', policy_id):
            if policy_attached(policy_id):
                with_retry(o.detach_policy, PolicyId=policy_id, TargetId=root_id())
            with_retry(o.delete_policy, PolicyId=policy_id)
        else:
            print('{} is no valid PolicyId'.format(policy_id))
    else:
        cfnresponse.send(event, context, cfnresponse.FAILED, {}, policy_id)
    cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, policy_id)