Reputation: 1240
I am trying to execute a shell command to migrate from the AWS lambda. The idea is that whenever we need to run the migration, we will call the lambda via AWS CLI. I am unable to make it run. The command to run migration never gets executed and it's always response with null. Any help would be greatly appreciated.
This is the code I have :
const exec = require("child_process").exec;
const { okResponse, errorResponse } = require('./response');
exports.handler = async (event) => {
exec("node ./node_modules/db-migrate/bin/db-migrate up --config=./database.json", (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error.message}`);
return errorResponse(500, 'Error running migration.');
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return errorResponse(500, 'Error running migration.');
}
console.log(`stdout: ${stdout}`);
return okResponse(200, 'Migration successfully.');
});
}
Upvotes: 2
Views: 6379
Reputation: 238081
My guess is that because you are using async lambda handler your function finishes before exec
has a chance to even run. Therefore, you could use promise
, as shown in the linked docs, to solve this issue.
An example would be:
const exec = require("child_process").exec;
const { okResponse, errorResponse } = require('./response');
exports.handler = async (event) => {
const promise = new Promise(function(resolve, reject) {
exec("node ./node_modules/db-migrate/bin/db-migrate up --config=./database.json", (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error.message}`);
return errorResponse(500, 'Error running migration.');
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return errorResponse(500, 'Error running migration.');
}
console.log(`stdout: ${stdout}`);
return okResponse(200, 'Migration successfully.');
})
})
return promise
}
Please note that I haven't run the code, and further changes may be required to make it work correctly.
Upvotes: 6