コード例 #1
0
ファイル: handler.py プロジェクト: part-up/partops
def send_response_cfn(event, context, response_status, cfn_attributes={}):
    response_body = {'Status': response_status,
                     'Reason': 'Log stream name: ' + context.log_stream_name,
                     'PhysicalResourceId': context.log_stream_name,
                     'StackId': event['StackId'],
                     'RequestId': event['RequestId'],
                     'LogicalResourceId': event['LogicalResourceId'],
                     'Data': cfn_attributes}

    requests.put(event['ResponseURL'], data=json.dumps(response_body))
def send(event, context, response_status, response_data, physical_resource_id):
    """
    This function is responsible for sending the custom resource response.
    """
    response_url = event['ResponseURL']

    response_body = {
        'Status': response_status,
        'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
        'PhysicalResourceId': physical_resource_id or context.log_stream_name,
        'StackId': event['StackId'],
        'RequestId': event['RequestId'],
        'LogicalResourceId': event['LogicalResourceId'],
        'Data': response_data
    }

    json_response_body = json.dumps(response_body)

    print("Response body:\n" + json_response_body)

    headers = {'content-type': '', 'content-length': str(len(json_response_body))}

    try:
        response = requests.put(response_url, data=json_response_body, headers=headers)
        print("Status code: " + response.reason)
    except ClientError as client_error:
        print("send(..) failed executing requests.put(..): " + str(client_error))
