1
0
Fork 0
gnu-plus-dotfiles/run_once_05-install-hosts.sh.tmpl

75 lines
No EOL
2.4 KiB
Bash

#!/usr/bin/env bash
# =============================================================================
# run_once_05-install-hosts.sh.tmpl
# Merge LAN host entries into /etc/hosts so omp / config / curl can
# resolve miche.local, kaiser.local, etc. by name.
#
# Idempotent: re-running this script is safe; it just rewrites the same
# block of LAN entries. Won't touch non-LAN entries.
#
# Skipped on boxes where /etc/hosts is cloud-init managed (e.g. cloud
# VMs) — they need a different strategy (cloud-init module).
# =============================================================================
set -euo pipefail
log() { printf '\033[1;34m[hosts]\033[0m %s\n' "$*"; }
HOSTS_FILE="/etc/hosts"
LAN_BLOCK_BEGIN="# >>> lan-hosts-managed-by-chezmoi >>>"
LAN_BLOCK_END="# <<< lan-hosts-managed-by-chezmoi <<<"
# Skip on cloud-init managed hosts
if [[ -f /etc/cloud/cloud.cfg ]] && grep -q "manage_etc_hosts" /etc/cloud/cloud.cfg; then
log "WARNING: /etc/hosts is cloud-init managed on this box"
log " add LAN host entries to your cloud-init config instead"
exit 0
fi
# LAN host entries to merge. Keep in sync with /etc/hosts on existing
# boxes (miche, kaiser, byte) so all boxes agree.
LAN_ENTRIES=$(cat <<'LAN_HOSTS'
192.168.1.208 tadbit.local
192.168.1.91 byte.local
192.168.1.194 bit.local
192.168.1.103 dayold.local
192.168.1.212 rorclar.local
192.168.1.153 ggbuttz.local
192.168.1.219 bazzite.local
192.168.1.107 crouton.local
192.168.1.215 rye.local
192.168.1.172 miche.local
192.168.1.65 kaiser.local
192.168.1.118 riska.local
LAN_HOSTS
)
# Build the new block
NEW_BLOCK="$LAN_BLOCK_BEGIN
$LAN_ENTRIES
$LAN_BLOCK_END"
# Read current hosts file
if [[ ! -f "$HOSTS_FILE" ]]; then
log "ERROR: $HOSTS_FILE missing — cannot merge LAN entries"
exit 1
fi
# If our block already exists, remove it first (so re-runs don't duplicate)
if grep -q "$LAN_BLOCK_BEGIN" "$HOSTS_FILE"; then
log "removing old LAN block"
sudo cp "$HOSTS_FILE" "${HOSTS_FILE}.bak.$(date +%s)"
sudo sed -i "/$LAN_BLOCK_BEGIN/,/$LAN_BLOCK_END/d" "$HOSTS_FILE"
fi
# Append the new block
log "appending LAN block to $HOSTS_FILE"
echo "" | sudo tee -a "$HOSTS_FILE" >/dev/null
echo "$NEW_BLOCK" | sudo tee -a "$HOSTS_FILE" >/dev/null
echo "" | sudo tee -a "$HOSTS_FILE" >/dev/null
# Verify by checking one of the entries
if grep -q "miche.local" "$HOSTS_FILE"; then
log "verified miche.local is now resolvable"
else
log "WARNING: miche.local not in $HOSTS_FILE after merge"
fi