Files
Boilerplates/Ansible/user-anlegen.sh

81 lines
2.5 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/sh
USERNAME="ansible"
SSH_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICBpQgsPoNARIuzw+YTuADA8lk7S3y9wqvPxtDAsdYbw ansible@deploy"
# Farbdefinitionen
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# OS-Erkennung
if [ -f /etc/os-release ]; then
. /etc/os-release
OS_ID=$ID
else
printf "${RED}✗ Kann Betriebssystem nicht erkennen.${NC}\n"
exit 1
fi
# Funktion: Ansible-Benutzer unter RHEL/AlmaLinux/CentOS
setup_rhel() {
printf "${BLUE}→ RHEL/AlmaLinux erkannt Benutzer wird mit useradd erstellt${NC}\n"
sudo useradd -m -s /bin/bash "$USERNAME"
}
# Funktion: Ansible-Benutzer unter Debian/Ubuntu
setup_debian() {
printf "${BLUE}→ Debian/Ubuntu erkannt Benutzer wird mit adduser erstellt${NC}\n"
sudo adduser --disabled-password --gecos "" "$USERNAME"
}
# Funktion: Ansible-Benutzer unter Alpine
setup_alpine() {
printf "${BLUE}→ Alpine Linux erkannt Benutzer wird mit adduser erstellt${NC}\n"
sudo adduser -D -s /bin/sh "$USERNAME"
}
# Hauptlogik
if id "$USERNAME" >/dev/null 2>&1; then
printf "${YELLOW}↷ Benutzer $USERNAME existiert bereits überspringe Erstellung${NC}\n"
else
case "$OS_ID" in
almalinux|centos|rhel|rocky)
setup_rhel
;;
debian|ubuntu)
setup_debian
;;
alpine)
setup_alpine
;;
*)
printf "${RED}✗ Nicht unterstütztes Betriebssystem: $OS_ID${NC}\n"
exit 1
;;
esac
fi
# Benutzer in /etc/shadow entsperren, falls gesperrt (! oder !! im Passwortfeld)
printf "${YELLOW}→ Überprüfe ob Benutzer $USERNAME in /etc/shadow gesperrt ist${NC}\n"
if sudo grep -E "^$USERNAME:(!+|\*+):" /etc/shadow >/dev/null; then
printf "${YELLOW}→ Benutzer ist gesperrt, entsperre für SSH-Key-Login${NC}\n"
sudo sed -i -r "s/^($USERNAME:)(!+|\*+)(:.*)/\1\3/" /etc/shadow
else
printf "${GREEN}→ Benutzer ist nicht gesperrt${NC}\n"
fi
# SSH-Verzeichnis einrichten
sudo mkdir -p /home/$USERNAME/.ssh
echo "$SSH_KEY" | sudo tee /home/$USERNAME/.ssh/authorized_keys > /dev/null
sudo chmod 700 /home/$USERNAME/.ssh
sudo chmod 600 /home/$USERNAME/.ssh/authorized_keys
sudo chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh
# Sudo ohne Passwort erlauben
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/$USERNAME > /dev/null
sudo chmod 440 /etc/sudoers.d/$USERNAME
printf "${GREEN}✓ Benutzer $USERNAME wurde erfolgreich eingerichtet.${NC}\n"