def send(event, context, responseStatus, responseData, physicalResourceId=None):
    responseUrl = event['ResponseURL']

    print(responseUrl)

    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name
    responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)

    print("Response body:\n" + json_responseBody)

    headers = {
        'content-type' : '',
        'content-length' : str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        print("Status code: " + response.reason)
    except Exception as e:
        print("send(..) failed executing requests.put(..): " + str(e))
コード例 #4
0
def handler(event, context):
    """Handle CodeBuild build status changes and send notifications to CFN WaitCondition."""
    print("CodeBuild event: %s" % json.dumps(event))
    notification_url = os.environ["NOTIFICATION_URL"]
    succeeded = event["detail"]["build-status"] == "SUCCEEDED"
    data = json.dumps(
        {
            "Status": "SUCCESS" if succeeded else "FAILURE",
            "Reason": "Build Complete" if succeeded else "Build Failed. See the CodeBuild logs for further details.",
            "UniqueId": event["detail"]["build-id"],
            "Data": "Build has completed.",
        }
    )
    print("Notification URL: %s" % notification_url)
    print("Notification data: %s" % data)
    requests.put(notification_url, data=data, headers={"Content-Type": ""})
コード例 #5
0
def send(event, context, response_status, response_data, physical_resource_id):
    """Send a response."""
    if 'ResponseURL' in event:
        if DEBUG_MODE is True:
            print("Started function send")
            print("CF Response URL: " + event['ResponseURL'])
        response_body = format_response_body(event, context, response_status, response_data, physical_resource_id)
        json_response_body = json.dumps(response_body)
        if DEBUG_MODE is True:
            print("CF Response Body: %s" % str(json_response_body))
        headers = {
            'content-type': '',
            'content-length': str(len(json_response_body))
            }
        try:
            response = requests.put(
                event['ResponseURL'],
                data=json_response_body,
                headers=headers
                )
            if DEBUG_MODE is True:
                print("CF Status code: ", response.reason)
                print("Finished function send")
        except Exception as error:  # pylint: disable=W0703
            print("Failed to send event, raising exception without retrying.")
            raise Exception(error)
コード例 #6
0
def send(event, context, response_status, response_data):
    ''' Informs CloudFormation about the state of the custom resource '''
    response_url = event['ResponseURL']

    print(response_url)

    response_body = {}
    response_body['Status'] = response_status
    response_body['Reason'] = \
        'See the details in CloudWatch Log Stream: ' + context.log_stream_name
    response_body['PhysicalResourceId'] = context.log_stream_name
    response_body['StackId'] = event['StackId']
    response_body['RequestId'] = event['RequestId']
    response_body['LogicalResourceId'] = event['LogicalResourceId']
    response_body['NoEcho'] = None
    response_body['Data'] = response_data

    json_response_body = dumps(response_body)

    print("Response body:\n" + json_response_body)

    headers = {
        'content-type': '',
        'content-length': str(len(json_response_body))
    }

    try:
        response = requests.put(response_url,
                                data=json_response_body,
                                headers=headers)
        print("Status code: " + response.reason)
    except RequestException as exception:
        print("send(..) failed executing requests.put(..): " + str(exception))
コード例 #7
0
def delete_respond_cloudformation(event, status, data=None):
    responseBody = {
        'Status': status,
        'Reason': 'See the details in CloudWatch Log Stream',
        'PhysicalResourceId': event['ServiceToken'],
        'StackId': event['StackId'],
        'RequestId': event['RequestId'],
        'LogicalResourceId': event['LogicalResourceId'],
        'Data': data
    }

    print('Response = ' + json.dumps(responseBody))
    print(event)
    lambda_client = get_client('lambda')
    function_name = os.environ['AWS_LAMBDA_FUNCTION_NAME']
    print('Deleting Lambda')
    lambda_client.delete_function(FunctionName=function_name)
    requests.put(event['ResponseURL'], data=json.dumps(responseBody))
コード例 #8
0
ファイル: okta.py プロジェクト: thebenwaters/tropokta
def lambda_handler(event, context):
    logger.info(event)
    logger.info('Received CF event')
    request_type, response_url = event.get('RequestType'), event.get(
        'ResponseURL')
    stack_id, request_id, logical_resource_id, physical_resource_id, resource_type = event.get('StackId', None), \
                                                                                     event.get('RequestId', None), \
                                                                                     event.get('LogicalResourceId',
                                                                                               None), \
                                                                                     event.get('PhysicalResourceId',
                                                                                               None), \
                                                                                     event.get('ResourceType', None)
    properties = {}
    return_properties = {
        'StackId': stack_id,
        'RequestId': request_id,
        'LogicalResourceId': logical_resource_id,
        'PhysicalResourceId': physical_resource_id
    }
    function_group = request_types.get(resource_type)
    non_empty_return_properties = {}
    for key, value in return_properties.items():
        if value is not None:
            non_empty_return_properties[key] = value
    for key, value in event.get('ResourceProperties').items():
        if 'OktaUser' in resource_type:
            if key in ALLOWED_USER_PROPERTIES:
                properties[key] = value
        if 'OktaGroup' in resource_type:
            if key in ALLOWED_GROUP_PROPERTIES:
                properties[key] = value
        if 'OktaUserGroup' in resource_type:
            if key in ALLOWED_USER_GROUP_ATTACHMENT_PROPERTIES:
                properties[key] = value
    func = function_group.get(request_type)
    if physical_resource_id:
        properties['PhysicalResourceId'] = physical_resource_id
    success, reason, _id = func(properties)
    non_empty_return_properties['Status'] = success
    non_empty_return_properties['Reason'] = reason
    if _id:
        non_empty_return_properties['PhysicalResourceId'] = _id
    requests.put(url=response_url,
                 data=json.dumps(non_empty_return_properties))
コード例 #9
0
def update_dashboard(dashboard_id, name, charts, org, project, api_key):
    payload = {'data': {'attributes': {'name': name, 'charts': charts}}}
    log.debug('update payload:')
    log.debug(json.dumps(payload))
    response = requests.put(
        'https://api.lightstep.com/public/v0.2/%s/projects/%s/metric_dashboards/%s'
        % (org, project, dashboard_id),
        headers={'Authorization': 'Bearer %s' % api_key},
        json=payload)
    return response.json()
コード例 #10
0
 def post_accept(id):
     requests.put(
         "https://discordapp.com/api/guilds/200746010102726657/members/" +
         str(id) + "/roles/530223486694719558",
         data=None,
         headers=headers)
     requests.put(
         "https://discordapp.com/api/guilds/200746010102726657/members/" +
         str(id) + "/roles/" + guildrole(playerdata['guildid']),
         data=None,
         headers=headers)
     guildtag = getguildtag(playerdata['guildid'])
     requests.patch(
         "https://discordapp.com/api/guilds/200746010102726657/members/" +
         str(id),
         data=None,
         json={'nick': '[' + guildtag + '] ' + player['albionname']},
         headers=headers)
     return
コード例 #11
0
def make_action_and_confirm(url, payload=None):
    auth_header = {"Authorization": "Bearer " + auth_token}
    r = requests.put(url, headers=auth_header, data=payload)
    if (r.status_code == 204):
        return True
    elif (r.status_code == 401):
        print("refreshing auth")
        refresh_auth(url, payload)
    else:
        print(r.status_code, r.text)
        return False
    def wrapper_func(event, context):

        logger.debug("Received %s request with event: %s" %
                     (event['RequestType'], json.dumps(event)))

        response = {
            "StackId": event["StackId"],
            "RequestId": event["RequestId"],
            "LogicalResourceId": event["LogicalResourceId"],
            "PhysicalResourceId": "custom_resource_physical_id",
            "Status": SUCCESS,
        }
        if event.get("PhysicalResourceId", False):
            response["PhysicalResourceId"] = event["PhysicalResourceId"]

        if base_response is not None:
            response.update(base_response)

        try:
            response.update(func(event, context))
        except NoResponse:
            # Do nothing, maybe we're being rescheduled?
            return
        except Exception as e:
            logger.exception("Failed to execute resource function")
            reason = "Exception was raised while handling custom resource."
            reason += " Message {}".format(e.args or e.message)
            response.update({
                "Status": FAILED,
                "Reason": reason,
                "Data": {
                    'FailureReason': reason
                }
            })

        serialized = json.dumps(response)
        logger.info("Responding to '%s' request with: %s" %
                    (event['RequestType'], serialized))

        req = requests.put(event['ResponseURL'],
                           data=serialized,
                           headers={
                               'Content-Length': str(len(serialized)),
                               'Content-Type': ''
                           })

        try:
            req
            logger.debug("Request to CFN API succeeded, nothing to do here")
        except requests.HTTPError as e:
            logger.error("Callback to CFN API failed with status %d" % e.code)
            logger.error("Response: %s" % e.reason)
        except requests.ConnectionError as e:
            logger.error("Failed to reach the server - %s" % e.reason)
コード例 #13
0
def update_list_item(event, listId, itemId, itemValue, itemVersion, itemStatus='completed'):
    headers = get_headers(event)
    if headers:
        data = {
            "value": itemValue,
            "status": itemStatus,
            "version": itemVersion
        }
        url = event['context']['System']['apiEndpoint'] + '/v2/householdlists/'+listId+'/items/'+itemId
        r = requests.put(url, headers=headers, data=json.dumps(data))
        logger.info(r.json())
コード例 #14
0
def response(status, event, context):
    request_body = {
        "Status": status,
        "PhysicalResourceId": context.log_stream_name,
        "StackId": event["StackId"],
        "RequestId": event["RequestId"],
        "LogicalResourceId": event["LogicalResourceId"],
        "Data": {}
    }
    response = requests.put(event["ResponseURL"],
                            data=json.dumps(request_body))
コード例 #15
0
    def send_response():
        """
        Send a response to cloudformation

        """

        log_info(event)
        response = requests.put(event['ResponseURL'],
                                json=event,
                                headers={'content-type': ''})
        response.raise_for_status()
コード例 #16
0
def send(event,
         context,
         responseStatus,
         responseData=None,
         physicalResourceId=None,
         noEcho=False,
         reason=None):
    try:
        log_stream_name = context.log_stream_name
    except:
        log_stream_name = '__mock__'

    if responseData:
        response_size = 0
        try:
            response_size = len(
                json.dumps(responseData, sort_keys=True, default=str))
            assert response_size <= 4096, 'response > 4k'
        except Exception as e:
            print('response: length={} error={}'.format(
                response_size, repr(e)))
            responseData = None

    responseUrl = event['ResponseURL']
    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody[
        'Reason'] = reason or 'See the details in CloudWatch Log Stream: ' + log_stream_name
    responseBody['PhysicalResourceId'] = physicalResourceId or log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['Data'] = responseData
    responseBody['NoEcho'] = noEcho

    json_responseBody = json.dumps(responseBody, sort_keys=True, default=str)

    if not noEcho: print("Response body:\n" + json_responseBody)

    if not log_stream_name == '__mock__':
        headers = {
            'content-type': '',
            'content-length': str(len(json_responseBody))
        }

        try:
            response = requests.put(responseUrl,
                                    data=json_responseBody,
                                    headers=headers)
            print("Status code: " + response.reason)
        except Exception as e:
            print("send(..) failed executing requests.put(..): " + str(e))
    else:
        print('Done!')
コード例 #17
0
def handler(event, context):
    count = 0
    for record in event["Records"]:
        # Get the primary key for use as the Elasticsearch ID
        id = record["dynamodb"]["Keys"]["id"]["S"]
        print id

        document = record["dynamodb"]["NewImage"]
        r = requests.put(url + id, auth=awsauth, json=document, headers=headers)
        count += 1
    return str(count) + " records processed."
def sendResponseToCloudformation(event, context, responseStatus):
    response_body = {'Status': responseStatus,
                     'Reason': 'Log stream name: ' + context.log_stream_name,
                     'PhysicalResourceId': context.log_stream_name,
                     'StackId': event['StackId'],
                     'RequestId': event['RequestId'],
                     'LogicalResourceId': event['LogicalResourceId'],
                     'Data': json.loads("{}")}

    response = requests.put(event['ResponseURL'], data=json.dumps(response_body))
    
    print("response ---> ", response)
コード例 #19
0
def send(
    event,
    context,
    response_status: str,
    response_data: str,
    physical_resource_id=None,
    no_echo=False,
    response_body={},
):
    """Help programming CustomResource within CloudFormation.

    Args:
        event: The Lambda event object
        context: The Lambda context object
        response_status: String with values "Success" or "Failure"
        response_data: A message for response logging
        physical_resource_id: CloudFormation PhysicalResourceId. Default None
        no_echo: CloudFormation echo capabilities. Default False
        response_body: Response object
    Returns:
        No Returns are delivered
    """
    response_url = event["ResponseURL"]

    print(response_url)

    response_body["Status"] = response_status
    response_body["Reason"] = ("See the details in CloudWatch Log Stream: " +
                               context.log_stream_name)
    response_body["PhysicalResourceId"] = (physical_resource_id
                                           or context.log_stream_name)
    response_body["StackId"] = event["StackId"]
    response_body["RequestId"] = event["RequestId"]
    response_body["LogicalResourceId"] = event["LogicalResourceId"]
    response_body["NoEcho"] = no_echo
    response_body["Data"] = response_data

    json_response_body = json.dumps(response_body)

    print("Response body:\n" + json_response_body)

    headers = {
        "content-type": "",
        "content-length": str(len(json_response_body))
    }

    try:
        response = requests.put(response_url,
                                data=json_response_body,
                                headers=headers)
        print("Status code: " + response.reason)
    except Exception as e:
        print("send(..) failed executing requests.put(..): " + str(e))
コード例 #20
0
def send(event,
         context,
         responseStatus,
         responseData,
         physicalResourceId,
         logger,
         reason=None):

    responseUrl = event['ResponseURL']
    logger.debug("CFN response URL: " + responseUrl)

    responseBody = {}
    responseBody['Status'] = responseStatus
    msg = 'See details in CloudWatch Log Stream: ' + context.log_stream_name
    if not reason:
        responseBody['Reason'] = msg
    else:
        responseBody['Reason'] = str(reason)[0:255] + '... ' + msg

    if physicalResourceId:
        responseBody['PhysicalResourceId'] = physicalResourceId
    elif 'PhysicalResourceId' in event:
        responseBody['PhysicalResourceId'] = event['PhysicalResourceId']
    else:
        responseBody['PhysicalResourceId'] = context.log_stream_name

    responseBody['StackId'] = event['StackId']
    try:
        responseBody['RequestId'] = event['RequestId']
    except KeyError:
        responseBody['RequestId'] = event['id']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    if responseData and responseData != {} and responseData != [] and isinstance(
            responseData, dict):
        responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)

    logger.debug("Response body:\n" + json_responseBody)

    headers = {
        'content-type': '',
        'content-length': str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logger.info("CloudFormation returned status code: " + response.reason)
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): " + str(e))
        raise
