Skip to content

Instantly share code, notes, and snippets.

@merictaze
Last active July 2, 2018 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merictaze/0f3a80a2e5c069e2dcbf8a321d7d659d to your computer and use it in GitHub Desktop.
Save merictaze/0f3a80a2e5c069e2dcbf8a321d7d659d to your computer and use it in GitHub Desktop.
EsIndexerFunction:
Type: 'AWS::Lambda::Function'
Properties:
Handler: 'index.handler'
Runtime: nodejs6.10
Role: !GetAtt LambdaRole.Arn
Environment:
Variables:
ES_ENDPOINT: !GetAtt ElasticsearchDomain.DomainEndpoint
ES_REGION: !Ref AWS::Region
Code:
ZipFile: |
var AWS = require('aws-sdk');
var path = require('path');
var creds = new AWS.EnvironmentCredentials('AWS');
var esDomain = {
endpoint: process.env.ES_ENDPOINT,
region: process.env.ES_REGION,
index: 'test',
doctype: 'order'
};
var endpoint = new AWS.Endpoint(esDomain.endpoint);
exports.handler = (event, context, callback) => {
event.Records.forEach(record => {
postDocumentToES(record.dynamodb.NewImage, context);
});
}
function postDocumentToES(doc, context) {
var req = new AWS.HttpRequest(endpoint);
req.method = 'POST';
req.path = path.join('/', esDomain.index, esDomain.doctype);
req.region = esDomain.region;
req.body = JSON.stringify(doc);
req.headers['presigned-expires'] = false;
req.headers['Host'] = endpoint.host;
// Sign the request (Sigv4)
var signer = new AWS.Signers.V4(req, 'es');
signer.addAuthorization(creds, new Date());
// Post document to ES
var send = new AWS.NodeHttpClient();
send.handleRequest(req, null, function(httpResp) {
var body = '';
httpResp.on('data', chunk => body += chunk);
httpResp.on('end', chunk => context.succeed());
}, function(err) {
console.log('Error: ' + err);
context.fail();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment