Add sudo commands to init script through user data

December 19, 2018 985 views
Docker Automated Setups DigitalOcean Getting Started Initial Server Setup

Hello Geeks
I’m trying to create an init script for my droplet creation. So I’m setting Droplet meta data using User Data feature. I successfully install git and added new non root sudo user to the system. But when I try to install docker it’s not getting installed. My guess is because it’s a sudo command. Below is my script.

#!/bin/bash
set -euo pipefail

USERNAME=test

COPY_AUTHORIZED_KEYS_FROM_ROOT=true

OTHER_PUBLIC_KEYS_TO_ADD=()

useradd --create-home --shell "/bin/bash" --groups sudo "${USERNAME}"
usermod -aG sudo "${USERNAME}"

encrypted_root_pw="$(grep root /etc/shadow | cut --delimiter=: --fields=2)"

if [ "${encrypted_root_pw}" != "*" ]; then
    echo "${USERNAME}:${encrypted_root_pw}" | chpasswd --encrypted
    passwd --lock root
else
    passwd --delete "${USERNAME}"
fi

chage --lastday 0 "${USERNAME}"

home_directory="$(eval echo ~${USERNAME})"
mkdir --parents "${home_directory}/.ssh"

if [ "${COPY_AUTHORIZED_KEYS_FROM_ROOT}" = true ]; then
    cp /root/.ssh/authorized_keys "${home_directory}/.ssh"
fi

for pub_key in "${OTHER_PUBLIC_KEYS_TO_ADD[@]}"; do
    echo "${pub_key}" >> "${home_directory}/.ssh/authorized_keys"
done

chmod 0700 "${home_directory}/.ssh"
chmod 0600 "${home_directory}/.ssh/authorized_keys"
chown --recursive "${USERNAME}":"${USERNAME}" "${home_directory}/.ssh"

sed --in-place 's/^PermitRootLogin.*/PermitRootLogin prohibit-password/g' /etc/ssh/sshd_config
if sshd -t -q; then
    systemctl restart sshd
fi

apt-get install -y git
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install -y docker-ce
sudo curl -L https://github.com/docker/compose/releases/download/1.18.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
usermod -aG docker "${USERNAME}"

1 Answer

Hey friend,

I don’t think the sudo would throw it off, this should all be run at a level that doesn’t require it so it should just be excess at most. I have a couple of thoughts:

  1. Does the script run fine on a new droplet if you run it manually?
  2. What if you dropped a “sleep 30” at the top and downloaded/executed the script via user-data instead of running it directly in it? Here’s a good resource for building a user-data script: https://blog.digitalocean.com/automating-application-deployments-with-user-data/

Jarland

Have another answer? Share your knowledge.