コード例 #21
0
def callback(url, data):
    try:
        headers = {'Content-Type': ''}
        r = requests.put(url, data=data, headers=headers)
        r.raise_for_status()
        logger.debug("Request to CloudFormation succeeded")
    except requests.exceptions.HTTPError as e:
        logger.error("Callback to CloudFormation failed with status %d" %
                     e.response.status_code)
        logger.error("Response: %s" % e.response.text)
    except requests.exceptions.RequestException as e:
        logger.error("Failed to reach CloudFormation: %s" % e)
コード例 #22
0
def send_response(event, context, response_status, response_data):
    response_body = {'Status': response_status,
                    'StackId': event['StackId'],
                    'RequestId': event['RequestId'],
                    'PhysicalResourceId': context.log_stream_name,
                    'Reason': 'For details see AWS CloudWatch LogStream: ' + context.log_stream_name,
                    'LogicalResourceId': event['LogicalResourceId'],
                    'Data': response_data}
    request = requests.put(event['ResponseURL'], data=json.dumps(response_body))
    if request.status_code != 200:
        print(request.text)
        raise Exception('Error detected in [CFN RESPONSE != 200.')
コード例 #23
0
ファイル: lf1.py プロジェクト: FatBin/photo
def lambda_handler(event, context):

    #log s3 trigger
    for k, v in event.items():
        print("k:  ", k, " v: ", v)

    #call recognitions
    bucket = event['Records'][0]['s3']['bucket']['name']
    photo = event['Records'][0]['s3']['object']['key']

    print("bucketname: ", bucket)
    print("photoname: ", photo)
    labels = detect_labels(photo, bucket)

    #store to ES
    client = boto3.client('es')
    headers = {"Content-Type": "application/json"}

    #ES insert
    payload = '{ "index" : { "_index": "restaurants", "_type" : "Restaurant"} }\n'
    payload += '{"objectKey": "' + photo + '", "bucket": "' + bucket + '", "createdTimestamp": "' + datetime.now(
    ).strftime("%Y-%m-%dT%H:%M:%S") + '", "labels": ' + json.dumps(
        labels) + '}\n'
    print("write to es:")
    print(payload)
    '''
    payload = {
        "_index": "restaurants",
        "_type": "Restaurant",
        "_source": {
            "objectKey": photo,
            "bucket": bucket,
            "createdTimestamp": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
            "jsp": labels
            }
        }
    '''
    print(str(payload).lower())
    response = requests.put(
        'https://vpc-xl-es-single-iweyxmypvbdfodxpdfmxpy5c6i.us-east-1.es.amazonaws.com/_bulk',
        data=payload,
        headers=headers)

    #ES search

    print(response.json())
    print("error occured when inserting data?: ",
          response.json()['errors'])  # False = inserted
    print("inserted")

    #return
    return {'statusCode': 200, 'body': json.dumps('Photo upload Succeed')}
