690 lines
34 KiB
Python
690 lines
34 KiB
Python
#!/usr/bin/env python3
|
|
"""Canonical OCI config, state ownership, and read-only resource discovery.
|
|
|
|
Only the load/save commands write configuration. Discovery never changes OCI.
|
|
Shell output contains quoted assignments only; diagnostics go to stderr.
|
|
"""
|
|
import argparse
|
|
import contextlib
|
|
import fcntl
|
|
import json
|
|
import ipaddress
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
def atomic_write(path, text):
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, temporary = tempfile.mkstemp(prefix="." + path.name, dir=path.parent)
|
|
try:
|
|
with os.fdopen(fd, "w") as output:
|
|
output.write(text)
|
|
os.replace(temporary, path)
|
|
finally:
|
|
if os.path.exists(temporary):
|
|
os.unlink(temporary)
|
|
|
|
|
|
def read_config(path, names):
|
|
"""Read generated assignments as data, including the legacy %q format."""
|
|
values = {}
|
|
if not path.exists():
|
|
return values
|
|
for number, line in enumerate(path.read_text().splitlines(), 1):
|
|
if not line.strip() or line.lstrip().startswith("#"):
|
|
continue
|
|
legacy = re.fullmatch(r': "\$\{(\w+):=(.*)\}"; export \1', line.strip())
|
|
modern = re.fullmatch(r"export (\w+)=(.*)", line.strip())
|
|
match = legacy or modern
|
|
if not match or match[1] not in names:
|
|
raise ValueError(f"Unsupported assignment at {path}:{number}")
|
|
raw = match[2]
|
|
# Old saves wrapped %q in double quotes, accumulating escaped spaces.
|
|
if legacy:
|
|
raw = re.sub(r"\\+(?=\s)", r"\\", raw)
|
|
parts = shlex.split(raw)
|
|
if len(parts) != 1:
|
|
raise ValueError(f"Invalid value at {path}:{number}")
|
|
values[match[1]] = parts[0]
|
|
return values
|
|
|
|
|
|
def emit(values):
|
|
for name, value in sorted(values.items()):
|
|
print(f"export {name}={shlex.quote(str(value))}")
|
|
|
|
|
|
def object_id(item, label):
|
|
identifier = item.get("id") if isinstance(item, dict) else None
|
|
if not isinstance(identifier, str) or not identifier:
|
|
raise ValueError(f"OCI {label} response has no resource identifier")
|
|
return identifier
|
|
|
|
|
|
def config_text(values):
|
|
return "# Generated by Jeannie; canonical OCI foundation configuration.\n" + "".join(
|
|
f"export {key}={shlex.quote(str(value))}\n"
|
|
for key, value in sorted(values.items()) if value != ""
|
|
)
|
|
|
|
|
|
def read_state(path):
|
|
if not path.exists():
|
|
return {}
|
|
data = json.loads(path.read_text())
|
|
if data.get("version") != 4:
|
|
raise ValueError(f"Not a local OpenTofu state: {path}")
|
|
return data
|
|
|
|
|
|
def resources(state):
|
|
result = {}
|
|
for resource in state.get("resources", []):
|
|
if resource.get("mode") != "managed":
|
|
continue
|
|
if resource.get("module"):
|
|
continue
|
|
for instance in resource.get("instances", []):
|
|
if instance.get("deposed"):
|
|
continue
|
|
address = resource["type"] + "." + resource["name"]
|
|
result[address] = instance.get("attributes", {})
|
|
return result
|
|
|
|
|
|
def recorded(values, state):
|
|
"""Keep creation inputs/ownership consistent with this exact state."""
|
|
managed = resources(state)
|
|
mapping = {
|
|
"compartment_id": "LAB_OCI_COMPARTMENT_ID",
|
|
"edge_instance_id": "LAB_OCI_EDGE_INSTANCE_ID",
|
|
"email_instance_id": "LAB_OCI_EMAIL_INSTANCE_ID",
|
|
"edge_public_ip": "LAB_EDGE_HOST", "email_public_ip": "LAB_EMAIL_PUBLIC_IP",
|
|
"bastion_id": "LAB_OCI_BASTION_ID",
|
|
"backup_bucket_id": "LAB_OCI_BACKUP_BUCKET_ID",
|
|
"backup_bucket_name": "LAB_OCI_BACKUP_BUCKET_NAME",
|
|
"backup_bucket_namespace": "LAB_OCI_BACKUP_BUCKET_NAMESPACE",
|
|
"monitoring_topic_id": "LAB_OCI_MONITORING_TOPIC_ID",
|
|
}
|
|
for output, name in mapping.items():
|
|
value = state.get("outputs", {}).get(output, {}).get("value")
|
|
if isinstance(value, str) and value:
|
|
values[name] = value
|
|
for address, output, setting in (
|
|
("oci_core_vcn.homelab", "vcn_id", "LAB_OCI_EXISTING_VCN_ID"),
|
|
("oci_core_subnet.public", "public_subnet_id", "LAB_OCI_EXISTING_PUBLIC_SUBNET_ID"),
|
|
("oci_core_subnet.email", "email_subnet_id", "LAB_OCI_EXISTING_EMAIL_SUBNET_ID"),
|
|
):
|
|
value = state.get("outputs", {}).get(output, {}).get("value")
|
|
if address not in managed and isinstance(value, str) and value.startswith("ocid1."):
|
|
values[setting] = value
|
|
for role in ("homelab", "email"):
|
|
attributes = managed.get("oci_identity_compartment." + role)
|
|
if attributes:
|
|
prefix = "LAB_OCI_" + ("EMAIL_" if role == "email" else "")
|
|
values[prefix + "CREATE_COMPARTMENT"] = "true"
|
|
values[prefix + "COMPARTMENT_ID"] = attributes["id"]
|
|
values[prefix + "COMPARTMENT_NAME"] = attributes["name"]
|
|
vcn = managed.get("oci_core_vcn.homelab")
|
|
if vcn:
|
|
values["LAB_OCI_EXISTING_VCN_ID"] = ""
|
|
values["LAB_OCI_EXISTING_PUBLIC_SUBNET_ID"] = ""
|
|
values["LAB_OCI_COMPARTMENT_ID"] = vcn["compartment_id"]
|
|
cidrs = vcn.get("cidr_blocks") or [vcn.get("cidr_block")]
|
|
if cidrs[0]:
|
|
values["LAB_OCI_VCN_CIDR"] = cidrs[0]
|
|
for role in ("public", "private", "email"):
|
|
subnet = managed.get("oci_core_subnet." + role)
|
|
if subnet:
|
|
values[f"LAB_OCI_{role.upper()}_SUBNET_CIDR"] = subnet["cidr_block"]
|
|
if role == "email":
|
|
values["LAB_OCI_EXISTING_EMAIL_SUBNET_ID"] = ""
|
|
for role in ("edge", "email"):
|
|
vm = managed.get("oci_core_instance." + role)
|
|
if not vm:
|
|
continue
|
|
prefix = f"LAB_OCI_{role.upper()}_"
|
|
values.update({"LAB_OCI_COMPUTE_ENABLED": "true", prefix + "ENABLED": "true",
|
|
prefix + "INSTANCE_ID": vm["id"],
|
|
prefix + "EXISTING_INSTANCE_ID": "",
|
|
prefix + "COMPARTMENT_ID": vm["compartment_id"],
|
|
prefix + "AVAILABILITY_DOMAIN": vm["availability_domain"],
|
|
prefix + "SHAPE": vm["shape"]})
|
|
source = (vm.get("source_details") or [{}])[0]
|
|
if source.get("source_id"):
|
|
values[prefix + "IMAGE_ID"] = source["source_id"]
|
|
if source.get("boot_volume_size_in_gbs"):
|
|
values[prefix + "BOOT_VOLUME_SIZE_IN_GBS"] = str(source["boot_volume_size_in_gbs"])
|
|
if vm.get("public_ip"):
|
|
values["LAB_EDGE_HOST" if role == "edge" else "LAB_EMAIL_PUBLIC_IP"] = vm["public_ip"]
|
|
values["LAB_OCI_EDGE_INSTANCE_MANAGED"] = str("oci_core_instance.edge" in managed).lower()
|
|
values["LAB_OCI_STATE_BASTION_MANAGED"] = str("oci_bastion_bastion.homelab" in managed).lower()
|
|
if "oci_core_nat_gateway.homelab" in managed:
|
|
values["LAB_OCI_NAT_ENABLED"] = "true"
|
|
bastion = managed.get("oci_bastion_bastion.homelab")
|
|
if bastion:
|
|
values["LAB_OCI_BASTION_ENABLED"] = "true"
|
|
# These creation inputs must follow the selected state, not stale
|
|
# scratch-config values merged during migration. A name change forces
|
|
# replacement even when the Bastion OCID/ownership flag is correct.
|
|
values["LAB_OCI_BASTION_ID"] = bastion["id"]
|
|
values["LAB_OCI_BASTION_NAME"] = bastion["name"]
|
|
values["LAB_OCI_BASTION_TARGET_SUBNET_ID"] = bastion["target_subnet_id"]
|
|
for address, setting in (
|
|
("oci_objectstorage_bucket.homelab_backups", "LAB_OCI_BACKUP_BUCKET_COMPARTMENT_ID"),
|
|
("oci_ons_notification_topic.monitoring", "LAB_OCI_MONITORING_TOPIC_COMPARTMENT_ID"),
|
|
):
|
|
if address in managed:
|
|
values[setting] = managed[address]["compartment_id"]
|
|
if "oci_ons_notification_topic.monitoring" in managed:
|
|
values["LAB_OCI_MONITORING_TOPIC_NAME"] = managed["oci_ons_notification_topic.monitoring"]["name"]
|
|
if "oci_objectstorage_bucket.homelab_backups" in managed:
|
|
bucket = managed["oci_objectstorage_bucket.homelab_backups"]
|
|
values.update(LAB_OCI_BACKUP_BUCKET=bucket["name"],
|
|
LAB_OCI_BACKUP_BUCKET_NAME=bucket["name"],
|
|
LAB_OCI_BACKUP_BUCKET_NAMESPACE=bucket["namespace"])
|
|
# State metadata supplies the original key if legacy saves corrupted it.
|
|
vm = managed.get("oci_core_instance.edge", {})
|
|
key = (vm.get("metadata") or {}).get("ssh_authorized_keys")
|
|
if key and "\\" in values.get("LAB_OCI_SSH_PUBLIC_KEY", ""):
|
|
values["LAB_OCI_SSH_PUBLIC_KEY"] = key
|
|
return values
|
|
|
|
|
|
def state_path(values, repo):
|
|
path = Path(values.get("LAB_OCI_FOUNDATION_STATE_FILE") or
|
|
str(repo / "bootstrap/oci/terraform.tfstate")).expanduser()
|
|
if not path.is_absolute():
|
|
path = repo / "bootstrap/oci" / path
|
|
return path.resolve()
|
|
|
|
|
|
def load(args, names):
|
|
canonical = Path.home() / ".config/homelab/oci-foundation.env"
|
|
selected = Path(args.config).expanduser()
|
|
fresh = canonical.with_name("oci-foundation-fresh.env")
|
|
# Remote clients also load the CLI. An unconfigured laptop must not
|
|
# acquire a local foundation config, state pointer, or lock directory.
|
|
if not selected.exists() and not (selected == canonical and fresh.exists()):
|
|
return
|
|
with config_lock(selected):
|
|
values = read_config(selected, names)
|
|
migration = False
|
|
# The fresh stack was explicitly used to replace the original lab.
|
|
# Do not select arbitrary test/scratch state by size or modification time.
|
|
if selected == canonical and not values.get("LAB_OCI_FOUNDATION_STATE_FILE") and fresh.exists():
|
|
alternate = read_config(fresh, names)
|
|
if not alternate.get("LAB_OCI_FOUNDATION_STATE_FILE"):
|
|
raise ValueError("Legacy fresh config has no state path; refusing to guess")
|
|
if not state_path(alternate, args.repo).is_file():
|
|
raise ValueError("Legacy fresh state is missing; refusing a new foundation")
|
|
# Preserve operational features configured only in the old default,
|
|
# but let the selected foundation supply infrastructure identity.
|
|
values.update(alternate)
|
|
migration = True
|
|
# Caller overrides remain available; recorded resource identity/ownership
|
|
# is then authoritative and cannot accidentally turn into count=0.
|
|
values.update({k: os.environ[k] for k in names if os.environ.get(k)})
|
|
path = state_path(values, args.repo)
|
|
if values.get("LAB_OCI_FOUNDATION_STATE_FILE") and not path.is_file() and any(
|
|
values.get(name) for name in ("LAB_OCI_EDGE_INSTANCE_ID", "LAB_OCI_EMAIL_INSTANCE_ID")
|
|
):
|
|
raise ValueError(f"Recorded state is missing: {path}; restore it before continuing")
|
|
state = read_state(path)
|
|
values["LAB_OCI_FOUNDATION_STATE_FILE"] = str(path)
|
|
recorded(values, state)
|
|
if migration:
|
|
backup = canonical.parent / ("oci-foundation-archive-" +
|
|
datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ"))
|
|
backup.mkdir(mode=0o700)
|
|
for source in (canonical, fresh):
|
|
if source.exists():
|
|
shutil.copy2(source, backup / source.name)
|
|
atomic_write(canonical, config_text({k: v for k, v in values.items() if k in names}))
|
|
fresh.rename(backup / "oci-foundation-fresh.env.retired")
|
|
print(f"Reconciled OCI configs into {canonical}; originals archived in {backup}", file=sys.stderr)
|
|
values["LAB_OCI_CONFIG_LOADED"] = "true"
|
|
emit(values)
|
|
print(f"OCI foundation config={selected} state={path}", file=sys.stderr)
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def config_lock(path):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(path.parent / ".oci-foundation-config.lock", "a") as lock:
|
|
os.chmod(lock.name, 0o600)
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
yield
|
|
|
|
|
|
class OCI:
|
|
def __init__(self):
|
|
self.binary = shutil.which("oci") or str(Path.home() / ".local/share/homelab/venvs/oci-cli/bin/oci")
|
|
self.options = []
|
|
for flag, value in (("--profile", os.environ.get("LAB_OCI_CONFIG_PROFILE") or os.environ.get("OCI_CLI_PROFILE")),
|
|
("--region", os.environ.get("LAB_OCI_REGION"))):
|
|
if value:
|
|
self.options += [flag, value]
|
|
self.compartments_cache = None
|
|
|
|
def call(self, *arguments):
|
|
command = [self.binary, *self.options, *arguments, "--output", "json", "--query", "@"]
|
|
label = shlex.join(command)
|
|
is_list = "list" in arguments[:4]
|
|
process = subprocess.run(command,
|
|
capture_output=True, text=True, timeout=90)
|
|
if process.returncode:
|
|
# OCI deliberately conflates missing resources with denied access.
|
|
# A 404 must never switch an entire foundation into create mode.
|
|
raise ValueError(f"{label} failed: {process.stderr[-1800:]}")
|
|
output = process.stdout.strip()
|
|
if not output and is_list:
|
|
# CLI 3.95.1 render() emits nothing for [] with no display headers.
|
|
# Successful list calls are distinct from failed requests or gets.
|
|
return []
|
|
try:
|
|
envelope = json.loads(output)
|
|
except json.JSONDecodeError as error:
|
|
raise ValueError(
|
|
f"{label} returned invalid JSON (exit=0, stdout={len(output)} chars): "
|
|
f"{output[:200]!r}; stderr={process.stderr[-500:]!r}"
|
|
) from error
|
|
if not isinstance(envelope, dict):
|
|
raise ValueError(f"{label} did not return a JSON response object")
|
|
if "data" not in envelope and not (is_list and envelope.get("opc-total-items") == 0):
|
|
raise ValueError(f"{label} returned JSON without data (keys={sorted(envelope)})")
|
|
data = envelope.get("data")
|
|
if is_list:
|
|
if data is None:
|
|
data = []
|
|
if isinstance(data, dict) and isinstance(data.get("items"), list):
|
|
data = data["items"]
|
|
if not isinstance(data, list):
|
|
raise ValueError(f"{label} returned unexpected list data: {type(data).__name__}")
|
|
if arguments[:2] == ("ons", "topic"):
|
|
# Notifications calls this field topicId (topic-id in CLI JSON).
|
|
# Normalize both get and list results before adoption/deduplication.
|
|
rows = data if isinstance(data, list) else [data]
|
|
for row in rows:
|
|
if not isinstance(row, dict):
|
|
raise ValueError("OCI Notifications topic response is not an object")
|
|
row["id"] = row.get("topic-id") or row.get("id")
|
|
object_id(row, "Notifications topic")
|
|
return data
|
|
|
|
def compartments(self):
|
|
if self.compartments_cache is None:
|
|
tenancy = os.environ.get("LAB_OCI_TENANCY_ID", "")
|
|
if not tenancy.startswith("ocid1.tenancy."):
|
|
raise ValueError("A valid LAB_OCI_TENANCY_ID is required")
|
|
rows = self.call("iam", "compartment", "list", "--compartment-id", tenancy,
|
|
"--compartment-id-in-subtree", "true", "--all")
|
|
self.compartments_cache = [tenancy] + [
|
|
x["id"] for x in rows if x.get("lifecycle-state") == "ACTIVE"]
|
|
return self.compartments_cache
|
|
|
|
@staticmethod
|
|
def unique(rows, label):
|
|
by_id = {object_id(row, label): row for row in rows}
|
|
if len(by_id) > 1:
|
|
raise ValueError(f"Ambiguous {label}: {', '.join(by_id)}; select its OCID explicitly")
|
|
return next(iter(by_id.values()), None)
|
|
|
|
def named(self, group, kind, name, compartments=None, extra=()):
|
|
rows = []
|
|
for compartment in compartments or self.compartments():
|
|
data = self.call(group, kind, "list", "--compartment-id", compartment, "--all", *extra)
|
|
rows.extend(x for x in data if (x.get("display-name") or x.get("name")) == name
|
|
and x.get("lifecycle-state", x.get("state")) not in ("TERMINATED", "TERMINATING", "DELETED", "DELETING"))
|
|
return self.unique(rows, name)
|
|
|
|
def instance(self, role):
|
|
prefix = f"LAB_OCI_{role.upper()}_"
|
|
identity = os.environ.get(prefix + "INSTANCE_ID") or os.environ.get(prefix + "EXISTING_INSTANCE_ID")
|
|
name = os.environ.get(prefix + "DISPLAY_NAME", "homelab-edge" if role == "edge" else "homelab-mail")
|
|
if identity:
|
|
try:
|
|
vm = self.call("compute", "instance", "get", "--instance-id", identity)
|
|
if vm.get("lifecycle-state") not in ("TERMINATED", "TERMINATING"):
|
|
return vm
|
|
except ValueError as error:
|
|
if '"status": 404' not in str(error):
|
|
raise
|
|
# A 404 alone proves nothing. Only a complete, successful name
|
|
# lookup can establish whether a replacement is present or absent.
|
|
print(f"Rechecking recorded {role} instance {identity} by exact name", file=sys.stderr)
|
|
return self.named("compute", "instance", name)
|
|
|
|
def vnic(self, vm):
|
|
attachments = self.call("compute", "vnic-attachment", "list",
|
|
"--compartment-id", vm["compartment-id"],
|
|
"--instance-id", vm["id"], "--all")
|
|
vnics = [self.call("network", "vnic", "get", "--vnic-id", x["vnic-id"])
|
|
for x in attachments if x.get("lifecycle-state") == "ATTACHED"]
|
|
primary = [x for x in vnics if x.get("is-primary")]
|
|
vnic = self.unique(primary or vnics, "primary VNIC")
|
|
if not vnic:
|
|
raise ValueError(f"No attached VNIC for {vm['id']}")
|
|
return vnic
|
|
|
|
|
|
def resolve_edge():
|
|
oci = OCI()
|
|
vm = oci.instance("edge")
|
|
if not vm or vm.get("lifecycle-state") != "RUNNING":
|
|
raise ValueError("The managed OCI edge is absent or not RUNNING")
|
|
vnic = oci.vnic(vm)
|
|
if not vnic.get("public-ip"):
|
|
raise ValueError("The edge VNIC has no public IP for DNS")
|
|
values = {"LAB_OCI_EDGE_INSTANCE_ID": vm["id"],
|
|
"LAB_OCI_EDGE_COMPARTMENT_ID": vm["compartment-id"],
|
|
"LAB_OCI_EDGE_PRIVATE_IP": vnic["private-ip"],
|
|
"LAB_EDGE_HOST": vnic["public-ip"], "TF_VAR_edge_host": vnic["public-ip"],
|
|
"TF_VAR_edge_instance_id": vm["id"]}
|
|
transport = os.environ.get("LAB_EDGE_SSH_TRANSPORT", "tailscale")
|
|
if transport == "tailscale":
|
|
# Resolve the tailnet peer by identity, never by a stale inventory IP.
|
|
command = subprocess.run(["tailscale", "status", "--json"], capture_output=True,
|
|
text=True, timeout=15, check=True)
|
|
peers = json.loads(command.stdout).get("Peer", {}).values()
|
|
hostname = os.environ.get("LAB_EDGE_TAILSCALE_HOSTNAME", "homelab-oci-edge")
|
|
matches = [x for x in peers if x.get("HostName") == hostname and x.get("Online")
|
|
and any(ip.startswith("100.") for ip in x.get("TailscaleIPs", []))]
|
|
if len(matches) != 1:
|
|
raise ValueError(f"Expected one online Tailscale peer named {hostname}; found {len(matches)}")
|
|
peer = matches[0]
|
|
ip = next(ip for ip in peer["TailscaleIPs"] if ip.startswith("100."))
|
|
print(f"Using Tailscale peer {hostname} ({ip}) for OCI edge {vm['id']}", file=sys.stderr)
|
|
values.update(LAB_EDGE_TAILSCALE_IP=ip, TF_VAR_edge_ssh_host=ip)
|
|
elif transport == "bastion":
|
|
values["TF_VAR_edge_ssh_host"] = vnic["private-ip"]
|
|
else:
|
|
raise ValueError("LAB_EDGE_SSH_TRANSPORT must be tailscale or bastion")
|
|
emit(values)
|
|
|
|
|
|
def enabled(values, name, default=True):
|
|
return values.get(name, str(default)).lower() in ("true", "1", "yes", "on")
|
|
|
|
|
|
def validate_plan(plan):
|
|
if plan.get("errored"):
|
|
raise ValueError("OpenTofu returned an errored plan")
|
|
destructive = [x["address"] for x in plan.get("resource_changes", [])
|
|
if "delete" in x["change"]["actions"]]
|
|
if destructive:
|
|
raise ValueError("Foundation would delete/replace: " + ", ".join(destructive))
|
|
|
|
|
|
def reconcile(args):
|
|
values = {k: v for k, v in os.environ.items() if k.startswith("LAB_")}
|
|
state = read_state(state_path(values, args.repo))
|
|
managed = resources(state)
|
|
recorded(values, state)
|
|
os.environ.update(values)
|
|
oci = OCI()
|
|
imports = []
|
|
|
|
def adopt(address, item, import_id=None):
|
|
if item and address not in managed:
|
|
identity = import_id or object_id(item, address)
|
|
imports.append({"to": address + "[0]", "id": identity})
|
|
print(f"Adopting existing OCI {address}: {identity}", file=sys.stderr)
|
|
|
|
# Establish each VM's real compartment and subnet from its primary VNIC.
|
|
# Never search a VNIC using the foundation compartment as a substitute.
|
|
vnics = {}
|
|
for role in ("edge", "email"):
|
|
if not enabled(values, f"LAB_OCI_{role.upper()}_ENABLED"):
|
|
continue
|
|
vm = oci.instance(role)
|
|
if not vm:
|
|
values[f"LAB_OCI_{role.upper()}_INSTANCE_ID"] = ""
|
|
values[f"LAB_OCI_{role.upper()}_EXISTING_INSTANCE_ID"] = ""
|
|
continue
|
|
state_vm = managed.get("oci_core_instance." + role)
|
|
if state_vm and state_vm["id"] != vm["id"]:
|
|
raise ValueError(f"State owns {state_vm['id']} but discovery found {vm['id']}; "
|
|
"select the state that owns the replacement before applying")
|
|
prefix = f"LAB_OCI_{role.upper()}_"
|
|
values[prefix + "INSTANCE_ID"] = vm["id"]
|
|
values[prefix + "COMPARTMENT_ID"] = vm["compartment-id"]
|
|
if "oci_core_instance." + role not in managed:
|
|
values[prefix + "EXISTING_INSTANCE_ID"] = vm["id"]
|
|
vnic = oci.vnic(vm)
|
|
vnics[role] = vnic
|
|
values["LAB_EDGE_HOST" if role == "edge" else "LAB_EMAIL_PUBLIC_IP"] = vnic.get("public-ip") or ""
|
|
if role == "edge":
|
|
values["LAB_OCI_EDGE_PRIVATE_IP"] = vnic["private-ip"]
|
|
if "oci_core_vcn.homelab" in managed:
|
|
subnet = oci.call("network", "subnet", "get", "--subnet-id", vnic["subnet-id"])
|
|
if subnet["vcn-id"] != managed["oci_core_vcn.homelab"]["id"]:
|
|
raise ValueError(f"{role} VM belongs to another VCN; refusing to mix foundations")
|
|
# A surviving VM supplies the network identity even if local state was lost.
|
|
if "oci_core_vcn.homelab" not in managed:
|
|
vcn_id = values.get("LAB_OCI_EXISTING_VCN_ID")
|
|
public_id = values.get("LAB_OCI_EXISTING_PUBLIC_SUBNET_ID")
|
|
if "edge" in vnics:
|
|
public_id = vnics["edge"]["subnet-id"]
|
|
if public_id:
|
|
public = oci.call("network", "subnet", "get", "--subnet-id", public_id)
|
|
vcn_id = public["vcn-id"]
|
|
elif not vcn_id:
|
|
found = oci.named("network", "vcn", values.get("LAB_OCI_VCN_DISPLAY_NAME", "homelab-vcn"))
|
|
vcn_id = found["id"] if found else None
|
|
if vcn_id:
|
|
vcn = oci.call("network", "vcn", "get", "--vcn-id", vcn_id)
|
|
values["LAB_OCI_EXISTING_VCN_ID"] = vcn_id
|
|
values["LAB_OCI_COMPARTMENT_ID"] = vcn["compartment-id"]
|
|
if not public_id:
|
|
public = oci.named("network", "subnet", "homelab-public-subnet",
|
|
[vcn["compartment-id"]], ("--vcn-id", vcn_id))
|
|
if not public:
|
|
raise ValueError("Existing VCN has no unique public subnet")
|
|
public_id = public["id"]
|
|
values["LAB_OCI_EXISTING_PUBLIC_SUBNET_ID"] = public_id
|
|
else:
|
|
vcn_id = managed["oci_core_vcn.homelab"]["id"]
|
|
# Verify the recorded network before allowing any new children.
|
|
oci.call("network", "vcn", "get", "--vcn-id", vcn_id)
|
|
if vcn_id:
|
|
vcn = oci.call("network", "vcn", "get", "--vcn-id", vcn_id)
|
|
cidr = (vcn.get("cidr-blocks") or [vcn.get("cidr-block")])[0]
|
|
if "oci_core_subnet.email" not in managed and not values.get("LAB_OCI_EXISTING_EMAIL_SUBNET_ID"):
|
|
requested = values.get("LAB_OCI_EMAIL_SUBNET_CIDR", "")
|
|
if not requested or not ipaddress.ip_network(requested).subnet_of(ipaddress.ip_network(cidr)):
|
|
# Validate allocation against all existing subnets before creating.
|
|
rows = oci.call("network", "subnet", "list",
|
|
"--compartment-id", vcn["compartment-id"], "--vcn-id", vcn_id, "--all")
|
|
occupied = [ipaddress.ip_network(x["cidr-block"]) for x in rows]
|
|
available = next((x for x in ipaddress.ip_network(cidr).subnets(new_prefix=24)
|
|
if not any(x.overlaps(y) for y in occupied)), None)
|
|
if available is None:
|
|
raise ValueError(f"No free /24 in VCN {vcn_id}")
|
|
values["LAB_OCI_EMAIL_SUBNET_CIDR"] = str(available)
|
|
public_id = values.get("LAB_OCI_EXISTING_PUBLIC_SUBNET_ID")
|
|
if public_id:
|
|
public = oci.call("network", "subnet", "get", "--subnet-id", public_id)
|
|
values["LAB_OCI_BASTION_SSH_SOURCE_CIDR"] = public["cidr-block"]
|
|
for role in ("homelab", "email"):
|
|
prefix = "LAB_OCI_" + ("EMAIL_" if role == "email" else "")
|
|
if role == "email" and not enabled(values, "LAB_OCI_EMAIL_ENABLED"):
|
|
continue
|
|
identity = values.get(prefix + "COMPARTMENT_ID")
|
|
if identity:
|
|
oci.call("iam", "compartment", "get", "--compartment-id", identity)
|
|
else:
|
|
name = values.get(prefix + "COMPARTMENT_NAME",
|
|
"homelab-learning" if role == "homelab" else "homelab-email")
|
|
rows = oci.call("iam", "compartment", "list",
|
|
"--compartment-id", values["LAB_OCI_TENANCY_ID"],
|
|
"--compartment-id-in-subtree", "true", "--all")
|
|
found = oci.unique([x for x in rows if x.get("name") == name
|
|
and x.get("lifecycle-state") == "ACTIVE"], name)
|
|
if found:
|
|
identity = found["id"]
|
|
values[prefix + "COMPARTMENT_ID"] = identity
|
|
if identity and "oci_identity_compartment." + role not in managed:
|
|
values[prefix + "CREATE_COMPARTMENT"] = "false"
|
|
compartment = values.get("LAB_OCI_COMPARTMENT_ID")
|
|
if "email" in vnics and "oci_core_subnet.email" not in managed:
|
|
values["LAB_OCI_EXISTING_EMAIL_SUBNET_ID"] = vnics["email"]["subnet-id"]
|
|
elif vcn_id and "oci_core_subnet.email" not in managed and enabled(values, "LAB_OCI_EMAIL_ENABLED"):
|
|
found = oci.named("network", "subnet", "homelab-email-subnet",
|
|
[compartment], ("--vcn-id", vcn_id))
|
|
if found:
|
|
values["LAB_OCI_EXISTING_EMAIL_SUBNET_ID"] = found["id"]
|
|
# Reuse only exact named resources within the resolved VCN/compartment.
|
|
for role in ("edge", "email"):
|
|
if not vcn_id or not enabled(values, f"LAB_OCI_{role.upper()}_ENABLED"):
|
|
continue
|
|
address = "oci_core_network_security_group." + role
|
|
owner = values.get("LAB_OCI_EMAIL_COMPARTMENT_ID", compartment) if role == "email" else compartment
|
|
item = managed.get(address)
|
|
if not item:
|
|
item = oci.named("network", "nsg", f"homelab-{role}-nsg", [owner], ("--vcn-id", vcn_id))
|
|
adopt(address, item)
|
|
if not item:
|
|
continue
|
|
nsg_id = item["id"]
|
|
rules = oci.call("network", "nsg", "rules", "list", "--nsg-id", nsg_id, "--all")
|
|
desired = {"ssh": (22, values["LAB_OCI_ADMIN_CIDR"])}
|
|
if role == "edge":
|
|
desired.update(web=(80, "0.0.0.0/0"), https=(443, "0.0.0.0/0"))
|
|
if values.get("LAB_OCI_EDGE_TAILNET_SSH_CIDR"):
|
|
desired["tailnet_ssh"] = (22, values["LAB_OCI_EDGE_TAILNET_SSH_CIDR"])
|
|
if enabled(values, "LAB_OCI_MONITORING_ENABLED"):
|
|
desired["monitoring"] = (9100, values.get("LAB_OCI_MONITORING_CIDR") or values["LAB_OCI_ADMIN_CIDR"])
|
|
if role == "edge":
|
|
desired["container_monitoring"] = (9101, desired["monitoring"][1])
|
|
if enabled(values, "LAB_OCI_BASTION_ENABLED"):
|
|
cidr = values.get("LAB_OCI_BASTION_SSH_SOURCE_CIDR") or values.get("LAB_OCI_PUBLIC_SUBNET_CIDR", "10.50.10.0/24")
|
|
desired["bastion_ssh"] = (22, cidr)
|
|
if role == "email" and enabled(values, "LAB_OCI_OPEN_MAIL_PORTS", False):
|
|
desired.update(ports=(25, "0.0.0.0/0"), submission=(465, "0.0.0.0/0"),
|
|
submission_starttls=(587, "0.0.0.0/0"), imaps=(993, "0.0.0.0/0"))
|
|
used = set()
|
|
for suffix, (port, source) in desired.items():
|
|
address = f"oci_core_network_security_group_security_rule.{role}_{suffix}"
|
|
if address in managed:
|
|
continue
|
|
matches = []
|
|
for rule in rules:
|
|
tcp = rule.get("tcp-options") or rule.get("tcpOptions") or {}
|
|
ports = tcp.get("destination-port-range") or tcp.get("destinationPortRange") or {}
|
|
if (rule.get("direction") == "INGRESS" and str(rule.get("protocol")) == "6"
|
|
and rule.get("source") == source
|
|
and not rule.get("is-stateless", rule.get("isStateless", False))
|
|
and ports.get("min") == port and ports.get("max") == port):
|
|
matches.append(rule)
|
|
found = oci.unique(matches, address)
|
|
if found and found["id"] not in used:
|
|
adopt(address, found, f"networkSecurityGroups/{nsg_id}/securityRules/{found['id']}")
|
|
used.add(found["id"])
|
|
if enabled(values, "LAB_OCI_BASTION_ENABLED") and "oci_bastion_bastion.homelab" not in managed:
|
|
identity = values.get("LAB_OCI_BASTION_ID")
|
|
item = oci.call("bastion", "bastion", "get", "--bastion-id", identity) if identity else (
|
|
oci.named("bastion", "bastion", values.get("LAB_OCI_BASTION_NAME", "homelab-bastion")))
|
|
if item:
|
|
if item.get("lifecycle-state") != "ACTIVE":
|
|
raise ValueError("Recorded Bastion is not ACTIVE")
|
|
values["LAB_OCI_BASTION_ID"] = item["id"]
|
|
values["LAB_OCI_BASTION_TARGET_SUBNET_ID"] = item["target-subnet-id"]
|
|
if enabled(values, "LAB_OCI_BACKUP_BUCKET_ENABLED"):
|
|
address = "oci_objectstorage_bucket.homelab_backups"
|
|
if address not in managed:
|
|
namespace = values.get("LAB_OCI_BACKUP_BUCKET_NAMESPACE") or oci.call("os", "ns", "get")
|
|
bucket = values.get("LAB_OCI_BACKUP_BUCKET_NAME") or values.get("LAB_OCI_BACKUP_BUCKET", "homelab-backups")
|
|
if values.get("LAB_OCI_BACKUP_BUCKET_ID"):
|
|
match = oci.call("os", "bucket", "get", "--namespace-name", namespace, "--bucket-name", bucket)
|
|
else:
|
|
rows = []
|
|
for owner in oci.compartments():
|
|
rows.extend(oci.call("os", "bucket", "list", "--namespace-name", namespace,
|
|
"--compartment-id", owner, "--all"))
|
|
match = next((x for x in rows if x["name"] == bucket), None)
|
|
if match:
|
|
identity = f"n/{namespace}/b/{bucket}"
|
|
adopt(address, {"id": identity})
|
|
values.update(LAB_OCI_BACKUP_BUCKET_ID=identity, LAB_OCI_BACKUP_BUCKET_NAMESPACE=namespace,
|
|
LAB_OCI_BACKUP_BUCKET_COMPARTMENT_ID=match["compartment-id"])
|
|
address = "oci_identity_policy.object_storage_lifecycle"
|
|
if address not in managed:
|
|
found = oci.named("iam", "policy", "jeannie-object-storage-lifecycle",
|
|
[values["LAB_OCI_TENANCY_ID"]])
|
|
adopt(address, found)
|
|
if enabled(values, "LAB_OCI_MONITORING_ENABLED") and enabled(values, "LAB_OCI_MONITORING_ALARMS_ENABLED"):
|
|
address = "oci_ons_notification_topic.monitoring"
|
|
if address not in managed and compartment:
|
|
topic_id = values.get("LAB_OCI_MONITORING_TOPIC_ID")
|
|
found = oci.call("ons", "topic", "get", "--topic-id", topic_id) if topic_id else (
|
|
oci.named("ons", "topic", values.get("LAB_OCI_MONITORING_TOPIC_NAME", "homelab-monitoring")))
|
|
adopt(address, found)
|
|
if found:
|
|
values["LAB_OCI_MONITORING_TOPIC_COMPARTMENT_ID"] = found["compartment-id"]
|
|
values["LAB_OCI_MONITORING_TOPIC_NAME"] = found["name"]
|
|
for role in ("edge", "email"):
|
|
if not values.get(f"LAB_OCI_{role.upper()}_INSTANCE_ID"):
|
|
continue
|
|
owner = values.get(f"LAB_OCI_{role.upper()}_COMPARTMENT_ID") or compartment
|
|
for suffix, label in (("cpu_high", "cpu-high"), ("unavailable", "unavailable")):
|
|
address = f"oci_monitoring_alarm.{role}_{suffix}"
|
|
if address not in managed:
|
|
found = oci.named("monitoring", "alarm", f"homelab-{role}-{label}", [owner])
|
|
adopt(address, found)
|
|
# Import declarations are previewed in plan; they do not mutate state here.
|
|
atomic_write(args.repo / "bootstrap/oci/jeannie-imports.tf", "".join(
|
|
"import {\n to = " + item["to"] + "\n id = " + json.dumps(item["id"]) + "\n}\n"
|
|
for item in imports))
|
|
emit({k: v for k, v in values.items() if k.startswith("LAB_")})
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("load", "save", "reconcile", "edge", "discover", "check-plan"))
|
|
parser.add_argument("--config", type=Path, default=Path.home() / ".config/homelab/oci-foundation.env")
|
|
parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1])
|
|
parser.add_argument("--names", nargs="*", default=[])
|
|
parser.add_argument("--plan", type=Path)
|
|
parser.add_argument("--kind", choices=("instance", "vcn", "bastion"))
|
|
parser.add_argument("--name")
|
|
parser.add_argument("--root")
|
|
args = parser.parse_args()
|
|
names = set(args.names)
|
|
if args.action == "load":
|
|
load(args, names)
|
|
elif args.action == "save":
|
|
with config_lock(args.config):
|
|
atomic_write(args.config, config_text({k: os.environ.get(k, "") for k in names}))
|
|
elif args.action == "edge":
|
|
resolve_edge()
|
|
elif args.action == "reconcile":
|
|
reconcile(args)
|
|
elif args.action == "discover":
|
|
os.environ["LAB_OCI_TENANCY_ID"] = args.root
|
|
group, kind = {"instance": ("compute", "instance"), "vcn": ("network", "vcn"),
|
|
"bastion": ("bastion", "bastion")}[args.kind]
|
|
found = OCI().named(group, kind, args.name)
|
|
if found:
|
|
print(found["id"])
|
|
else:
|
|
sys.exit(1)
|
|
else:
|
|
validate_plan(json.loads(args.plan.read_text()))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (ValueError, OSError, subprocess.SubprocessError) as error:
|
|
print(f"OCI reconciliation failed: {error}", file=sys.stderr)
|
|
sys.exit(1)
|