0

When my EC2 VM (Ubuntu) starts, I'd like it to execute a python script myscript.py as ec2-user instead of the default root user. This includes using the ec2-user's python executable, installed packages and binaries (e.g. chromedriver)

How can I do this?

What I did/ tried so far:

  • logged in as ec2-user, I verified that python myscript.py, python --version and which python work as intended
  • logged in as root, running python results in Command 'python' not found
  • logged in as root, running su ec2-user -c python results in Command 'python' not found. Same result with sudo -u ec2-user bash -c 'python --version'
  • logged in as root, running /path/to/ec2-user/python_executable /path/to/myscript.py does start the script, but crashes due not not finding binaries (e.g. chromedriver)
  • adding su ec2-user -c 'echo "Switched to User ${USER} with $(python --version) in $(which python)" >> /path/to/logfile.log' adds the line Switched to User ec2-user with in to the logfile, hence does not assume the ec2-user user when calling python

So, how can I make my user ec2-user execute myscript.py within the execution of the user data at instance startup?

references:

Dr-Nuke
  • 368
  • 3
  • 11
  • The user-data script runs as root but you can sudo to any given user e.g. `sudo -u ubuntu whoami`. – jarmod Apr 07 '23 at 12:17

1 Answers1

0

I finally solved the problem by using a cronjob with @reboot, running the desired commands at every startup

Dr-Nuke
  • 368
  • 3
  • 11