Skip to content

EC2 User Data Script Not Executing NodeJs File On Launch or Reboot

0

I'm trying to build a user data file to be included on each and every AWS EC2 instance I launch.

The data should be executed on initial launch, as well as on every reboot/restart.

It is supposed to create/overwrite a .env file using params passed in the data itself, and then run a nodejs app that comes as part of the custom system image.

This is what I have so far

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash

# Function for logging
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> /home/ec2-user/userdata.log
}

log "Starting User Data script execution"

# Create .env file
log "Creating .env file"
cat << EOF > /home/ec2-user/.env
UN=XXXX
PW=XXXX
EOF
log ".env file created"

cd /home/ec2-user/
log "Current directory: $(pwd)"
screen -d -m node index.js
log "User Data script execution completed"

--//--

This successfully creates the .env file, however it is not able to launch index.js, despite explicitly navigating to the directory that I am 100% certain contains the file in question.

I can SSH into the machine and run the same screen -d -m node index.js command with no issues.

Any help would be greatly appreciated!

asked a year ago155 views
1 Answer
1

Hello,

Try screen -dmS session1 node index.js

Also use absolute path like /home/ec2-user/index.js

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.