34 lines
861 B
Bash
34 lines
861 B
Bash
#!/bin/bash
|
|
set -euo pipefail
|
|
|
|
USERNAME="$1"
|
|
SSH_KEY="$2"
|
|
|
|
echo "Creating ansible user: $USERNAME"
|
|
|
|
# --- Create user if not exists
|
|
if ! id "$USERNAME" &>/dev/null; then
|
|
useradd -m "$USERNAME"
|
|
mkdir -p "/home/$USERNAME/.ssh"
|
|
echo "$SSH_KEY" > "/home/$USERNAME/.ssh/authorized_keys"
|
|
chmod 700 "/home/$USERNAME/.ssh"
|
|
chmod 600 "/home/$USERNAME/.ssh/authorized_keys"
|
|
chown -R "$USERNAME:$USERNAME" "/home/$USERNAME/.ssh"
|
|
else
|
|
echo "User $USERNAME already exists, skipping creation"
|
|
fi
|
|
|
|
# --- Harden the ansible user
|
|
|
|
# Disable password (no password login)
|
|
passwd -d "$USERNAME"
|
|
passwd -l "$USERNAME"
|
|
|
|
# Allow full passwordless sudo (needed for playbook tasks)
|
|
cat <<EOF > "/etc/sudoers.d/99_${USERNAME}"
|
|
${USERNAME} ALL=(ALL) NOPASSWD: ALL
|
|
EOF
|
|
chmod 0440 "/etc/sudoers.d/99_${USERNAME}"
|
|
|
|
echo "✅ User $USERNAME hardened for automation-only access"
|