コード例 #24
0
def lambda_handler(event, context):
    _init_bin('vault')
    s='-config='
    s+=os.path.join(BIN_DIR, 'vault.hcl')
    cmdline = [os.path.join(BIN_DIR, 'vault'), 'server', s]
#    cmdline = [os.path.join(BIN_DIR, 'vault'), 'server', '-dev']
#    try:
#        print subprocess.check_output(cmdline, shell=False, stderr=subprocess.STDOUT)
#    except subprocess.CalledProcessError, e:
#        print "Ping stdout output:\n", e.output
    shutil.copy(os.path.join(LAMBDA_TASK_ROOT, 'vault.hcl'), os.path.join(BIN_DIR, 'vault.hcl'))
    replace(os.path.join(BIN_DIR, 'vault.hcl'), 'BUCKET_NAME', BUCKET_NAME)
    replace(os.path.join(BIN_DIR, 'vault.hcl'), 'KEY_ID', KEY_ID)
    subprocess.Popen(cmdline, shell=False, stderr=subprocess.STDOUT)
    print('subprocess started')
    while True:
        try:
            response = requests.get('http://localhost:8200/v1/sys/seal-status')
            print('vault is running!')
            break
        except requests.ConnectionError:
            print('sleeping')
            time.sleep(5.0)
    path = remove_prefix(event['path'])
    print(path)
    url=urlparse.urljoin('http://localhost:8200', path)
    if event['httpMethod'] == 'GET':
        request = requests.get(url, headers=event['headers'])
    elif event['httpMethod'] == 'PUT':
        print event['body']
        request = requests.put(url, headers=event['headers'], data=event['body'])
    elif event['httpMethod'] == 'POST':
        print event['body']
        request = requests.post(url, headers=event['headers'], data=event['body'])
    else:
        print(fail)
    print(request.text)
    if request.text:
        data = request.json()
        print(data)
        return {
            'statusCode': request.status_code,
            'body': json.dumps(data),
            'isBase64Encoded': 'false'
        }
    else:
        print('empty')
        return {
            'statusCode': request.status_code,
            'isBase64Encoded': 'false'
        }
