I get the following error when trying to create a function and assign a newly created role. I'm printing the ARN and it looks OK.
Using "Node.js 16.x"
2023-03-17T19:26:40.245Z 342fa261-e9d8-426d-9231-60d9409a76dc INFO Role ARN is arn:aws:iam::XXXX:role/MQTT-SAVE-ROLE
2023-03-17T19:26:40.446Z 342fa261-e9d8-426d-9231-60d9409a76dc INFO Role ARN is arn:aws:iam::XXXX:role/MQTT-SAVE-ROLE
2023-03-17T19:26:41.064Z 342fa261-e9d8-426d-9231-60d9409a76dc INFO InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda.
const AWS = require('aws-sdk');
const path = require('path');
const s3 = new AWS.S3();
const lambda = new AWS.Lambda();
const iam = new AWS.IAM();
exports.handler = async (event) => {
// TODO implement
//Create Role
var info = {
name: "MQTT-SAVE-ROLE",
PolicyArn: ["arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"],
};
var role = await createRole(info);
console.log("Role ARN is", role);
//Create Function
info = {
name: "mqtt_save",
role: role
};
var respCreate = await createFunction(info);
return;
};
async function createRole(info) {
var role;
var myPolicy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
};
var createParams = {
AssumeRolePolicyDocument: JSON.stringify(myPolicy),
RoleName: info.name
};
try {
var respIam = await iam.createRole(createParams).promise();
console.log("Role ARN is", respIam.Role.Arn); // successful response
role = respIam.Role.Arn;
//attach Role Policy
for(var i = 0; i< info.PolicyArn.length; i++ ){
var policyParams = {
PolicyArn: info.PolicyArn[i],
RoleName: info.name
};
await iam.attachRolePolicy(policyParams).promise();
}
} catch (err) {
console.log(err, err.stack); // an error occurred
return;
}
return role;
}
async function createFunction(info) {
//Create Function
var params = {
Code: {
S3Bucket: 'base-lambda-code',
S3Key : info.name + '.zip',
},
FunctionName: info.name + '_test',
Description: 'Function used to save data from MQTT to Dynamo DB',
Role: info.role,
Handler: 'index.handler',
Runtime: "nodejs16.x" ,
PackageType: "Zip",
Publish: true,
Timeout: '60',
};
try {
var response = await lambda.createFunction(params).promise();
console.log("ARN: ",response.FunctionArn );
console.log("State: ", response.State );
} catch (err) {
console.log(err, err.stack); // an error occurred
return;
}
return response;
}
Thank you for the response Skisman, but I don't think that is the problem that I'm having right now, If I create the role and then run the function to add it to the lambda it works, it is just when I do it all in the same function. It looks like it needs to "wait until active" (I haven't found this option), I also tried adding delays but I get the same result