Search code examples
node.jsamazon-ec2webhooks

How do I resolve the following EACCES: permission denied in my nodejs app?


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}`);
});

Solution

  • Switch to root account and perform this commands:

    chown -R ubuntu:ubuntu /home/ubuntu/webhook-handler

    logout back to ubuntu account, and then run the script.