コード例 #25
0
def send(event,
         context,
         responseStatus,
         responseData,
         physicalResourceId,
         logger,
         reason=None):

    responseUrl = event['ResponseURL']
    logger.debug("CFN response URL: " + responseUrl)

    responseBody = {}
    responseBody['Status'] = responseStatus
    msg = 'See details in CloudWatch Log Stream: ' + context.log_stream_name
    if not reason:
        responseBody['Reason'] = msg
    else:
        responseBody['Reason'] = str(reason)[0:255] + '... ' + msg
    responseBody[
        'PhysicalResourceId'] = physicalResourceId or context.log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    if responseData and responseData != {} and responseData != [] and isinstance(
            responseData, dict):
        responseBody['Data'] = responseData

    logger.debug("<<<<<<< Response body >>>>>>>>>>")
    logger.debug(responseBody)
    json_responseBody = json.dumps(responseBody)

    headers = {
        'content-type': '',
        'content-length': str(len(json_responseBody))
    }

    try:
        if responseUrl == 'http://pre-signed-S3-url-for-response':
            logger.info(
                "CloudFormation returned status code: THIS IS A TEST OUTSIDE OF CLOUDFORMATION"
            )
            pass
        else:
            response = requests.put(responseUrl,
                                    data=json_responseBody,
                                    headers=headers)
            logger.info("CloudFormation returned status code: " +
                        response.reason)
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): " + str(e))
        raise
コード例 #26
0
def sendResponseCfn(event, context, responseStatus):
    """
    Send the correctly formatted response_data for cloudformation to know that this lambda has succeeded or failed.

    Args:
      event (dict): the aws event that triggered the lambda
      context (dict): the aws context the lambda runs under
      responseStatus (string): SUCCESS or FAILED
    Returns:
      nothing
    """
    response_body = {
        'Status': responseStatus,
        'Reason': 'Log stream name: ' + context.log_stream_name,
        'PhysicalResourceId': context.log_stream_name,
        'StackId': event['StackId'],
        'RequestId': event['RequestId'],
        'LogicalResourceId': event['LogicalResourceId'],
        'Data': json.loads("{}")
    }

    requests.put(event['ResponseURL'],
                 data=json.dumps(response_body).encode("utf8"))
コード例 #27
0
ファイル: ESManualSnapshot.py プロジェクト: vineetps/Lambda
def lambda_handler(event, context):

    bucket = event['bucket']
    host = event['host']
    region = event['region']
    snapshotRole = event['snapshotRole']
    snapshotName = event['snapshotName']
    path = '_snapshot/' + host.split('/')[2]
    service = 'es'

    credentials = boto3.Session().get_credentials()
    awsauth = AWS4Auth(credentials.access_key,
                       credentials.secret_key,
                       region,
                       service,
                       session_token=credentials.token)

    url = host + path
    print url
    payload = {
        "type": "s3",
        "settings": {
            "bucket": bucket,
            "region": region,
            "role_arn": snapshotRole
        }
    }

    headers = {"Content-Type": "application/json"}

    r = requests.put(url, auth=awsauth, json=payload, headers=headers)
    print(r.status_code)
    print(r.text)

    r = requests.put(url + '/' + snapshotName)
    print(r.status_code)
    print(r.text)
コード例 #28
0
def send_response(event, context, status, data=None):

    response_url = None

    if 'ResponseURL' in event:
        response_url = event['ResponseURL']
    else:
        LOGGER.warning('Request did not contain a ResponseURL.')
        if data:
            LOGGER.info(data)
        return 500

    response_body = {}
    response_body['Status'] = status
    response_body['Reason'] = 'Log Stream=%s' % context.log_stream_name
    response_body['PhysicalResourceId'] = context.log_stream_name
    response_body['StackId'] = event[
        'StackId'] if 'StackId' in event else "Unknown StackId"
    response_body['RequestId'] = event[
        'RequestId'] if 'RequestId' in event else "Unknown RequestId"
    response_body['LogicalResourceId'] = (event['LogicalResourceId']
                                          if 'LogicalResourceId' in event else
                                          "Unknown LogicalResourceId")

    response_body['Data'] = data if data else {}
    json_body = json.dumps(response_body)
    LOGGER.debug("Response %s" % json_body)
    headers = {'content-type': '', 'content-length': str(len(json_body))}

    try:
        response = requests.put(response_url, data=json_body, headers=headers)

    except Exception as e:
        LOGGER.error(
            "Failed to send response. stack-id=%(stack)s, resource-type=%(rt)s, err=%(err)s, url=%(url)s"
            % {
                'stack': event['StackId'],
                'rt': event['ResourceType'],
                'err': e,
                'url': response_url
            })
        return 500

    else:
        LOGGER.info("Response sent, status=%(code)s, url=%(url)s" % {
            'code': response.reason,
            'url': response_url
        })
        return response.reason
