Files
bootstrap-scripts/create-user.sh
2025-07-03 18:26:33 +00:00

58 lines
1.4 KiB
Bash

#!/bin/bash
echo "== Flexible User Creation Script =="
echo
read -p "Username to create (required): " USERNAME
if [[ -z "$USERNAME" ]]; then
echo "Error: Username is required."
exit 1
fi
read -p "Paste the SSH public key: " PUBKEY
if [[ -z "$PUBKEY" ]]; then
echo "Error: Public key is required."
exit 1
fi
read -p "Comma-separated groups to add (e.g. sudo,docker): " GROUPS
# DEBUG LINE
echo "[DEBUG] Raw GROUPS value: '$GROUPS'"
# Create the user if not exists
if id "$USERNAME" &>/dev/null; then
echo "[*] User '$USERNAME' already exists. Skipping creation."
else
echo "[+] Creating user: $USERNAME"
useradd -m -s /bin/bash "$USERNAME"
fi
# Add user to groups if any were entered
if [[ -n "$GROUPS" ]]; then
echo "[+] Adding $USERNAME to groups: $GROUPS"
usermod -aG "$GROUPS" "$USERNAME"
fi
# Setup SSH
SSH_DIR="/home/$USERNAME/.ssh"
AUTHORIZED_KEYS="$SSH_DIR/authorized_keys"
mkdir -p "$SSH_DIR"
touch "$AUTHORIZED_KEYS"
chmod 700 "$SSH_DIR"
chmod 600 "$AUTHORIZED_KEYS"
chown -R "$USERNAME:$USERNAME" "$SSH_DIR"
# Add SSH key if not present
if grep -Fxq "$PUBKEY" "$AUTHORIZED_KEYS"; then
echo "[*] Public key already present. Skipping."
else
echo "$PUBKEY" >> "$AUTHORIZED_KEYS"
echo "[+] Public key added."
fi
echo
echo "[✓] User '$USERNAME' setup complete."
[[ -n "$GROUPS" ]] && echo "[✓] Groups added: $GROUPS"
echo "[✓] SSH access configured."