0

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)

Parzival
  • 2,004
  • 4
  • 33
  • 47
  • I'm confused why don't you want to comment out the appropriate line "/etc/sudoers" and do the `sudo shutdown` command "programmatically"? – Reinstate Monica Please Jan 20 '14 at 06:12
  • Pardon my nOOb question, but is there a way to comment out the `Default requiretty` line programmatically then? And wouldn't that itself require root privileges? – Parzival Jan 20 '14 at 06:33
  • Sorry, I meant you can do the `sudo shutdown` command programmatically after you login and modify the system file. Why do you need to modify the file from the same script? – Reinstate Monica Please Jan 20 '14 at 06:44
  • Because I don't actually login, I'm passing the script via cloud-init. – Parzival Jan 20 '14 at 06:48

2 Answers2

1

You cannot shutdown a Linux system without appropriate privileges (required by reboot(2) syscall).

And you need root privileges to edit /etc/sudoers to enable sudo without password.

If what you try was possible, there would be no protection on Linux, which is (like all Unixes) a multi-user operating system.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

This is probably an AWS-only solution, but...

I launched an EC2 instance, SSH'd into it, manually commented out the Default requiretty on /etc/sudoers, saved the change, created an Amazon Machine Image (AMI) based on that instance, then used that AMI to launch all other instances. The change on /etc/sudoers propagates to any instance based on that AMI, so os.system('sudo shutdown now -P') will work fine.

Parzival
  • 2,004
  • 4
  • 33
  • 47