#!/bin/bash # Reference role names; preserve unrelated hosts entries and Samba configuration. set -euo pipefail : "${ROLE:?}" fqdn="$ROLE.au-team.irpo" hostnamectl --static set-hostname "$fqdn" hostnamectl --transient set-hostname "$fqdn" ROLE="$ROLE" python3 <<'PY' import os from pathlib import Path role = os.environ['ROLE'] fqdn = role + '.au-team.irpo' address = {'isp':'172.16.1.1', 'hq-rtr':'192.168.100.1', 'br-rtr':'192.168.254.0', 'hq-srv':'192.168.100.2', 'br-srv':'192.168.200.2', 'hq-cli':'192.168.100.34'}[role] path = Path('/etc/hosts') lines = path.read_text().splitlines() updated = [] for line in lines: body, marker, comment = line.partition('#') fields = body.split() if len(fields) > 1 and (role in fields[1:] or fqdn in fields[1:]): aliases = [a for a in fields[1:] if a not in (role, fqdn)] # Keep unrelated aliases on their original address. Remove only this # reference role's aliases, then give it a dedicated LAN entry below. if not aliases: if marker: updated.append('#' + comment) continue line = fields[0] + ' ' + ' '.join(aliases) if marker: line += ' #' + comment updated.append(line) updated.append(address + ' ' + fqdn + ' ' + role) path.write_text('\n'.join(updated) + '\n') PY if [[ $ROLE == hq-srv ]] && systemctl is-active --quiet dnsmasq; then # dnsmasq also imports hosts entries; expose only the real LAN address. systemctl restart dnsmasq fi test "$(hostnamectl --static)" = "$fqdn" test "$(hostname -f)" = "$fqdn" hostnamectl --static hostname -f