I am trying to put together a nodejs
script that automatically updates my code on the AWS servers whenever i update my code on github. The script uses webhooks. The following code is the script called webhook_server.js
For some reason I get the following error whenever I try to run the script:
Error writing to log file: Error: EACCES: permission denied, open '/home/ubuntu/webhook-handler/webhook_server.log'
Since its a permission issue, I thought the following command would resolve the issue but the issue still persists:
sudo chmod 755 /home/ubuntu/webhook-handler
sudo chmod 644 /home/ubuntu/webhook-handler/webhook_server.log
Following is the content the webhook_server.js
file:
const express = require('express');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
const fs = require('fs');
const app = express();
const port = 3002;
const logFile = '/home/ubuntu/webhook-handler/webhook_server.log';
const log = (message) => {
const timestamp = new Date().toISOString();
try {
fs.appendFileSync(logFile, `${timestamp} ${message}n`);
} catch (err) {
console.error(`Error writing to log file: ${err}`);
}
};
app.use(bodyParser.json());
app.post('/webhook', (req, res) => {
log('n===========================');
log('Received a webhook event');
// Verify the event is a push event
if (req.body.ref === 'refs/heads/main') {
log('Push event on main branch detected');
// Execute the script to update the code
exec('/home/ubuntu/update_code.sh', (error, stdout, stderr) => {
if (error) {
log(`Error executing script: ${error.message}`);
return res.status(500).send({ message: 'Error executing script' });
}
log(`stdout: ${stdout}`);
log(`stderr: ${stderr}`);
res.status(200).send({ message: 'Script executed successfully' });
});
} else {
log('Not a push event on main branch');
res.status(400).send({ message: 'Not a push event on main branch' });
}
});
app.listen(port, () => {
log(`Webhook handler listening at http://localhost:${port}`);
});
2
Answers
Switch to
root
account and perform this commands:chown -R ubuntu:ubuntu /home/ubuntu/webhook-handler
logout
back toubuntu
account, and then run the script.Check File Permissions:
If the error relates to file access, use the ls -l command on the EC2 instance to verify the file permissions. The user running your Node.js app (usually ec2-user or a dedicated user) should have read/write/execute permissions (depending on the operation) for the file and its directory path.
You can adjust permissions using chmod command (e.g., chmod 755 filename).