horihiro
horihiro

Reputation: 98

How to know event souce of lambda function in itself

I want to know the event source of lambda function in the function.

What I want to do is to use one lambda function from some AWS service(CloudWatch, S3, Step functions, etc...) and to change its behavior depending on the service.

A context object (one of arguments of the function) has information about the lambda function but not about event source.

Is there the way to know that?

Upvotes: 4

Views: 4108

Answers (1)

user7401700
user7401700

Reputation:

If you have identified a Kinesis or DynamoDB stream as an event source for a Lambda function with the API

aws lambda create-event-source-mapping

, then you can get them with

aws lambda list-event-source-mappings

If you don't, then you can make a best guess with a function like the following:

function getLambdaEventSource(event) {
    if (event.Records && event.Records[0].cf) return 'isCloudfront';

    if (event.configRuleId && event.configRuleName && event.configRuleArn) return 'isAwsConfig';

    if (event.Records && (event.Records[0].eventSource === 'aws:codecommit')) return 'isCodeCommit';

    if (event.authorizationToken === "incoming-client-token") return 'isApiGatewayAuthorizer';

    if (event.StackId && event.RequestType && event.ResourceType) return 'isCloudFormation';

    if (event.Records && (event.Records[0].eventSource === 'aws:ses')) return 'isSes';

    if (event.pathParameters && event.pathParameters.proxy) return 'isApiGatewayAwsProxy';

    if (event.source === 'aws.events') return 'isScheduledEvent';

    if (event.awslogs && event.awslogs.data) return 'isCloudWatchLogs';

    if (event.Records && (event.Records[0].EventSource === 'aws:sns')) return 'isSns';

    if (event.Records && (event.Records[0].eventSource === 'aws:dynamodb')) return 'isDynamoDb';

    if (event.records && event.records[0].approximateArrivalTimestamp) return 'isKinesisFirehose';

    if (event.records && event.deliveryStreamArn && event.deliveryStreamArn.startsWith('arn:aws:kinesis:')) return 'isKinesisFirehose';

    if (event.eventType === 'SyncTrigger' && event.identityId && event.identityPoolId) return 'isCognitoSyncTrigger';

    if (event.Records && event.Records[0].eventSource === 'aws:kinesis') return 'isKinesis';

    if (event.Records && event.Records[0].eventSource === 'aws:s3') return 'isS3';

    if (event.operation && event.message) return 'isMobileBackend';

}

I say that it's a best guess because an event source like an API gateway request can potentially be sending anything. If you're sure that you won't have such a case, then the function above can do the trick.

Upvotes: 6

Related Questions