5

I'm trying and failing to start a long-running command on launch of an EC2 (Amazon Linux). It needs to run under the ec2-user account. This was my first attempt:

#!/bin/bash
echo 'Woot 1!' > /home/ec2-user/woot1.txt
pushd /home/ec2-user/my-app-dir
nohup sudo -u ec2-user /home/ec2-user/my-app-dir/my_process.py &
echo 'Woot 2!' > /home/ec2-user/woot2.txt

The key command I'm trying to run is the "nohup" line, to run my_process.py.

The shell script works when I run it as root from a shell, but when I supply it in user-data to ec2-run-instances and login to the instance, I see both woot1.txt and woot2.txt, but my_process.py is not running. What's more, my_process.py creates a log file when it runs, but there is no log file there (and no nohup.out either) when I supply the script as user-data to ec2-run-instances.

I've tried putting the same things in a cloud-init form as well, with the same results:

#cloud-config
runcmd:
 - echo 'Woot 1!' > /home/ec2-user/woot1.txt
 - pushd /home/ec2-user/my-app-dir
 - nohup sudo -u ec2-user /home/ec2-user/my-app-dir/my_process.py &
 - echo 'Woot 2!' > /home/ec2-user/woot2.txt

If anyone can tell me where I'm going wrong, I'd appreciate it.

Tom Slee
  • 181
  • 1
  • 6

2 Answers2

3

The reason the process was not running was that the Amazon EC2 Linux instance is Red-Hat like, and there is a bug/feature in those distros that a sudo command requires a tty. There is no tty attached to the environment when the cloud-init is processed, and so it fails.

One answer is to edit etc/sudoers and change the line

Defaults requiretty

to

Defaults !requiretty

There are other approaches, apparently, but this worked for me.

Tom Slee
  • 181
  • 1
  • 6
  • FYI this restriction has been removed in Fedora already https://bugzilla.redhat.com/show_bug.cgi?id=1020147 and that means it's likely to be removed from RHEL releases at some point. But whether or not amazon will follow with its derivative, I've no remote idea. – akostadinov Feb 22 '16 at 07:02
0

I'm guessing there is no shell attached to this command.

Instead of

- echo 'Woot 1!' > /home/ec2-user/woot1.txt

Try

- /bin/sh -c "echo 'Woot 1!' > /home/ec2-user/woot1.txt"
hookenz
  • 14,132
  • 22
  • 86
  • 142
  • I must not have been clear. The "echo" commands run, but my_process.py is the line that is not executed. – Tom Slee Aug 10 '15 at 11:35
  • Ah, what happens if you put the full path to nohup? /usr/bin/nohup or whatever the path is. – hookenz Aug 12 '15 at 00:02
  • So that's a good question and I'll give it a go. For now, I've fixed the problem by taking another approach: adding the script to /etc/rc.local before saving the AMI. That seems to work. – Tom Slee Aug 12 '15 at 03:11