我正在使用
AWS SDK for JavaScript,当我尝试创建Lambda函数时它返回以下错误:
InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda.
我已经仔细检查了我的角色,这完全有效.但是,我仍然无法创建Lambda函数.
我的角色信任关系是:
- {
- "Version": "2012-10-17","Statement": [
- {
- "Effect": "Allow","Principal": {
- "Service": [
- "lambda.amazonaws.com"
- ]
- },"Action": [
- "sts:AssumeRole"
- ]
- }
- ]
- }
解决方法
当角色无效(事实并非如此)或尝试在角色创建后创建Lambda函数时,会发生此错误.亚马逊需要几秒钟的时间来通过所有地区复制您的新角色.所以,这里的修复是在创建Lambda函数之前等待几秒钟.
解决方案 – 示例1:
- var AWS = require('aws-sdk');
- var lambda = new AWS.Lambda();
- var params = {}; // define your parameters
- lambda.createFunction(params,function(err,data) {
- if (err && err.code === 'InvalidParameterValueException') {
- // try again after a few seconds
- setTimeout(function(){
- lambda.createFunction(params,callback);
- },10000);
- } else {
- callback(err,data);
- }
- });
解决方案 – 示例2:
通常,等待5秒就足够了,但也可以多花一点时间.对于更强大的解决方案,您可以使用重试模块,如this.
- var AWS = require('aws-sdk');
- var retry = require('retry');
- var lambda = new AWS.Lambda();
- var params = {}; // define your parameters
- var operation = retry.operation({
- retries: 3,// try 1 time and retry 3 times if needed,total = 4
- minTimeout: 1 * 1000,// the number of milliseconds before starting the first retry
- maxTimeout: 15 * 1000 // the maximum number of milliseconds between two retries
- });
- operation.attempt(function(currentAttempt) {
- lambda.createFunction(params,data) {
- if (operation.retry(err) && err.code === 'InvalidParameterValueException')
- return;
- callback(err);
- });
- });