如何使用aws-sdk在现有lambda函数上创建触发器?
我希望API Gateway端点以代理集成类型作为触发器。
我使用的是nodejs和aws-sdk 2.39.0。
答案 0 :(得分:0)
不优雅,但有效。
我非常乐意接受修订/更好的解决方案。我是AWS SDK的新手。
const createApi = () => {
sts.getCallerIdentity(function(err, data) {
if (err) {
console.log(err);
} else {
const accountId = data.Account;
const functionName = 'resize-images-on-' + settings.aws.bucket;
const apiName = 'resize-images-on-' + settings.aws.bucket + '-api';
const uri = 'arn:aws:apigateway:' + settings.aws.region + ':lambda:path/2015-03-31/functions/arn:aws:lambda:' + settings.aws.region + ':' + accountId + ':function:' + functionName + '/invocations';
var apiSwagger = {
"swagger": "2.0",
"info": {
"version": "2017-04-10T12:43:16Z",
"title": apiName
},
"basePath": "/prod",
"schemes": [
"https"
],
"paths": {
"/resize": {
"x-amazon-apigateway-any-method": {
"responses": {
"200": {
"description": "200 response"
}
},
"x-amazon-apigateway-integration": {
"responses": {
".*": {
"statusCode": "200"
}
},
"uri": uri,
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"type": "aws_proxy"
}
}
}
}
}
apiSwagger = JSON.stringify(apiSwagger);
const apiParams = {
body: apiSwagger,
};
apigateway.importRestApi(apiParams, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('API created');
configureLambda(data.id, accountId);
}
});
}
});
}
const configureLambda = (apiId, accountId) => {
console.log('Configuring lambda ...');
const functionName = 'resize-images-on-' + settings.aws.bucket;
const lambdaPolicies = [
{
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: "apigateway.amazonaws.com",
StatementId: uuid(),
SourceArn: 'arn:aws:execute-api:' + settings.aws.region + ':' + accountId + ':' + apiId + '/prod/ANY/resize'
},
{
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: "apigateway.amazonaws.com",
StatementId: uuid(),
SourceArn: 'arn:aws:execute-api:' + settings.aws.region + ':' + accountId + ':' + apiId + '/*/*/resize'
}
];
lambda.addPermission(lambdaPolicies[0], function(err, data) {
if (err) {
console.log(err);
} else {
lambda.addPermission(lambdaPolicies[1], function(err, data) {
if (err) {
console.log(err);
} else {
console.log('Lambda configured');
}
});
}
});
}