Running sudo commands in cloud-init script

initsudotty

I'm developing an automatic bootstrapper for some servers as we are using Amazon EC2 for our infrastructure.

What I do is: run a Fabric script which connects to EC2 and initializes a new instance, putting in user-data a cloud-init script. This script checks out a Mercurial project which contains Fabric tasks, then, after the checkout, the script will find out which type of server it's running in and execute a specific local Fabric task.

My problem is that some tasks needs to run sudo commands, as the script was initialized from cloud-init it happens that sudo warns about needing to run over a tty, I tried to modify that to run su --session-command="my commands to restart services" root and it doesn't (and seems like that shouldn't) work at all.

So, how can I run sudo commands in this boot script?

Some code:

cloud_init_script:

#!/bin/sh
su --session-command="\
source /etc/profile; \
cd /home/my_user; \
hg clone ssh://fabric_tasks_repo fabric; \
/usr/local/bin/fab -f /home/my_user/fabric/fabfile.py \`ec2-describe-tags   --filter \"resource-type=instance\"   --filter \"resource-id=$(ec2-metadata -i | cut -d ' ' -f2)\"   --filter \"key=type\" | cut -f5\` > /home/my_user/fabric.log 2>&1" my_user &

The trick in the /usr/local/bin/fab line is that it'll run some ec2 scripts to check which tag-key "type" the server is in.

Best Answer

sudo: Sorry, you must have a tty to run sudo

Run visudo and add the following line to disable requiretty for your user:

Defaults:username !requiretty