#!/usr/bin/env bash # Local drift detection runner. # Runs terraform plan (all workspaces) and ansible --check, then summarises. # # Usage: # ./scripts/drift-detect.sh # run everything # ./scripts/drift-detect.sh --terraform # terraform only # ./scripts/drift-detect.sh --ansible # ansible only # ./scripts/drift-detect.sh --check-only # alias for full run (no apply) set -euo pipefail REPO_ROOT="$(git rev-parse --show-toplevel)" cd "$REPO_ROOT" RUN_TF=true RUN_ANSIBLE=true for arg in "$@"; do case "$arg" in --terraform) RUN_ANSIBLE=false ;; --ansible) RUN_TF=false ;; --check-only) ;; # default, no-op *) echo "Unknown flag: $arg" >&2; exit 1 ;; esac done DRIFT_FOUND=0 # ── Terraform ────────────────────────────────────────────────────────────────── if [ "$RUN_TF" = true ]; then echo "" echo "━━━ Terraform drift detection ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" for workspace in terraform/proxmox terraform/dns terraform/pihole; do if [ ! -f "${workspace}/providers.tf" ] && [ ! -f "${workspace}/provider.tf" ]; then echo "[SKIP] ${workspace} — no providers.tf found" continue fi echo "" echo "--- ${workspace} ---" ( cd "$workspace" if [ ! -d .terraform ]; then terraform init -input=false -no-color >/dev/null 2>&1 fi set +e terraform plan -detailed-exitcode -input=false -no-color EXIT=$? set -e if [ "$EXIT" -eq 2 ]; then echo "DRIFT: ${workspace} has pending changes" DRIFT_FOUND=1 elif [ "$EXIT" -ne 0 ]; then echo "ERROR in ${workspace} — plan failed (exit ${EXIT})" DRIFT_FOUND=1 fi ) done fi # ── Ansible ──────────────────────────────────────────────────────────────────── if [ "$RUN_ANSIBLE" = true ]; then echo "" echo "━━━ Ansible drift detection (--check --diff) ━━━━━━━━━━━━━━━━━━━━━━━━━━━" ( cd ansible ansible-playbook playbooks/site.yml --check --diff 2>&1 | tee /tmp/ansible-drift.log if grep -q 'changed=' /tmp/ansible-drift.log; then echo "DRIFT: Ansible found pending changes" DRIFT_FOUND=1 fi ) fi # ── Summary ──────────────────────────────────────────────────────────────────── echo "" echo "━━━ Summary ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" if [ "$DRIFT_FOUND" -eq 0 ]; then echo "No drift detected. All infrastructure matches declared state." else echo "Drift detected — review the plan output above." fi exit "$DRIFT_FOUND"