Over time, I’ve improved on my server create script by allowing for the inclusion of some configuration files that I find useful.

To do this, I created a new Github repo for my dotfiles based on some inspiration by Mastering Vim. I’ve been using Vim for quite some time, but this book had some good ideas to make my usage even better. Among them, the idea of creating a Github repo for dotfiles.

Now, I can run a script and get a configured server that I can use in a variety of ways. I’ll continue to refine it as I come up with new use cases and ideas.

The new script looks like:

#!/bin/bash
set -euo pipefail

# make a choice that is then handled in main
# use: choice <prompt>
# returns: global variable CHOICE

function choice {

    CHOICE=''
    local prompt="$*"
    local answer

    read -p "$prompt" answer
    case "$answer" in
        [yY1] ) CHOICE='y';;
        [nN0] ) CHOICE='n';;
        *     ) CHOICE="$answer";;
    esac
} # end of function choice

# hcloud arguments
NAME=tiger
IMAGE=ubuntu-20.04
TYPE=cx11
SSH_KEY=id_hetzner

# cloud-config arguments
USER_NAME=demo
SSH_PUB_KEY=`cat ~/.ssh/$SSH_KEY.pub`
SSH_PORT=4444

# use getopts to get the arguments
while getopts 'n:i:t:s:u:p:' OPTION
do
    case $OPTION in
        n) NAME="$OPTARG"
           ;;
        i) IMAGE="$OPTARG"
           ;;
        t) TYPE="$OPTARG"
           ;;
        u) USER_NAME="$OPTARG"
           ;;
        s) SSH_KEY="$OPTARG"
           ;;
        p) SSH_PORT="$OPTARG"
           ;;
        ?) printf "Usage: %s -n server_name -i "\
           "image -t value -s ssh_key -u user_name "\
           "-p ssh_port\n" ${0##*/} >&2
           exit 2
           ;;
    esac
done

printf "Provided server parameters\n"
printf "\tName: $NAME\n"
printf "\tImage: $IMAGE\n"
printf "\tType: $TYPE\n"
printf "\tSSH Key: $SSH_KEY\n"
printf "\tUser name: $USER_NAME\n"
printf "\tSSH Port: $SSH_PORT\n"
printf "\n"

choice "Would you like to create the server? [Y/n]:"
if [ "$CHOICE" != "n" ]; then
    printf "Creating...\n"
else
    exit 0
fi

# a here-document to pass the cloud-init script
hcloud server create --name "$NAME" --image "$IMAGE" --type "$TYPE" \
                     --ssh-key "$SSH_KEY" --user-data-from-file - <<EOF
#cloud-config
packages:
 - snapd
 - git
 - build-essential
 - tmux
 - tree
users:
  - name: $USER_NAME
    ssh-authorized-keys:
      - $SSH_PUB_KEY
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    groups: sudo
    shell: /bin/bash
runcmd:
  - git clone https://github.com/rericsson/dotfiles.git /home/$USER_NAME/dotfiles
  - chown -R demo:demo /home/demo
  - ln -s /home/$USER_NAME/dotfiles/.vimrc /home/$USER_NAME/.vimrc
  - ln -s /home/$USER_NAME/dotfiles/.tmux.conf /home/$USER_NAME/.tmux.conf
  - sed -i -e '/^#Port/s/^.*$/Port $SSH_PORT/' /etc/ssh/sshd_config
  - systemctl restart sshd
  - ufw allow $SSH_PORT/tcp
  - ufw enable
EOF
hetzner  linux  vim