Question
Add sudo commands to init script through user data
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}"
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
×