コード例 #29
0
def send_cfn_confirmation(event,
                          context,
                          responseStatus,
                          responseData,
                          physicalResourceId,
                          logger,
                          reason=None):

    if (os.environ['CONFIRM'] == 'False'):  # is there a better way of doing
        # this? I think there are some runtime options with SAM
        logger.info("In DEBUG mode and not confirming")
        return

    responseUrl = event['ResponseURL']
    logger.info("CFN response URL: " + responseUrl)

    responseBody = {}
    responseBody['Status'] = responseStatus
    msg = 'See details in CloudWatch Log Stream: ' + context.log_stream_name
    if not reason:
        responseBody['Reason'] = msg
    else:
        responseBody['Reason'] = str(reason)[0:255] + '... ' + msg
    responseBody[
        'PhysicalResourceId'] = physicalResourceId or context.log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    if responseData and responseData != {} and responseData != [] and isinstance(
            responseData, dict):
        responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)

    logger.info("Response body:\n" + json_responseBody)

    headers = {
        'content-type': '',
        'content-length': str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logger.info("CloudFormation returned status code: " + response.reason)
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): " + str(e))
        raise
コード例 #30
0
ファイル: handler.py プロジェクト: ericnchen/toggl-watcher
def stop(event, context):
    logger.debug("Starting the stop_current() routine.")

    status = check_status()

    if "id" in status:
        url = f"https://www.toggl.com/api/v8/time_entries/{status['id']}/stop"
        token = os.environ["TOGGL_API_TOKEN"]
        auth_token = base64.b64encode(f"{token}:api_token".encode()).decode()
        r = requests.put(url, headers={"Authorization": "Basic " + auth_token})
        status_code = r.status_code
    else:
        status_code = 200

    return {"statusCode": status_code}
コード例 #31
0
def handler(event, context):
    count = 0
    for record in event["Records"]:
        # Get the primary key for use as the Elasticsearch ID
        id = record["dynamodb"]["Keys"]["id"]["S"]
        print "bookId " + id

        if record['eventName'] == 'REMOVE':
            r = requests.delete(url + id, auth=awsauth)
        else:
            document = record['dynamodb']['NewImage']
            r = requests.put(url + id, auth=awsauth, json=document, headers=headers)
        count += 1
        
    return str(count) + " records processed."
コード例 #32
0
ファイル: setup_cognito.py プロジェクト: Stage2Sec/Hindsite
def lambda_handler(event, context):
    print(event)
    domain = ''
    try:
        if event['RequestType'] == "Create":
            domain_name = event['ResourceProperties']['DomainName']
            user_pool_id = event['ResourceProperties']['UserPoolId']
            client_id = event['ResourceProperties']['ClientId']
            endpoint_url = event['ResourceProperties']['EndpointUrl']
            domain = create_domain(domain_name,user_pool_id)
            update_client_settings(user_pool_id,client_id, endpoint_url)
        elif event['RequestType'] == "Update":
            old_domain_name = event['OldResourceProperties']['DomainName']
            old_user_pool_id = event['OldResourceProperties']['UserPoolId']
            domain_name = event['ResourceProperties']['DomainName']
            user_pool_id = event['ResourceProperties']['UserPoolId']
            client_id = event['ResourceProperties']['ClientId']
            endpoint_url = event['ResourceProperties']['EndpointUrl']
            delete_domain(old_domain_name,old_user_pool_id)
            domain = create_domain(domain_name, user_pool_id)
            update_client_settings(user_pool_id,client_id, endpoint_url)
        elif event['RequestType'] == "Delete":
            domain_name = event['ResourceProperties']['DomainName']
            user_pool_id = event['ResourceProperties']['UserPoolId']
            delete_domain(domain_name, user_pool_id)

    except Exception as e:
        print(e)
    finally:
        response_url = event['ResponseURL']
        response_body = dict()
        response_body['Status'] = "SUCCESS"
        response_body['Reason'] = ""
        response_body['PhysicalResourceId'] = 'NONE'
        response_body['StackId'] = event['StackId']
        response_body['RequestId'] = event['RequestId']
        response_body['LogicalResourceId'] = event['LogicalResourceId']
        json_response_body = json.dumps(response_body)
        print(json_response_body)

        headers = {
        'content-type': '',
        'content-length': str(len(json_response_body))
        }

        response = requests.put(response_url,
                                data=json_response_body,
                                headers=headers)
