|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +set -euo pipefail |
| 4 | + |
| 5 | +log() { |
| 6 | + echo "[INFO] $1" |
| 7 | +} |
| 8 | + |
| 9 | +warn() { |
| 10 | + echo "[WARN] $1" |
| 11 | +} |
| 12 | + |
| 13 | +error() { |
| 14 | + echo "[ERROR] $1" |
| 15 | +} |
| 16 | + |
| 17 | +{ |
| 18 | + # Determine admin group |
| 19 | + if getent group sudo > /dev/null; then |
| 20 | + admin_group="sudo" |
| 21 | + elif getent group wheel > /dev/null; then |
| 22 | + admin_group="wheel" |
| 23 | + else |
| 24 | + warn "No suitable admin group (sudo/wheel) found. Skipping ansible user setup." |
| 25 | + exit 0 |
| 26 | + fi |
| 27 | + |
| 28 | + # Create ansible user if it doesn't exist |
| 29 | + if id "ansible" &>/dev/null; then |
| 30 | + log "User 'ansible' already exists. Skipping user creation." |
| 31 | + else |
| 32 | + useradd -m -s /bin/bash -G "$admin_group" ansible || { |
| 33 | + error "Failed to create user 'ansible'." |
| 34 | + exit 0 |
| 35 | + } |
| 36 | + fi |
| 37 | + |
| 38 | + # Configure passwordless sudo |
| 39 | + SUDOERS_FILE="/etc/sudoers.d/ansible" |
| 40 | + SUDOERS_LINE="ansible ALL=(ALL) NOPASSWD:ALL" |
| 41 | + |
| 42 | + if [[ -f "$SUDOERS_FILE" ]] && grep -Fxq "$SUDOERS_LINE" "$SUDOERS_FILE"; then |
| 43 | + log "Passwordless sudo already configured for ansible user." |
| 44 | + else |
| 45 | + echo "$SUDOERS_LINE" > "$SUDOERS_FILE" |
| 46 | + chmod 0440 "$SUDOERS_FILE" |
| 47 | + fi |
| 48 | + |
| 49 | + # Set up SSH key |
| 50 | + SSH_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK6kq0F66kQIEala1jD+V2y5nN0ks6TSdVBPpFEvQOAE" |
| 51 | + SSH_DIR="/home/ansible/.ssh" |
| 52 | + AUTH_KEYS="$SSH_DIR/authorized_keys" |
| 53 | + |
| 54 | + mkdir -p "$SSH_DIR" |
| 55 | + chmod 700 "$SSH_DIR" |
| 56 | + chown -R ansible:ansible "$SSH_DIR" |
| 57 | + |
| 58 | + if [[ -f "$AUTH_KEYS" ]] && grep -q "$SSH_KEY" "$AUTH_KEYS"; then |
| 59 | + log "SSH key already present for ansible user. Skipping." |
| 60 | + else |
| 61 | + echo "$SSH_KEY" >> "$AUTH_KEYS" |
| 62 | + chmod 600 "$AUTH_KEYS" |
| 63 | + chown -R ansible:ansible "$SSH_DIR" |
| 64 | + fi |
| 65 | + chown -R ansible:ansible /home/ansible |
| 66 | + |
| 67 | + log "Ansible user setup completed successfully." |
| 68 | + |
| 69 | +} || { |
| 70 | + warn "An error occurred during ansible user setup. Continuing with instance initialization..." |
| 71 | +} |
0 commit comments