I want to launch an Amazon EC2 instance programmatically, use cloud-init to execute a Python script, then have this same script terminate the instance. Everything works fine, except for the self-termination part. I've tried this:
os.system('sudo shutdown now -P')
And this:
os.system('sudo -n shutdown now -P')
And also this:
os.popen('sudo -S shutdown now -P')
No good. In all cases the /var/log/cloud-init.log
file shows sudo: sorry, you must have a tty to run sudo
.
Apparently commenting out the Default requiretty
line on /etc/sudoers
does the trick, but I want to do things programmatically, so I guess that's not an option here (and it probably would require root privileges as well, which takes us back to square one).
I suppose I could use a multi-part cloud-init script - say, follow the Python script with a bash script that does the self-termination. But surely there must be a way to solve this from within Python?
(Amazon Linux. Python 2.7.5. Boto 2.23)