コード例 #33
0
ファイル: index.py プロジェクト: dvedhire/cdk-examples
def sendResponse(event, context, responseStatus, responseData):
    responseBody = {'Status': responseStatus,
                    'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
                    'PhysicalResourceId': context.log_stream_name,
                    'StackId': event['StackId'],
                    'RequestId': event['RequestId'],
                    'LogicalResourceId': event['LogicalResourceId'],
                    'Data': responseData}
    print 'RESPONSE BODY:n' + json.dumps(responseBody)
    responseUrl = event['ResponseURL']
    json_responseBody = json.dumps(responseBody)
    headers = {
        'content-type' : '',
        'content-length' : str(len(json_responseBody))
    }
    response = requests.put(responseUrl,data=json_responseBody,headers=headers)
コード例 #34
0
def send_response(event,
                  context,
                  responseStatus,
                  responseData,
                  resourceId,
                  reason=None):
    logging.getLogger().debug("send_response - Start")

    responseUrl = event['ResponseURL']
    logging.getLogger().debug(responseUrl)

    cw_logs_url = "https://console.aws.amazon.com/cloudwatch/home?region=%s#logEventViewer:group=%s;stream=%s" % (
        context.invoked_function_arn.split(':')[3], context.log_group_name,
        context.log_stream_name)
    logging.getLogger().debug("Logs: cw_logs_url")

    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody['Reason'] = reason or (
        'See the details in CloudWatch Logs: ' + cw_logs_url)
    responseBody['PhysicalResourceId'] = resourceId
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['NoEcho'] = False
    responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)

    logging.getLogger().debug("Response body:\n" + json_responseBody)

    headers = {
        'content-type': '',
        'content-length': str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logging.getLogger().debug("Status code: " + response.reason)

    except Exception as error:
        logging.getLogger().error(
            "send(..) failed executing requests.put(..): " + str(error))

    logging.getLogger().debug("send_response - End")
コード例 #35
0
def send_response(event, context, response_status, response_data):
    response_body = json.dumps({
        "Status": response_status,
        "Reason": "See the details in CloudWatch Log Stream: " + context.log_stream_name,
        "PhysicalResourceId": context.log_stream_name,
        "StackId": event['StackId'],
        "RequestId": event['RequestId'],
        "LogicalResourceId": event['LogicalResourceId'],
        "Data": response_data
    })
    
    headers = {
        "Content-Type": "",
        "Content-Length": str(len(response_body))
    }
    
    response = requests.put(event["ResponseURL"], headers = headers, data = response_body)
コード例 #36
0
    def send_response(cls, resource, url, response_content):
        if url == cls.DUMMY_RESPONSE_URL_SILENT:
            return
        elif url == cls.DUMMY_RESPONSE_URL_PRINT:
            six.print_(json.dumps(response_content, indent=2))
        else:
            put_response = requests.put(url,
                                        data=json.dumps(response_content))
            status_code = put_response.status_code
            response_text = put_response.text
            
            body_text = ""
            if status_code // 100 != 2:
                body_text = "\n" + response_text
            resource._base_logger.debug("Status code: {} {}{}".format(put_response.status_code, http_client.responses[put_response.status_code], body_text))

        return put_response
コード例 #37
0
def sendResponse(event, context, responseStatus, responseData):
    responseBody = {'Status': responseStatus,
                    'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
                    'PhysicalResourceId': context.log_stream_name,
                    'StackId': event['StackId'],
                    'RequestId': event['RequestId'],
                    'LogicalResourceId': event['LogicalResourceId'],
                    'Data': responseData}
    print 'RESPONSE BODY:n' + json.dumps(responseBody)
    try:
        req = requests.put(event['ResponseURL'], data=json.dumps(responseBody))
        if req.status_code != 200:
            print req.text
            raise Exception('Recieved non 200 response while sending response to CFN.')
        return
    except requests.exceptions.RequestException as e:
        print req.text
        print e
        raise
コード例 #38
0
def sendResponse(event, context, responseStatus, responseData, reason=None, physical_resource_id=None):
    responseBody = {'Status': responseStatus,
                    'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
                    'PhysicalResourceId': physical_resource_id or context.log_stream_name,
                    'StackId': event['StackId'],
                    'RequestId': event['RequestId'],
                    'LogicalResourceId': event['LogicalResourceId'],
                    'Data': responseData}
    print 'RESPONSE BODY:n' + json.dumps(responseBody)
    responseUrl = event['ResponseURL']
    json_responseBody = json.dumps(responseBody)
    headers = {
        'content-type' : '',
        'content-length' : str(len(json_responseBody))
    }
    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        print "Status code: " + response.reason
    except Exception as e:
        print "send(..) failed executing requests.put(..): " + str(e)
コード例 #39
0
ファイル: crhelper.py プロジェクト: awslabs/cfncluster
def send(event, context, responseStatus, responseData, physicalResourceId, logger, reason=None):

    responseUrl = event["ResponseURL"]
    logger.debug("CFN response URL: " + responseUrl)

    responseBody = {}
    responseBody["Status"] = responseStatus
    msg = "See details in CloudWatch Log Stream: " + context.log_stream_name
    if not reason:
        responseBody["Reason"] = msg
    else:
        responseBody["Reason"] = str(reason)[0:255] + "... " + msg

    if physicalResourceId:
        responseBody["PhysicalResourceId"] = physicalResourceId
    elif "PhysicalResourceId" in event:
        responseBody["PhysicalResourceId"] = event["PhysicalResourceId"]
    else:
        responseBody["PhysicalResourceId"] = context.log_stream_name

    responseBody["StackId"] = event["StackId"]
    responseBody["RequestId"] = event["RequestId"]
    responseBody["LogicalResourceId"] = event["LogicalResourceId"]
    if responseData and responseData != {} and responseData != [] and isinstance(responseData, dict):
        responseBody["Data"] = responseData

    json_responseBody = json.dumps(responseBody)

    logger.debug("Response body:\n" + json_responseBody)

    headers = {"content-type": "", "content-length": str(len(json_responseBody))}

    try:
        response = requests.put(responseUrl, data=json_responseBody, headers=headers)
        logger.info("CloudFormation returned status code: " + response.reason)
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): " + str(e))
        raise
