`sudo` commands in cloud-init are SLOW! How to fix

amazon ec2amazon-web-servicescloud-initsystemd

I am trying to bootstrap a Centos7 EC2 instance (ami-02eac2c0129f6376b) with bash user-data. Because it runs as root and I need to create a lot of things as the centos user, I use sudo -Hu centos <cmd> many times. Each call introduces a 25 second delay. I have hundreds. What can I do to speed this up?

This is a known issue, but I cannot find any solutions.

I have tried:

  • Add and /etc/hosts entry for my hostname
printf "\n127.0.0.1   %s %s\n" "$(hostname -f)" "$(hostname -s)" | tee -a /etc/hosts
  • Remove myhostname from /etc/nsswitch.conf
sed -Ei 's/\s*myhostname//' /etc/nsswitch.conf

These delays are EXTREMELY painful because I am currently in the Trial and Error phase of building out new user-data scripts.

What can I do?

Best Answer

While it's better to figure out why sudo is slow and resolve that, you can group your commands together to only call sudo once. Inside your script, you could do something like this:

sudo -Hu centos bash <<EOF
somecommand
somecommand2
morecommands
EOF