コード例 #40
0
def send(event, context, responseStatus, responseData, physicalResourceId,
         logger, reason=None):

    responseUrl = event['ResponseURL']
    logger.debug("CFN response URL: " + responseUrl)

    responseBody = {}
    responseBody['Status'] = responseStatus
    msg = 'See details in CloudWatch Log Stream: ' + context.log_stream_name
    if not reason:
        responseBody['Reason'] = msg
    else:
        responseBody['Reason'] = str(reason)[0:255] + '... ' + msg
    responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    if responseData and responseData != {} and responseData != [] and isinstance(responseData, dict):
        responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)

    logger.debug("Response body:\n" + json_responseBody)

    headers = {
        'content-type': '',
        'content-length': str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logger.info("CloudFormation returned status code: " + response.reason)
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): " + str(e))
        raise
コード例 #41
0
def send(event, context, response_status, response_data, physical_resource_id,
         logger, reason=None):
    response_url = event['ResponseURL']
    logger.debug("CFN response URL: {}".format(response_url))

    response_body = dict()
    response_body['Status'] = response_status
    msg = 'See CloudWatch Log Stream: {}'.format(context.log_stream_name)
    if not reason:
        response_body['Reason'] = msg
    else:
        response_body['Reason'] = str(reason)[0:255] + ' ({})'.format(msg)
    response_body['PhysicalResourceId'] = physical_resource_id or 'NONE'
    response_body['StackId'] = event['StackId']
    response_body['RequestId'] = event['RequestId']
    response_body['LogicalResourceId'] = event['LogicalResourceId']
    if response_data and response_data != {} and response_data != [] and isinstance(response_data, dict):
        response_body['Data'] = response_data

    json_response_body = json.dumps(response_body)

    logger.debug("Response body:\n{}".format(json_response_body))

    headers = {
        'content-type': '',
        'content-length': str(len(json_response_body))
    }

    try:
        response = requests.put(response_url,
                                data=json_response_body,
                                headers=headers)
        logger.info("CloudFormation returned status code: {}".format(response.reason))
    except Exception as e:
        logger.error("send(..) failed executing requests.put(..): {}".format(e))
        raise
コード例 #42
0
ファイル: cfnlambda.py プロジェクト: electronicalias/mytools
def cfn_response(event,
                 context,
                 response_status,
                 response_data={},
                 physical_resource_id=None):
    """Format and send a CloudFormation custom resource object.

    Creates a JSON payload with a CloudFormation custom resource object[1],
    then HTTP PUTs this payload to an AWS signed URL. Replicates the
    functionality of the NodeJS cfn-response module in python.[2]

    Args:
        event: A dictionary containing CloudFormation custom resource provider
            request fields.[3]
        context: An AWS LambdaContext object containing lambda runtime
            information.[4]
        response_status: A status of SUCCESS or FAILED to send back to
            CloudFormation.[2] Use the Status.SUCCESS and Status.FAILED
            constants.
        response_data: A dictionary of key value pairs to pass back to
            CloudFormation which can be accessed with the Fn::GetAtt function
            on the CloudFormation custom resource.[5]
        physical_resource_id: An optional unique identifier of the custom
            resource that invoked the function. By default, the name of the
            CloudWatch Logs log stream is used.

    Returns:
        None

    Raises:
        No exceptions raised

    [1]: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#cfn-lambda-function-code-cfnresponsemodule
    [2]: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html
    [3]: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-requests.html#crpg-ref-request-fields
    [4]: http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
    [5]: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html#crpg-ref-responses-data
    """
    if physical_resource_id is None:
        physical_resource_id = context.log_stream_name
    response_data = validate_response_data(response_data)
    reason = ("See the details in CloudWatch Log Stream: %s" %
              context.log_stream_name)
    if (response_status == Status.FAILED) and 'result' in response_data:
        reason = "%s %s" % (response_data['result'], reason)

    body = {
        "Status": response_status,
        "Reason": reason,
        "PhysicalResourceId": physical_resource_id,
        "StackId": event['StackId'],
        "RequestId": event['RequestId'],
        "LogicalResourceId": event['LogicalResourceId'],
        "Data": response_data
    }
    response_body = json.dumps(body)
    logger.debug("Response body: %s", response_body)
    try:
        response = requests.put(event['ResponseURL'],
                                data=response_body)
        logger.debug("Status code: %s" % response.status_code)
        # logger.debug("Status message: %s" % response.status_message)
        # how do we get the status message?
    except Exception as e:
        logger.error("send(..) failed executing https.request(..): %s" %
                     e.message)