Reconcile canonical OCI state and make edge discovery repeatable

This commit is contained in:
juvenal.diaz 2026-10-29 14:13:41 -06:00
parent 6ee4f65a49
commit 0f276c02ec
13 changed files with 989 additions and 684 deletions

2
.gitignore vendored
View File

@ -50,3 +50,5 @@ __pycache__/
# Tofu state backups
*.tfstate.*.backup
*.tfstate.bak*
bootstrap/oci/jeannie-imports.tf
bootstrap/oci/.jeannie-foundation.lock

View File

@ -93,6 +93,7 @@ locals {
resource "null_resource" "edge_services" {
triggers = {
instance_id = var.edge_instance_id
host = var.edge_host
user = var.edge_user
install_dir = var.edge_install_dir

View File

@ -1,3 +1,9 @@
variable "edge_instance_id" {
description = "Resolved OCI identity; re-provision a replacement even if it reuses the public IP."
type = string
default = ""
}
variable "edge_host" {
type = string
default = ""

View File

@ -15,6 +15,54 @@ The foundation plan/apply path installs OCI CLI into
`LAB_OCI_CLI_AUTO_INSTALL=false` to disable that behavior, or install it
explicitly with `./jeannie oci-auth install`.
Jeannie uses `~/.config/homelab/oci-foundation.env` as the canonical
configuration for foundation and edge. If that file has no state pointer and
`oci-foundation-fresh.env` is present, the resolver merges its infrastructure
inputs into the canonical file, preserves backup/monitoring settings, and uses
the exact state file recorded by the fresh configuration. Both original configs
are backed up in an `oci-foundation-archive-*` directory; the fresh config is
retired there. State files are never merged, copied over each other, or selected
by modification time. Explicit `LAB_OCI_FOUNDATION_CONFIG_FILE` overrides remain
available for intentionally separate test stacks.
The resolver reads generated configs as data and writes shell-quoted values
atomically with mode 0600. It repairs the legacy SSH-key escaping and uses exact
resource addresses in state to preserve managed VM, network, and Bastion
ownership. Managed VMs keep compute enabled; the normal foundation workflow
cannot disable/destroy them through an accidentally persisted flag.
Before each plan/apply, read-only OCI lookups validate recorded instance IDs
and resolve VNICs using each instance's real compartment. Discovery uses exact
names and scopes and refuses ambiguous matches or authorization failures.
Surviving VMs supply their VCN/subnet identity when state is missing.
Already-created NSGs, matching rules, backup buckets, lifecycle policies,
monitoring topics, and alarms are adopted using generated import declarations
in `bootstrap/oci/jeannie-imports.tf`. Imports are visible in the plan and enter
state only during apply. Ordinary apply executes the saved, checked plan and
refuses any resource deletion or replacement. `destroy --yes` remains a separate,
explicit operation.
From Debian, validate a migration without applying infrastructure changes:
```bash
./jeannie oci-foundation verify
./jeannie oci-foundation plan
```
Review imports and additions in the complete plan. A second successful apply
should produce no further imports or infrastructure changes. The offline
regressions use temporary files and mocks; they never contact OCI or SSH.
Edge deployment defaults to `LAB_EDGE_SSH_TRANSPORT=tailscale`. It resolves the
recorded OCI VM and its public address for DNS, then finds the single online
Tailscale peer named `homelab-oci-edge` for SSH. Override the peer name with
`LAB_EDGE_TAILSCALE_HOSTNAME`. `LAB_EDGE_SSH_TRANSPORT=bastion` selects the
existing Bastion workflow explicitly. A missing/offline tailnet peer fails before
provisioning; a first boot without Tailscale needs the Bastion transport.
SSH uses a single bounded authentication check and preserves known host keys.
Routine applies no longer restart caches; use `./jeannie edge-cache-flush`
when a cache reset is intended.
Prepare the config with `./jeannie oci-auth init`. The command creates the
private key locally, prints the public key for the one-time OCI user upload,
and writes the config with restrictive permissions. It never sends the private

View File

@ -4,9 +4,9 @@ locals {
network_vcn_id = trimspace(var.existing_vcn_id) != "" ? var.existing_vcn_id : oci_core_vcn.homelab[0].id
public_subnet_id = trimspace(var.existing_public_subnet_id) != "" ? var.existing_public_subnet_id : oci_core_subnet.public[0].id
email_subnet_id = trimspace(var.existing_email_subnet_id) != "" ? var.existing_email_subnet_id : oci_core_subnet.email[0].id
# The persisted default (10.0.2.0/24) may belong to an older VCN. When
# attaching to an existing VCN, derive a deterministic /24 inside it.
email_subnet_cidr = trimspace(var.existing_vcn_id) != "" ? cidrsubnet(data.oci_core_vcn.existing[0].cidr_blocks[0], 8, 2) : cidrsubnet(var.vcn_cidr, 8, 2)
# The resolver preserves the managed subnet's CIDR and validates new
# allocations against the resolved VCN before invoking OpenTofu.
email_subnet_cidr = var.email_subnet_cidr
email_route_table_id = trimspace(var.existing_vcn_id) != "" ? data.oci_core_subnet.existing_public[0].route_table_id : local.public_route_table_id
bastion_target_subnet_id = trimspace(var.bastion_target_subnet_id) != "" ? var.bastion_target_subnet_id : local.public_subnet_id
bastion_client_cidrs = length(var.bastion_client_cidr_block_allow_list) > 0 ? var.bastion_client_cidr_block_allow_list : [var.admin_cidr]
@ -47,7 +47,7 @@ data "oci_objectstorage_namespace" "homelab" {
resource "oci_objectstorage_bucket" "homelab_backups" {
count = var.enabled && var.backup_bucket_enabled ? 1 : 0
compartment_id = local.target_compartment_id
compartment_id = trimspace(var.backup_bucket_compartment_id) != "" ? var.backup_bucket_compartment_id : local.target_compartment_id
namespace = trimspace(var.backup_bucket_namespace) != "" ? var.backup_bucket_namespace : data.oci_objectstorage_namespace.homelab[0].namespace
name = var.backup_bucket_name
access_type = "NoPublicAccess"
@ -64,7 +64,7 @@ resource "oci_objectstorage_bucket" "homelab_backups" {
resource "oci_ons_notification_topic" "monitoring" {
count = var.enabled && var.monitoring_enabled && var.monitoring_alarms_enabled ? 1 : 0
compartment_id = local.target_compartment_id
compartment_id = trimspace(var.monitoring_topic_compartment_id) != "" ? var.monitoring_topic_compartment_id : local.target_compartment_id
name = var.monitoring_topic_name
description = "Jeannie OCI VM monitoring alarms"
freeform_tags = local.base_tags
@ -85,7 +85,7 @@ resource "oci_identity_policy" "object_storage_lifecycle" {
name = "jeannie-object-storage-lifecycle"
description = "Allow OCI Object Storage to execute Jeannie backup lifecycle rules"
statements = [
"Allow service objectstorage-${var.region} to manage object-family in compartment ${var.compartment_name}",
"Allow service objectstorage-${var.region} to manage object-family in compartment id ${trimspace(var.backup_bucket_compartment_id) != "" ? var.backup_bucket_compartment_id : local.target_compartment_id}",
]
freeform_tags = local.base_tags
}

View File

@ -148,6 +148,18 @@ variable "monitoring_topic_name" {
default = "homelab-monitoring"
}
variable "monitoring_topic_compartment_id" {
description = "Preserve the owner compartment of an adopted monitoring topic."
type = string
default = ""
}
variable "backup_bucket_compartment_id" {
description = "Preserve the owner compartment of an adopted backup bucket."
type = string
default = ""
}
variable "monitoring_notification_email" {
description = "Optional email subscription for OCI VM alarms; OCI requires confirmation before delivery."
type = string

View File

@ -133,7 +133,7 @@ Observability And GitOps
edge Deploy/check the OCI edge stack only.
email-vm {status|plan|apply|setup|status-server|destroy --yes}
Manage the OCI email VM and its mail-server baseline.
oci-foundation {status|plan|apply|destroy --yes}
oci-foundation {verify|status|plan|apply|destroy --yes}
Create the opt-in OCI compartment, network, edge VM, and email VM.
oci-auth {install|init [--force]|check} Install/check OCI CLI and API-key authentication on Debian.
oci {status|doctor|bastion ssh [--print-command]|cleanup}

View File

@ -3686,6 +3686,9 @@ gitops_manage() {
state_status() {
require_debian_server "state status"
if [[ "${1:-}" == "oci" || "${1:-}" == "bootstrap/oci" ]]; then
oci_foundation_export_inputs
fi
"${REPO_ROOT}/scripts/state-status" "$@"
}
@ -3759,6 +3762,12 @@ oci_foundation_config_names=(
LAB_OCI_SSH_PUBLIC_KEY LAB_OCI_SSH_PRIVATE_KEY LAB_EDGE_SSH_KEY_PATH LAB_OCI_CREATE_COMPARTMENT LAB_OCI_COMPARTMENT_ID LAB_OCI_COMPARTMENT_NAME
LAB_OCI_EDGE_ENABLED LAB_OCI_EMAIL_ENABLED LAB_OCI_COMPUTE_ENABLED LAB_OCI_NAT_ENABLED LAB_OCI_EDGE_EXISTING_INSTANCE_ID LAB_OCI_EMAIL_EXISTING_INSTANCE_ID
LAB_OCI_EXISTING_VCN_ID LAB_OCI_EXISTING_PUBLIC_SUBNET_ID LAB_OCI_EXISTING_EMAIL_SUBNET_ID
LAB_OCI_VCN_CIDR LAB_OCI_PUBLIC_SUBNET_CIDR LAB_OCI_PRIVATE_SUBNET_CIDR
LAB_OCI_EDGE_IMAGE_ID LAB_OCI_EMAIL_IMAGE_ID LAB_OCI_EDGE_SHAPE LAB_OCI_EMAIL_SHAPE
LAB_OCI_EDGE_BOOT_VOLUME_SIZE_IN_GBS LAB_OCI_EMAIL_BOOT_VOLUME_SIZE_IN_GBS
LAB_OCI_BACKUP_BUCKET_COMPARTMENT_ID LAB_OCI_MONITORING_TOPIC_COMPARTMENT_ID
LAB_OCI_CONFIG_PROFILE
LAB_EDGE_SSH_TRANSPORT LAB_EDGE_TAILSCALE_HOSTNAME LAB_EDGE_SSH_PREFLIGHT_SECONDS
LAB_OCI_EMAIL_CREATE_COMPARTMENT LAB_OCI_EMAIL_COMPARTMENT_ID LAB_OCI_EMAIL_COMPARTMENT_NAME
LAB_OCI_EMAIL_SUBNET_CIDR LAB_OCI_EDGE_AVAILABILITY_DOMAIN LAB_OCI_EMAIL_AVAILABILITY_DOMAIN
LAB_OCI_OPEN_MAIL_PORTS LAB_OCI_AUTO_CONFIGURE_EDGE LAB_EDGE_HOST LAB_EDGE_TAILSCALE_IP
@ -3776,352 +3785,39 @@ oci_foundation_config_file() {
}
oci_foundation_load_config() {
local file canonical config_dir candidate candidate_state
canonical="${HOME}/.config/homelab/oci-foundation.env"
file="$(oci_foundation_config_file)"
# Keep one canonical config path. Older runs could leave a separate
# *-fresh.env containing the only valid state-file pointer; adopt that
# file as the input source and save the normalized values back to the
# canonical path after reconciliation. An explicitly selected config
# remains authoritative for deliberate side-by-side test stacks.
if [[ -z "${LAB_OCI_FOUNDATION_CONFIG_FILE:-}" && "${file}" == "${canonical}" ]]; then
config_dir="$(dirname "${canonical}")"
candidate_state=""
if [[ -r "${file}" ]]; then
candidate_state="$(
unset LAB_OCI_FOUNDATION_STATE_FILE
# shellcheck disable=SC1090
source "${file}"
printf '%s' "${LAB_OCI_FOUNDATION_STATE_FILE:-}"
) 2>/dev/null)"
fi
if [[ -z "${candidate_state}" || ! -f "${candidate_state}" ]]; then
for candidate in "${config_dir}/oci-foundation-fresh.env" "${config_dir}"/oci-foundation-*.env; do
[[ -r "${candidate}" && "${candidate}" != "${file}" ]] || continue
candidate_state="$(
unset LAB_OCI_FOUNDATION_STATE_FILE
# shellcheck disable=SC1090
source "${candidate}"
printf '%s' "${LAB_OCI_FOUNDATION_STATE_FILE:-}"
) 2>/dev/null)"
if [[ -n "${candidate_state}" && -f "${candidate_state}" ]]; then
file="${candidate}"
export LAB_OCI_FOUNDATION_CONFIG_FILE="${canonical}"
printf 'Adopting OCI foundation config %s as canonical input.\n' "${candidate}" >&2
break
fi
done
fi
fi
[[ -r "${file}" ]] || return 0
# The file contains only generated parameter-assignment lines using shell
# quoting; each assignment preserves an explicitly supplied environment value.
# shellcheck disable=SC1090
source "${file}"
[[ "${LAB_OCI_CONFIG_LOADED:-false}" == "true" ]] && return 0
local resolved
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" load \
--config "$(oci_foundation_config_file)" --repo "${REPO_ROOT}" \
--names "${oci_foundation_config_names[@]}")" || return 1
# The resolver emits quoted assignments, never file-provided code.
eval "${resolved}"
}
oci_foundation_save_config() {
local file name value
file="$(oci_foundation_config_file)"
mkdir -p "$(dirname "${file}")"
umask 077
{
printf '%s\n' '# Generated by Jeannie; local OCI foundation inputs.'
for name in "${oci_foundation_config_names[@]}"; do
value="${!name:-}"
[[ -n "${value}" ]] || continue
printf ': "${%s:=%q}"; export %s\n' "${name}" "${value}" "${name}"
done
} >"${file}"
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" save \
--config "$(oci_foundation_config_file)" --repo "${REPO_ROOT}" \
--names "${oci_foundation_config_names[@]}"
}
oci_foundation_reconcile_existing() {
local oci_bin="" output_file status compartment_id compartment_name
local homelab_state_file="${LAB_OCI_FOUNDATION_STATE_FILE:-${REPO_ROOT}/bootstrap/oci/terraform.tfstate}"
local homelab_compartment_managed=false
local network_state_managed=false
local edge_state_managed=false
local email_state_managed=false
if [[ -f "${homelab_state_file}" ]] && grep -q '"type"[[:space:]]*:[[:space:]]*"oci_identity_compartment"' "${homelab_state_file}"; then
homelab_compartment_managed=true
fi
if [[ -f "${homelab_state_file}" ]] && grep -q '"type"[[:space:]]*:[[:space:]]*"oci_core_vcn"' "${homelab_state_file}"; then
network_state_managed=true
fi
if [[ -f "${homelab_state_file}" ]] && grep -q '"type"[[:space:]]*:[[:space:]]*"oci_core_instance"' "${homelab_state_file}" && grep -q '"name"[[:space:]]*:[[:space:]]*"edge"' "${homelab_state_file}"; then
edge_state_managed=true
fi
if [[ -f "${homelab_state_file}" ]] && grep -q '"type"[[:space:]]*:[[:space:]]*"oci_core_instance"' "${homelab_state_file}" && grep -q '"name"[[:space:]]*:[[:space:]]*"email"' "${homelab_state_file}"; then
email_state_managed=true
fi
if command -v oci >/dev/null 2>&1; then
oci_bin="$(command -v oci)"
elif [[ -x "${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci" ]]; then
oci_bin="${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci"
else
echo "OCI foundation discovery requires the OCI CLI; refusing to plan without it." >&2
return 1
fi
local resolved
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" reconcile \
--repo "${REPO_ROOT}")" || return 1
eval "${resolved}"
}
# Prefer OCIDs recorded by a prior Jeannie/OpenTofu run. Listing VCNs is
# not available to every OCI identity, while state outputs remain the
# authoritative handoff between foundation and dependent services.
if command -v tofu >/dev/null 2>&1 && [[ -f "${homelab_state_file}" ]]; then
local recovered_output
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw vcn_id 2>/dev/null || true)"
[[ "${recovered_output}" == ocid1.vcn.* && -z "${LAB_OCI_EXISTING_VCN_ID:-}" ]] && export LAB_OCI_EXISTING_VCN_ID="${recovered_output}"
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw public_subnet_id 2>/dev/null || true)"
[[ "${recovered_output}" == ocid1.subnet.* && -z "${LAB_OCI_EXISTING_PUBLIC_SUBNET_ID:-}" ]] && export LAB_OCI_EXISTING_PUBLIC_SUBNET_ID="${recovered_output}"
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw email_subnet_id 2>/dev/null || true)"
[[ "${recovered_output}" == ocid1.subnet.* && -z "${LAB_OCI_EXISTING_EMAIL_SUBNET_ID:-}" ]] && export LAB_OCI_EXISTING_EMAIL_SUBNET_ID="${recovered_output}"
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw compartment_id 2>/dev/null || true)"
[[ "${recovered_output}" == ocid1.compartment.* && -z "${LAB_OCI_COMPARTMENT_ID:-}" ]] && export LAB_OCI_COMPARTMENT_ID="${recovered_output}"
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw edge_instance_id 2>/dev/null || true)"
# A resource still present in this state must remain managed by its
# resource block. Setting *_EXISTING_INSTANCE_ID for it changes the
# count to zero and makes OpenTofu plan a destructive replacement.
if [[ "${edge_state_managed}" != "true" && "${recovered_output}" == ocid1.instance.* && -z "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}" ]]; then
export LAB_OCI_EDGE_EXISTING_INSTANCE_ID="${recovered_output}"
fi
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw email_instance_id 2>/dev/null || true)"
if [[ "${email_state_managed}" != "true" && "${recovered_output}" == ocid1.instance.* && -z "${LAB_OCI_EMAIL_EXISTING_INSTANCE_ID:-}" ]]; then
export LAB_OCI_EMAIL_EXISTING_INSTANCE_ID="${recovered_output}"
fi
recovered_output="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -state="${homelab_state_file}" -raw bastion_id 2>/dev/null || true)"
[[ "${recovered_output}" == ocid1.bastion.* && -z "${LAB_OCI_BASTION_ID:-}" ]] && export LAB_OCI_BASTION_ID="${recovered_output}"
[[ -n "${LAB_OCI_EXISTING_VCN_ID:-}" ]] && printf 'Recovered OCI foundation OCIDs from state outputs.\n'
oci_foundation_export_inputs() {
# Rebuild this stack's TF_VAR set. export_if_unset would otherwise
# retain stale counts/OCIDs from before reconciliation.
local name
while IFS= read -r name; do
unset "TF_VAR_${name}"
done < <(sed -n 's/^variable "\([^"]*\)".*/\1/p' "${REPO_ROOT}/bootstrap/oci/variables.tf")
export_oci_foundation_tf_vars
if [[ "${LAB_OCI_STATE_BASTION_MANAGED:-false}" == "true" ]]; then
export TF_VAR_bastion_existing_id=""
fi
# Persisted OCIDs can refer to deleted resources after a tenancy reset.
# Validate the compartment before using it as the discovery root.
if [[ -n "${LAB_OCI_COMPARTMENT_ID:-}" && "${LAB_OCI_COMPARTMENT_ID}" != "null" ]] && ! "${oci_bin}" iam compartment get --compartment-id "${LAB_OCI_COMPARTMENT_ID}" >/dev/null 2>&1; then
printf 'Persisted OCI compartment %s is absent; rediscovering by name.\n' "${LAB_OCI_COMPARTMENT_ID}" >&2
unset LAB_OCI_COMPARTMENT_ID
fi
# Reuse named child compartments when a previous state file was lost or a
# prior apply completed only partway. OCI rejects a second compartment with
# the same name, so discover the active OCID before Terraform plans.
for status in homelab email; do
case "${status}" in
homelab)
[[ "${LAB_OCI_CREATE_COMPARTMENT:-true}" == "true" || "${homelab_compartment_managed}" == "true" ]] || continue
compartment_id="${LAB_OCI_COMPARTMENT_ID:-}"
compartment_name="${LAB_OCI_COMPARTMENT_NAME:-homelab-learning}"
if [[ "${homelab_compartment_managed}" == "true" ]]; then
export LAB_OCI_CREATE_COMPARTMENT=true
fi
;;
email)
[[ "${LAB_OCI_EMAIL_CREATE_COMPARTMENT:-true}" == "true" ]] || continue
compartment_id="${LAB_OCI_EMAIL_COMPARTMENT_ID:-}"
compartment_name="${LAB_OCI_EMAIL_COMPARTMENT_NAME:-homelab-email}"
;;
esac
[[ -n "${compartment_id}" && "${compartment_id}" != "null" ]] || {
compartment_id="$("${oci_bin}" iam compartment list \
--compartment-id "${LAB_OCI_TENANCY_ID}" \
--compartment-id-in-subtree true \
--name "${compartment_name}" --all \
--query 'data[0].id' --raw-output 2>/dev/null || true)"
if [[ -n "${compartment_id}" && "${compartment_id}" != "null" ]]; then
if [[ "${status}" == "homelab" ]]; then
export LAB_OCI_COMPARTMENT_ID="${compartment_id}"
# Keep the Terraform resource address when state still
# manages the compartment; otherwise a persisted
# reconciliation flag would plan its destruction.
if [[ "${homelab_compartment_managed}" == "true" ]]; then
export LAB_OCI_CREATE_COMPARTMENT=true
else
export LAB_OCI_CREATE_COMPARTMENT=false
fi
else
export LAB_OCI_EMAIL_COMPARTMENT_ID="${compartment_id}"
export LAB_OCI_EMAIL_CREATE_COMPARTMENT=false
fi
printf 'Reusing existing OCI %s compartment %s (%s).\n' \
"${status}" "${compartment_name}" "${compartment_id}"
fi
}
done
# Recover an existing VCN when the persisted input was lost. This keeps
# subnet CIDR derivation and all dependent resources anchored to the
# surviving network instead of falling back to the default VCN inputs.
if [[ "${network_state_managed}" == "true" ]]; then
# The VCN and dependent network resources are still managed by this
# state file; keep their resource counts stable rather than switching
# to data-source mode and planning their destruction.
unset LAB_OCI_EXISTING_VCN_ID LAB_OCI_EXISTING_PUBLIC_SUBNET_ID
printf 'Preserving state-managed OCI VCN and network resources.\n'
elif [[ -z "${LAB_OCI_EXISTING_VCN_ID:-}" ]]; then
local discovered_vcn_id
discovered_vcn_id="$(oci_discover_vcn_id "${LAB_OCI_TENANCY_ID}" "${LAB_OCI_VCN_DISPLAY_NAME:-homelab-vcn}" "${LAB_OCI_VCN_CIDR:-10.50.0.0/16}" || true)"
if [[ -n "${discovered_vcn_id}" && "${discovered_vcn_id}" != "null" ]]; then
export LAB_OCI_EXISTING_VCN_ID="${discovered_vcn_id}"
printf 'Reusing existing OCI VCN (%s).\n' "${discovered_vcn_id}"
fi
fi
if [[ -n "${LAB_OCI_EXISTING_VCN_ID:-}" && -z "${LAB_OCI_EXISTING_PUBLIC_SUBNET_ID:-}" ]]; then
local discovered_public_subnet_id
discovered_public_subnet_id="$(${oci_bin} network subnet list \
--compartment-id "${LAB_OCI_COMPARTMENT_ID}" \
--vcn-id "${LAB_OCI_EXISTING_VCN_ID}" --all \
--query 'data[?"display-name"==`homelab-public-subnet`].id | [0]' \
--raw-output 2>/dev/null || true)"
if [[ -n "${discovered_public_subnet_id}" && "${discovered_public_subnet_id}" != "null" ]]; then
export LAB_OCI_EXISTING_PUBLIC_SUBNET_ID="${discovered_public_subnet_id}"
printf 'Reusing existing OCI public subnet (%s).\n' "${discovered_public_subnet_id}"
fi
fi
# If state was lost, adopt active Jeannie-named instances instead of
# creating duplicates. State-managed instances remain untouched by this
# discovery path.
if [[ "${edge_state_managed}" != "true" && -z "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}" && "${LAB_OCI_EDGE_ENABLED:-true}" == "true" && "${LAB_OCI_COMPUTE_ENABLED:-true}" == "true" ]]; then
local discovered_edge_instance
discovered_edge_instance="$(oci_discover_active_instance_id "${LAB_OCI_EDGE_DISPLAY_NAME:-homelab-edge}" "${LAB_OCI_TENANCY_ID}" || true)"
if [[ "${discovered_edge_instance}" == ocid1.instance.* ]]; then
export LAB_OCI_EDGE_EXISTING_INSTANCE_ID="${discovered_edge_instance}"
printf 'Adopting existing OCI edge instance (%s).\n' "${discovered_edge_instance}"
fi
fi
if [[ "${email_state_managed}" != "true" && -z "${LAB_OCI_EMAIL_EXISTING_INSTANCE_ID:-}" && "${LAB_OCI_EMAIL_ENABLED:-true}" == "true" && "${LAB_OCI_COMPUTE_ENABLED:-true}" == "true" ]]; then
local discovered_email_instance
discovered_email_instance="$(oci_discover_active_instance_id "${LAB_OCI_EMAIL_DISPLAY_NAME:-homelab-mail}" "${LAB_OCI_TENANCY_ID}" || true)"
if [[ "${discovered_email_instance}" == ocid1.instance.* ]]; then
export LAB_OCI_EMAIL_EXISTING_INSTANCE_ID="${discovered_email_instance}"
local discovered_email_compartment
discovered_email_compartment="$("${oci_bin}" compute instance get --instance-id "${discovered_email_instance}" --query 'data."compartment-id"' --raw-output 2>/dev/null || true)"
if [[ "${discovered_email_compartment}" == ocid1.compartment.* ]]; then
export LAB_OCI_EMAIL_COMPARTMENT_ID="${discovered_email_compartment}"
export LAB_OCI_EMAIL_CREATE_COMPARTMENT=false
fi
printf 'Adopting existing OCI email instance (%s).\n' "${discovered_email_instance}"
fi
fi
# Existing VCNs may outlive the local state file. Use the VCN owner
# compartment for discovery and avoid creating a duplicate Bastion.
if [[ "${LAB_OCI_BASTION_ID:-}" == Usage:* || "${LAB_OCI_BASTION_ID:-}" == *"Error:"* ]]; then
unset LAB_OCI_BASTION_ID
fi
if truthy "${LAB_OCI_BASTION_ENABLED:-true}" && [[ -z "${LAB_OCI_BASTION_ID:-}" ]]; then
local bastion_compartment_id="${LAB_OCI_COMPARTMENT_ID:-${LAB_OCI_TENANCY_ID:-}}"
if [[ -n "${LAB_OCI_EXISTING_VCN_ID:-}" ]]; then
bastion_compartment_id="$("${oci_bin}" network vcn get \
--vcn-id "${LAB_OCI_EXISTING_VCN_ID}" \
--query 'data."compartment-id"' --raw-output 2>/dev/null || true)"
fi
if [[ -n "${bastion_compartment_id}" ]]; then
local discovered_bastion_id
discovered_bastion_id="$("${oci_bin}" bastion bastion list \
--compartment-id "${bastion_compartment_id}" --all \
--query "data[?name==\`${LAB_OCI_BASTION_NAME:-homelab-bastion}\`].id | [0]" \
--raw-output 2>/dev/null || true)"
if [[ "${discovered_bastion_id}" == ocid1.bastion.* ]]; then
export LAB_OCI_BASTION_ID="${discovered_bastion_id}"
printf 'Reusing existing OCI Bastion (%s).\n' "${discovered_bastion_id}"
elif [[ "${LAB_OCI_BASTION_NAME:-homelab-bastion}" == "homelab-bastion" && -n "${LAB_OCI_COMPARTMENT_ID:-}" ]]; then
# OCI can reject a duplicate Bastion name even when the
# existing Bastion belongs to an older network. Make the new
# Bastion name deterministic for this VCN.
local bastion_suffix
bastion_suffix="${LAB_OCI_COMPARTMENT_ID: -8}"
export LAB_OCI_BASTION_NAME="homelab-bastion-${bastion_suffix}"
printf 'Using network-specific OCI Bastion name %s.\n' "${LAB_OCI_BASTION_NAME}"
fi
fi
fi
# A persisted email subnet CIDR can belong to an older VCN. Select a free
# deterministic /24 inside the current VCN rather than failing late at OCI.
if [[ -n "${LAB_OCI_EXISTING_VCN_ID:-}" && -z "${LAB_OCI_EXISTING_EMAIL_SUBNET_ID:-}" && -n "${LAB_OCI_EMAIL_SUBNET_CIDR:-}" ]] && command -v python3 >/dev/null 2>&1; then
local vcn_cidr corrected_email_cidr existing_email_subnet_id
local vcn_compartment_id
vcn_compartment_id="$("${oci_bin}" network vcn get --vcn-id "${LAB_OCI_EXISTING_VCN_ID}" \
--query 'data."compartment-id"' --raw-output 2>/dev/null || true)"
if [[ -n "${vcn_compartment_id}" ]]; then
existing_email_subnet_id="$("${oci_bin}" network subnet list \
--compartment-id "${vcn_compartment_id}" --vcn-id "${LAB_OCI_EXISTING_VCN_ID}" --all \
--query 'data[?"display-name"==`homelab-email-subnet`].id | [0]' \
--raw-output 2>/dev/null || true)"
if [[ -n "${existing_email_subnet_id}" && "${existing_email_subnet_id}" != "null" ]]; then
export LAB_OCI_EXISTING_EMAIL_SUBNET_ID="${existing_email_subnet_id}"
printf 'Reusing existing OCI email subnet (%s).\n' "${existing_email_subnet_id}"
fi
fi
vcn_cidr="$("${oci_bin}" network vcn get --vcn-id "${LAB_OCI_EXISTING_VCN_ID}" \
--query 'data."cidr-blocks"[0]' --raw-output 2>/dev/null || true)"
corrected_email_cidr="$(python3 - "${vcn_cidr}" "${LAB_OCI_EMAIL_SUBNET_CIDR}" <<'PY'
import ipaddress
import itertools
import sys
try:
vcn = ipaddress.ip_network(sys.argv[1], strict=False)
requested = ipaddress.ip_network(sys.argv[2], strict=False)
if requested.subnet_of(vcn):
print(requested)
elif vcn.prefixlen <= 24:
print(next(itertools.islice(vcn.subnets(new_prefix=24), 30, 31)))
except (ValueError, IndexError, StopIteration):
pass
PY
)"
if [[ -n "${corrected_email_cidr}" && "${corrected_email_cidr}" != "${LAB_OCI_EMAIL_SUBNET_CIDR}" ]]; then
export LAB_OCI_EMAIL_SUBNET_CIDR="${corrected_email_cidr}"
printf 'Adjusted email subnet CIDR to %s inside the existing VCN.\n' "${corrected_email_cidr}"
fi
fi
[[ -n "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}" ]] || return 0
output_file="$(mktemp)"
if ! "${oci_bin}" compute instance get \
--instance-id "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID}" \
--query 'data.id' --raw-output >"${output_file}" 2>&1; then
if grep -q '"status": 404' "${output_file}"; then
printf '%s\n' 'Persisted OCI edge/network resources are absent; switching foundation to create mode.' >&2
export LAB_OCI_CREATE_COMPARTMENT=true
unset LAB_OCI_COMPARTMENT_ID LAB_OCI_EDGE_EXISTING_INSTANCE_ID
unset LAB_OCI_EXISTING_VCN_ID LAB_OCI_EXISTING_PUBLIC_SUBNET_ID LAB_OCI_EXISTING_EMAIL_SUBNET_ID
rm -f "${output_file}"
return 0
fi
cat "${output_file}" >&2
rm -f "${output_file}"
return 1
fi
rm -f "${output_file}"
for status in vcn subnet; do
local resource_id=""
case "${status}" in
vcn) resource_id="${LAB_OCI_EXISTING_VCN_ID:-}"; [[ -n "${resource_id}" ]] || continue ;;
subnet) resource_id="${LAB_OCI_EXISTING_PUBLIC_SUBNET_ID:-}"; [[ -n "${resource_id}" ]] || continue ;;
esac
output_file="$(mktemp)"
if [[ "${status}" == "vcn" ]]; then
"${oci_bin}" network vcn get --vcn-id "${resource_id}" >"${output_file}" 2>&1 || true
else
"${oci_bin}" network subnet get --subnet-id "${resource_id}" >"${output_file}" 2>&1 || true
fi
if grep -q '"status": 404' "${output_file}"; then
printf '%s\n' 'Persisted OCI edge/network resources are absent; switching foundation to create mode.' >&2
export LAB_OCI_CREATE_COMPARTMENT=true
unset LAB_OCI_COMPARTMENT_ID LAB_OCI_EDGE_EXISTING_INSTANCE_ID
unset LAB_OCI_EXISTING_VCN_ID LAB_OCI_EXISTING_PUBLIC_SUBNET_ID LAB_OCI_EXISTING_EMAIL_SUBNET_ID
rm -f "${output_file}"
return 0
elif grep -q '"status": [45][0-9][0-9]' "${output_file}"; then
cat "${output_file}" >&2
rm -f "${output_file}"
return 1
fi
rm -f "${output_file}"
done
}
oci_wait_for_ssh() {
@ -4188,7 +3884,7 @@ oci_foundation_manage() {
unset TF_VAR_compute_enabled
unset TF_VAR_edge_availability_domain TF_VAR_email_availability_domain
unset TF_VAR_existing_vcn_id TF_VAR_existing_public_subnet_id TF_VAR_existing_email_subnet_id
export_oci_foundation_tf_vars
oci_foundation_export_inputs
local action="${1:-status}"
shift || true
local stack="${REPO_ROOT}/bootstrap/oci"
@ -4200,10 +3896,20 @@ oci_foundation_manage() {
fi
case "${action}" in
verify)
python3 "${REPO_ROOT}/tests/jeannie/test_oci_foundation_resolve.py"
;;
status)
tofu -chdir="${stack}" show "${tofu_state_args[@]}" -no-color 2>/dev/null || echo "OCI foundation has no state yet."
;;
plan|apply)
# Serialize generated import declarations as well as state access.
local foundation_lock
exec {foundation_lock}>"${stack}/.jeannie-foundation.lock"
if ! flock -n "${foundation_lock}"; then
echo "Another OCI foundation run is active; wait for it to finish." >&2
return 1
fi
if [[ "${TF_VAR_enabled:-false}" != "true" ]]; then
echo "OCI foundation is disabled. Set LAB_OCI_FOUNDATION_ENABLED=true and the required LAB_OCI_* inputs first." >&2
return 2
@ -4219,14 +3925,28 @@ oci_foundation_manage() {
unset TF_VAR_compute_enabled
unset TF_VAR_edge_availability_domain TF_VAR_email_availability_domain
unset TF_VAR_existing_vcn_id TF_VAR_existing_public_subnet_id TF_VAR_existing_email_subnet_id
export_oci_foundation_tf_vars
oci_foundation_export_inputs
oci_foundation_save_config
tofu -chdir="${stack}" init
if [[ "${action}" == "plan" ]]; then
tofu -chdir="${stack}" plan "${tofu_state_args[@]}" "$@"
else
tofu -chdir="${stack}" init -input=false
local foundation_plan foundation_json
foundation_plan="$(mktemp "${TMPDIR:-/tmp}/jeannie-oci-plan.XXXXXX")"
foundation_json="${foundation_plan}.json"
if ! tofu -chdir="${stack}" plan "${tofu_state_args[@]}" -input=false -out="${foundation_plan}" "$@"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
if ! tofu -chdir="${stack}" show -json "${foundation_plan}" >"${foundation_json}" ||
! python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" check-plan --plan "${foundation_json}"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
if [[ "${action}" == "apply" ]]; then
record_change_journal "oci-foundation" apply "$@"
tofu -chdir="${stack}" apply "${tofu_state_args[@]}" "$@" -auto-approve
if ! tofu -chdir="${stack}" apply "${tofu_state_args[@]}" "${foundation_plan}"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
rm -f "${foundation_plan}" "${foundation_json}"
local discovered_edge_ip
local discovered_email_ip
local discovered_bastion_id
@ -4320,6 +4040,9 @@ oci_foundation_manage() {
return 1
fi
fi
rm -f "${foundation_plan}" "${foundation_json}"
flock -u "${foundation_lock}"
exec {foundation_lock}>&-
;;
destroy)
if [[ "${1:-}" != "--yes" ]]; then
@ -4332,7 +4055,7 @@ oci_foundation_manage() {
tofu -chdir="${stack}" destroy "${tofu_state_args[@]}" "$@" -auto-approve
;;
*)
echo "Usage: ./jeannie oci-foundation {status|plan|apply|destroy --yes}" >&2
echo "Usage: ./jeannie oci-foundation {verify|status|plan|apply|destroy --yes}" >&2
return 2
;;
esac
@ -4359,21 +4082,35 @@ oci_bastion_ssh() {
}
oci_enable_bastion_plugin() {
local instance_id="${1:-}"
local oci_bin agent_config
local instance_id="${1:-}" oci_bin agent_config instance_json
[[ -n "${instance_id}" ]] || return 0
oci_bin="$(oci_cli_resolve)" || return 1
instance_json="$("${oci_bin}" compute instance get --instance-id "${instance_id}" --output json)" || return 1
agent_config="$(mktemp)"
cat >"${agent_config}" <<'JSON'
{
"pluginsConfig": [
{
"desiredState": "ENABLED",
"name": "Bastion"
}
]
}
JSON
if ! printf '%s' "${instance_json}" | python3 -c '
import json, sys
config = json.load(sys.stdin).get("data", {}).get("agent-config") or {}
plugins = config.get("plugins-config") or []
if any(p.get("name") == "Bastion" and p.get("desired-state") == "ENABLED" for p in plugins):
sys.exit(0)
updated = [{"name": p["name"], "desiredState": p.get("desired-state", "DISABLED")}
for p in plugins if p.get("name") != "Bastion"]
updated.append({"name": "Bastion", "desiredState": "ENABLED"})
result = {"pluginsConfig": updated}
for source, target in (("is-management-disabled", "isManagementDisabled"),
("is-monitoring-disabled", "isMonitoringDisabled"),
("are-all-plugins-disabled", "areAllPluginsDisabled")):
if config.get(source) is not None:
result[target] = config[source]
print(json.dumps(result))
' >"${agent_config}"; then
rm -f "${agent_config}"
return 1
fi
if [[ ! -s "${agent_config}" ]]; then
rm -f "${agent_config}"
return 0
fi
if ! "${oci_bin}" compute instance update --instance-id "${instance_id}" \
--agent-config "file://${agent_config}" --force >/dev/null; then
rm -f "${agent_config}"
@ -4393,74 +4130,18 @@ oci_cli_resolve() {
}
oci_discover_active_instance_id() {
local display_name="$1" root_compartment="$2" oci_bin compartments compartment_id payload result
oci_bin="$(oci_cli_resolve)" || return 1
compartments="${root_compartment}"$'\n'$("${oci_bin}" iam compartment list --compartment-id "${root_compartment}" --compartment-id-in-subtree true --all --query 'data[].id' --raw-output 2>/dev/null || true)
while IFS= read -r compartment_id; do
[[ -n "${compartment_id}" ]] || continue
payload="$("${oci_bin}" compute instance list --compartment-id "${compartment_id}" --all --output json 2>/dev/null || true)"
[[ -n "${payload}" ]] || continue
result="$(OCI_DISCOVERY_JSON="${payload}" python3 - "${display_name}" <<'PY'
import json, os, sys
name = sys.argv[1]
for item in json.loads(os.environ["OCI_DISCOVERY_JSON"]).get("data", []):
if item.get("display-name") == name and item.get("lifecycle-state") == "RUNNING":
print(item.get("id", ""))
break
PY
)"
[[ -n "${result}" ]] && { printf '%s\n' "${result}"; return 0; }
done <<<"${compartments}"
return 1
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind instance --name "$1" --root "$2"
}
oci_discover_vcn_id() {
local root_compartment="$1" display_name="$2" target_cidr="${3:-}" oci_bin compartments compartment_id payload result
oci_bin="$(oci_cli_resolve)" || return 1
compartments="${root_compartment}"$'\n'$("${oci_bin}" iam compartment list --compartment-id "${root_compartment}" --all --query 'data[].id' --raw-output 2>/dev/null || true)
while IFS= read -r compartment_id; do
[[ -n "${compartment_id}" ]] || continue
payload="$("${oci_bin}" network vcn list --compartment-id "${compartment_id}" --all --output json 2>/dev/null || true)"
[[ -n "${payload}" ]] || continue
result="$(OCI_DISCOVERY_JSON="${payload}" python3 - "${display_name}" "${target_cidr}" <<'PY'
import json, os, sys
name = sys.argv[1]
target_cidr = sys.argv[2]
for item in json.loads(os.environ["OCI_DISCOVERY_JSON"]).get("data", []):
tags = item.get("freeform-tags") or {}
cidrs = item.get("cidr-blocks") or []
if item.get("cidr-block"):
cidrs.append(item.get("cidr-block"))
if item.get("display-name") == name or tags.get("managed_by") == "jeannie" or target_cidr in cidrs:
print(item.get("id", ""))
break
PY
)"
[[ -n "${result}" ]] && { printf '%s\n' "${result}"; return 0; }
done <<<"${compartments}"
return 1
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind vcn --name "$2" --root "$1"
}
oci_discover_active_bastion_id() {
local root_compartment="$1" bastion_name="$2" oci_bin compartments compartment_id payload result
oci_bin="$(oci_cli_resolve)" || return 1
compartments="${root_compartment}"$'\n'$("${oci_bin}" iam compartment list --compartment-id "${root_compartment}" --all --query 'data[].id' --raw-output 2>/dev/null || true)
while IFS= read -r compartment_id; do
[[ -n "${compartment_id}" ]] || continue
payload="$("${oci_bin}" bastion bastion list --compartment-id "${compartment_id}" --all --output json 2>/dev/null || true)"
[[ -n "${payload}" ]] || continue
result="$(OCI_DISCOVERY_JSON="${payload}" python3 - "${bastion_name}" <<'PY'
import json, os, sys
name = sys.argv[1]
for item in json.loads(os.environ["OCI_DISCOVERY_JSON"]).get("data", []):
if item.get("name") == name and item.get("lifecycle-state", item.get("state")) == "ACTIVE":
print(item.get("id", ""))
break
PY
)"
[[ -n "${result}" ]] && { printf '%s\n' "${result}"; return 0; }
done <<<"${compartments}"
return 1
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind bastion --name "$2" --root "$1"
}
oci_status() {

View File

@ -370,17 +370,22 @@ export_oci_foundation_tf_vars() {
export_if_unset TF_VAR_existing_vcn_id "${LAB_OCI_EXISTING_VCN_ID:-}"
export_if_unset TF_VAR_existing_public_subnet_id "${LAB_OCI_EXISTING_PUBLIC_SUBNET_ID:-}"
export_if_unset TF_VAR_existing_email_subnet_id "${LAB_OCI_EXISTING_EMAIL_SUBNET_ID:-}"
export_if_unset TF_VAR_vcn_cidr "${LAB_OCI_VCN_CIDR:-}"
export_if_unset TF_VAR_public_subnet_cidr "${LAB_OCI_PUBLIC_SUBNET_CIDR:-}"
export_if_unset TF_VAR_private_subnet_cidr "${LAB_OCI_PRIVATE_SUBNET_CIDR:-}"
export_if_unset TF_VAR_email_subnet_cidr "${LAB_OCI_EMAIL_SUBNET_CIDR:-}"
export_if_unset TF_VAR_admin_cidr "${LAB_OCI_ADMIN_CIDR:-}"
export_if_unset TF_VAR_monitoring_enabled "${LAB_OCI_MONITORING_ENABLED:-}"
export_if_unset TF_VAR_monitoring_cidr "${LAB_OCI_MONITORING_CIDR:-${LAB_OCI_ADMIN_CIDR:-}}"
export_if_unset TF_VAR_monitoring_alarms_enabled "${LAB_OCI_MONITORING_ALARMS_ENABLED:-}"
export_if_unset TF_VAR_monitoring_topic_name "${LAB_OCI_MONITORING_TOPIC_NAME:-}"
export_if_unset TF_VAR_monitoring_topic_compartment_id "${LAB_OCI_MONITORING_TOPIC_COMPARTMENT_ID:-}"
export_if_unset TF_VAR_monitoring_notification_email "${LAB_OCI_MONITORING_NOTIFICATION_EMAIL:-}"
export_if_unset TF_VAR_edge_monitoring_instance_id "${LAB_OCI_EDGE_INSTANCE_ID:-}"
export_if_unset TF_VAR_email_monitoring_instance_id "${LAB_OCI_EMAIL_INSTANCE_ID:-}"
export_if_unset TF_VAR_backup_bucket_enabled "${LAB_OCI_BACKUP_BUCKET_ENABLED:-}"
export_if_unset TF_VAR_backup_bucket_name "${LAB_OCI_BACKUP_BUCKET_NAME:-${LAB_OCI_BACKUP_BUCKET:-}}"
export_if_unset TF_VAR_backup_bucket_compartment_id "${LAB_OCI_BACKUP_BUCKET_COMPARTMENT_ID:-}"
export_if_unset TF_VAR_backup_bucket_namespace "${LAB_OCI_BACKUP_BUCKET_NAMESPACE:-}"
export_if_unset TF_VAR_bastion_enabled "${LAB_OCI_BASTION_ENABLED:-}"
export_if_unset TF_VAR_bastion_name "${LAB_OCI_BASTION_NAME:-}"

View File

@ -7987,271 +7987,52 @@ edge_apply() {
export TF_VAR_edge_ssh_key_path="${configured_edge_key}"
fi
refresh_oci_edge_endpoint || return 1
oci_ensure_edge_bastion_ingress || return 1
refresh_oci_edge_host_key
if [[ -n "${LAB_OCI_BASTION_ID:-}" && -n "${LAB_OCI_EDGE_INSTANCE_ID:-}" &&
"${LAB_OCI_BASTION_ENABLED:-true}" != "false" ]] &&
declare -F oci_enable_bastion_plugin >/dev/null 2>&1; then
oci_enable_bastion_plugin "${LAB_OCI_EDGE_INSTANCE_ID}" || return 1
if [[ "${LAB_EDGE_SSH_TRANSPORT:-tailscale}" == "bastion" ]]; then
oci_ensure_edge_bastion_ingress || return 1
if [[ -n "${LAB_OCI_EDGE_INSTANCE_ID:-}" ]]; then
oci_enable_bastion_plugin "${LAB_OCI_EDGE_INSTANCE_ID}" || return 1
fi
prepare_oci_edge_bastion || return 1
fi
prepare_oci_edge_bastion || return 1
edge_ssh_args
local ssh_host="${TF_VAR_edge_ssh_host}" ssh_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
# One bounded authentication check gives a useful error before OpenTofu
# can retry the same inaccessible host for several minutes.
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true || return 1
run_tofu_stack "bootstrap/edge"
run_tofu_stack "bootstrap/edge" || return 1
# OpenTofu does not rerun provisioners when inputs are unchanged. Reconcile
# stopped containers and check the deployed proxy without recreating them.
edge_ssh_args
local install_dir="${TF_VAR_edge_install_dir:-${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}}"
if [[ "${install_dir}" == *"'"* ]]; then
echo "Invalid edge install directory." >&2
return 1
fi
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
"cd '${install_dir}' && sudo docker compose up -d --no-recreate &&
sudo docker compose exec -T nginx-dev nginx -t &&
curl -kfsS --connect-timeout 5 --max-time 10 https://127.0.0.1/edge-health >/dev/null" || return 1
local edge_host="${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}"
if [[ -n "${edge_host}" ]] && declare -F update_duckdns_edge_ip >/dev/null 2>&1; then
update_duckdns_edge_ip "${edge_host}"
fi
edge_flush_caches
# Flushing caches restarts services on otherwise unchanged applies.
if truthy "${LAB_EDGE_FLUSH_CACHES_AFTER_APPLY:-false}"; then
edge_flush_caches
fi
return 0
}
refresh_oci_edge_endpoint() {
local stack="${REPO_ROOT}/bootstrap/oci"
local state_file="${LAB_OCI_FOUNDATION_STATE_FILE:-}"
local -a tofu_state_args=()
local discovered_edge_ip=""
local discovered_edge_private_ip=""
local discovered_edge_instance_id=""
local state_bastion_id=""
local oci_bin=""
local vnic_id=""
local tenancy_id="${LAB_OCI_TENANCY_ID:-}"
local oci_config_file="${OCI_CLI_CONFIG_FILE:-${HOME}/.oci/config}"
local instance_compartment="${LAB_OCI_COMPARTMENT_ID:-}"
local existing_instance_id="${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}"
local candidate_compartment=""
local candidate_id=""
local edge_identity_stale=false
# A managed edge OCID is derived from foundation state or OCI discovery;
# never let a stale value from a previous long-lived API invocation survive
# into Bastion plugin/session setup. Explicit existing-instance mode keeps
# its caller-provided identity.
if [[ -z "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}" ]]; then
unset LAB_OCI_EDGE_INSTANCE_ID
fi
# These are derived per run; never retain a proxy/private address from a
# previous long-lived API invocation.
local resolved
unset TF_VAR_edge_ssh_host TF_VAR_edge_bastion_host TF_VAR_edge_bastion_user
unset TF_VAR_edge_bastion_port TF_VAR_edge_bastion_private_key_path
unset LAB_OCI_EDGE_BASTION_PROXY_COMMAND LAB_OCI_EDGE_BASTION_SESSION_ID
# A recreated OCI instance can receive a new public IP. Prefer the
# foundation output over inventory so a standalone `edge` run is
# idempotent instead of trying the previous address.
if [[ -n "${state_file}" ]]; then
tofu_state_args=("-state=${state_file}")
fi
if [[ ! -d "${stack}" ]] || ! command -v tofu >/dev/null 2>&1; then
return 0
fi
discovered_edge_ip="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw edge_public_ip 2>/dev/null || true)"
discovered_edge_instance_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw edge_instance_id 2>/dev/null || true)"
state_bastion_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw bastion_id 2>/dev/null || true)"
if [[ "${state_bastion_id}" == ocid1.bastion.* ]]; then
export LAB_OCI_BASTION_ID="${state_bastion_id}"
elif [[ "${LAB_OCI_BASTION_ID:-}" != ocid1.bastion.* ]]; then
unset LAB_OCI_BASTION_ID
fi
# The API service may not inherit the interactive shell's OCI compartment
# variables. Recover the managed compartment from foundation state so a
# recreated edge can still be discovered without manual exports.
if [[ -z "${instance_compartment}" ]]; then
instance_compartment="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw compartment_id 2>/dev/null || true)"
fi
# The remote API is long-lived and may not have received the tenancy
# export that was used by an interactive shell. Recover it from the OCI
# profile so compartment-wide discovery remains self-contained.
if [[ -z "${tenancy_id}" && -r "${oci_config_file}" ]]; then
tenancy_id="$(awk -v profile="[${OCI_CLI_PROFILE:-DEFAULT}]" '
$0 == profile { in_profile=1; next }
/^\[/ { in_profile=0 }
in_profile && $0 ~ /^[[:space:]]*tenancy[[:space:]]*=/ {
sub(/^[[:space:]]*tenancy[[:space:]]*=[[:space:]]*/, "", $0)
print $0
exit
}
' "${oci_config_file}" 2>/dev/null || true)"
# OCI profile names are case-sensitive in the file but operators may
# export a differently-cased OCI_CLI_PROFILE. If the selected section
# was not found, use the first tenancy entry as a safe fallback.
if [[ -z "${tenancy_id}" ]]; then
tenancy_id="$(awk '
/^[[:space:]]*tenancy[[:space:]]*=/ {
sub(/^[[:space:]]*tenancy[[:space:]]*=[[:space:]]*/, "", $0)
print $0
exit
}
' "${oci_config_file}" 2>/dev/null || true)"
fi
fi
# Ignore stale shell values such as a literal command substitution or a
# compartment OCID accidentally assigned to the tenancy variable. This
# lets the validated OCI profile value above take precedence.
if [[ -n "${tenancy_id}" && "${tenancy_id}" != ocid1.tenancy.* ]]; then
tenancy_id=""
fi
if [[ -z "${tenancy_id}" && -r "${oci_config_file}" ]]; then
tenancy_id="$(awk '
/^[[:space:]]*tenancy[[:space:]]*=/ {
sub(/^[[:space:]]*tenancy[[:space:]]*=[[:space:]]*/, "", $0)
print $0
exit
}
' "${oci_config_file}" 2>/dev/null || true)"
fi
# Existing-instance mode can retain an old/null public_ip in state. Query
# OCI directly from the instance OCID and read the attached VNIC instead.
if [[ -z "${discovered_edge_instance_id}" || "${discovered_edge_instance_id}" == "null" ]]; then
if [[ "${LAB_OCI_EDGE_INSTANCE_MANAGED:-false}" != "true" ]]; then
discovered_edge_instance_id=""
else
discovered_edge_instance_id="${LAB_OCI_EDGE_INSTANCE_ID:-}"
fi
fi
# An old explicit existing-instance input must not pin recovery to a
# deleted jump box. Prefer a still-valid explicit instance; otherwise
# clear it and allow adoption of the current Jeannie-managed edge.
if [[ -n "${existing_instance_id}" && "${existing_instance_id}" != "null" ]] &&
declare -F oci_cli_resolve >/dev/null 2>&1; then
oci_bin="${oci_bin:-$(oci_cli_resolve 2>/dev/null || true)}"
if [[ -n "${oci_bin}" ]] && "${oci_bin}" compute instance get \
--instance-id "${existing_instance_id}" >/dev/null 2>&1; then
discovered_edge_instance_id="${existing_instance_id}"
edge_identity_stale=false
else
printf 'Configured OCI edge instance %s is absent; clearing the explicit identity and rediscovering.\n' \
"${existing_instance_id}" >&2
unset LAB_OCI_EDGE_EXISTING_INSTANCE_ID
existing_instance_id=""
edge_identity_stale=true
LAB_OCI_EDGE_INSTANCE_MANAGED=true
export LAB_OCI_EDGE_INSTANCE_MANAGED
fi
fi
if [[ -n "${discovered_edge_instance_id}" &&
"${discovered_edge_instance_id}" != "null" &&
-n "${instance_compartment}" ]] &&
declare -F oci_cli_resolve >/dev/null 2>&1; then
oci_bin="$(oci_cli_resolve 2>/dev/null || true)"
if [[ -n "${oci_bin}" && -n "${instance_compartment}" ]]; then
vnic_id="$("${oci_bin}" compute vnic-attachment list \
--compartment-id "${instance_compartment}" \
--instance-id "${discovered_edge_instance_id}" \
--query 'data[0]."vnic-id"' --raw-output 2>/dev/null || true)"
if [[ -n "${vnic_id}" && "${vnic_id}" != "null" ]]; then
discovered_edge_ip="$("${oci_bin}" network vnic get \
--vnic-id "${vnic_id}" \
--query 'data."public-ip"' --raw-output 2>/dev/null || true)"
discovered_edge_private_ip="$("${oci_bin}" network vnic get \
--vnic-id "${vnic_id}" \
--query 'data."private-ip"' --raw-output 2>/dev/null || true)"
else
edge_identity_stale=true
fi
fi
fi
# A state file or persisted config can retain an OCID for an instance that
# was destroyed outside OpenTofu. Clear that identity before managed-edge
# adoption so the current Jeannie-tagged instance can be found.
if [[ "${edge_identity_stale}" == "true" ]]; then
printf 'Persisted OCI edge instance %s is absent; rediscovering the Jeannie-managed edge.\n' \
"${discovered_edge_instance_id}" >&2
discovered_edge_instance_id=""
discovered_edge_ip=""
discovered_edge_private_ip=""
fi
# State may have been lost even though the Jeannie-created instance still
# exists. Recover only the exact managed identity: display name
# homelab-edge plus managed_by=jeannie. Never adopt arbitrary jump boxes.
if [[ ( -n "${tenancy_id}" || -n "${instance_compartment}" ) &&
-z "${existing_instance_id}" &&
( "${LAB_OCI_EDGE_INSTANCE_MANAGED:-false}" != "true" || "${edge_identity_stale}" == "true" || -z "${discovered_edge_instance_id}" ) ]] &&
declare -F oci_cli_resolve >/dev/null 2>&1; then
oci_bin="${oci_bin:-$(oci_cli_resolve 2>/dev/null || true)}"
if [[ -n "${oci_bin}" ]]; then
local -a edge_compartments=("${instance_compartment}")
# The instance may have been recreated in a child compartment
# after the original state was removed. Enumerate the tenancy's
# compartments so recovery does not depend on the old compartment
# OCID being correct.
if [[ -n "${tenancy_id}" ]]; then
while IFS= read -r candidate_compartment; do
[[ -n "${candidate_compartment}" ]] && edge_compartments+=("${candidate_compartment}")
done < <("${oci_bin}" iam compartment list \
--compartment-id "${tenancy_id}" \
--compartment-id-in-subtree true --all --output json 2>/dev/null \
| python3 -c 'import json,sys
raw=sys.stdin.read().strip()
data=json.loads(raw) if raw else {}
print("\\n".join(x.get("id", "") for x in data.get("data", [])))' 2>/dev/null || true)
edge_compartments+=("${tenancy_id}")
fi
for candidate_compartment in "${edge_compartments[@]}"; do
[[ -n "${candidate_compartment}" ]] || continue
candidate_id="$("${oci_bin}" compute instance list \
--compartment-id "${candidate_compartment}" --all --output json 2>/dev/null \
| python3 -c 'import json,sys
for item in json.load(sys.stdin).get("data", []):
if item.get("display-name") == "homelab-edge" and item.get("lifecycle-state") != "TERMINATED":
print(item.get("id", ""))
break' 2>/dev/null || true)"
if [[ -n "${candidate_id}" && "${candidate_id}" != "null" ]]; then
discovered_edge_instance_id="${candidate_id}"
instance_compartment="${candidate_compartment}"
LAB_OCI_EDGE_INSTANCE_MANAGED=true
export LAB_OCI_EDGE_INSTANCE_MANAGED
vnic_id="$("${oci_bin}" compute vnic-attachment list \
--compartment-id "${instance_compartment}" \
--instance-id "${discovered_edge_instance_id}" \
--query 'data[0]."vnic-id"' --raw-output 2>/dev/null || true)"
if [[ -n "${vnic_id}" && "${vnic_id}" != "null" ]]; then
discovered_edge_ip="$("${oci_bin}" network vnic get \
--vnic-id "${vnic_id}" \
--query 'data."public-ip"' --raw-output 2>/dev/null || true)"
discovered_edge_private_ip="$("${oci_bin}" network vnic get \
--vnic-id "${vnic_id}" \
--query 'data."private-ip"' --raw-output 2>/dev/null || true)"
fi
break
fi
done
fi
fi
if [[ -z "${discovered_edge_ip}" || "${discovered_edge_ip}" == "null" ]]; then
if [[ "${LAB_OCI_EDGE_INSTANCE_MANAGED:-false}" == "true" ]]; then
printf 'Jeannie-managed OCI edge discovery failed (instance=%s compartment=%s); refusing stale LAB_EDGE_HOST=%s.\n' \
"${discovered_edge_instance_id:-unknown}" "${instance_compartment:-unknown}" "${LAB_EDGE_HOST:-unset}" >&2
return 1
fi
return 0
fi
if [[ "${LAB_EDGE_HOST:-}" != "${discovered_edge_ip}" ]]; then
printf 'Refreshing OCI edge endpoint: %s -> %s\n' "${LAB_EDGE_HOST:-unset}" "${discovered_edge_ip}"
fi
export LAB_EDGE_HOST="${discovered_edge_ip}"
export TF_VAR_edge_host="${discovered_edge_ip}"
if [[ -n "${discovered_edge_private_ip}" && "${discovered_edge_private_ip}" != "null" &&
-n "${LAB_OCI_BASTION_ID:-}" && "${LAB_OCI_BASTION_ENABLED:-true}" != "false" ]]; then
export TF_VAR_edge_ssh_host="${discovered_edge_private_ip}"
export LAB_OCI_EDGE_PRIVATE_IP="${discovered_edge_private_ip}"
printf 'OCI edge private address discovered: %s (Bastion session will be prepared before SSH)\n' "${discovered_edge_private_ip}"
else
unset TF_VAR_edge_ssh_host LAB_OCI_EDGE_PRIVATE_IP
fi
if [[ "${discovered_edge_instance_id}" == ocid1.instance.* ]]; then
export LAB_OCI_EDGE_INSTANCE_ID="${discovered_edge_instance_id}"
fi
if [[ "${instance_compartment}" == ocid1.compartment.* ]]; then
export LAB_OCI_EDGE_COMPARTMENT_ID="${instance_compartment}"
fi
if declare -F oci_foundation_save_config >/dev/null 2>&1; then
oci_foundation_save_config
fi
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" edge \
--repo "${REPO_ROOT}")" || return 1
eval "${resolved}"
oci_foundation_save_config
}
oci_ensure_edge_bastion_ingress() {
@ -8312,8 +8093,8 @@ print("\\n".join(data.get("nsg-ids") or []))' 2>/dev/null || true)"
--nsg-id "${nsg}" --direction INGRESS --all --output json 2>/dev/null \
| SOURCE_CIDR="${source_cidr}" python3 -c 'import json,os,sys
for rule in json.load(sys.stdin).get("data", []):
tcp=rule.get("tcpOptions") or {}
port=tcp.get("destinationPortRange") or {}
tcp=rule.get("tcp-options") or rule.get("tcpOptions") or {}
port=tcp.get("destination-port-range") or tcp.get("destinationPortRange") or {}
if (rule.get("direction") == "INGRESS" and rule.get("protocol") == "6" and
rule.get("source") in (os.environ["SOURCE_CIDR"], "0.0.0.0/0") and
str(port.get("min")) == "22" and str(port.get("max")) == "22"):
@ -8459,7 +8240,7 @@ refresh_oci_edge_host_key() {
edge_ssh_args() {
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}}"
EDGE_SSH_ARGS=(-i "${edge_key}" -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
EDGE_SSH_ARGS=(-i "${edge_key}" -o BatchMode=yes -o ConnectTimeout="${LAB_EDGE_SSH_PREFLIGHT_SECONDS:-10}" -o ConnectionAttempts=1 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
if [[ -n "${LAB_OCI_EDGE_BASTION_PROXY_COMMAND:-}" ]]; then
if [[ "${LAB_OCI_EDGE_BASTION_PROXY_COMMAND}" == *'%h:%p'* ]]; then
EDGE_SSH_ARGS+=( -o "ProxyCommand=${LAB_OCI_EDGE_BASTION_PROXY_COMMAND}" )

View File

@ -0,0 +1,638 @@
#!/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 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"
if "oci_bastion_bastion.homelab" in managed:
values["LAB_OCI_BASTION_ENABLED"] = "true"
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):
process = subprocess.run([self.binary, *self.options, *arguments, "--output", "json"],
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"OCI {' '.join(arguments[:3])} failed: {process.stderr[-1800:]}")
return json.loads(process.stdout).get("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 = {row["id"]: 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:
imports.append({"to": address + "[0]", "id": import_id or item["id"]})
print(f"Adopting existing OCI {address}: {import_id or item['id']}", 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)

View File

@ -24,7 +24,10 @@ def inspect_stack(repo: Path, name: str, relative: str) -> dict:
directory = repo / relative
row = {"stack": name, "path": relative, "state": "missing", "lock": "clear", "drift": "unknown"}
state_file = directory / "terraform.tfstate"
lock_file = directory / ".terraform.tfstate.lock.info"
if relative == "bootstrap/oci" and os.environ.get("LAB_OCI_FOUNDATION_STATE_FILE"):
state_file = Path(os.environ["LAB_OCI_FOUNDATION_STATE_FILE"]).expanduser()
row["state_path"] = str(state_file)
lock_file = state_file.with_name("." + state_file.name + ".lock.info")
if not state_file.exists():
row["detail"] = "local state file not found"
return row
@ -47,6 +50,8 @@ def inspect_stack(repo: Path, name: str, relative: str) -> dict:
"-detailed-exitcode",
"-lock-timeout=0s",
]
if relative == "bootstrap/oci":
command.append(f"-state={state_file}")
try:
completed = subprocess.run(command, text=True, capture_output=True, timeout=900)
output = (completed.stdout + "\n" + completed.stderr).strip()

View File

@ -0,0 +1,126 @@
"""Offline regressions. Execute on Debian, without OCI or SSH access."""
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[2] / "scripts/oci-foundation-resolve.py"
SPEC = importlib.util.spec_from_file_location("oci_resolver", SOURCE)
resolver = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(resolver)
class ResolverTests(unittest.TestCase):
def test_unconfigured_remote_client_does_not_create_files(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
with patch.object(Path, "home", return_value=root):
resolver.load(SimpleNamespace(config=config, repo=root), set())
self.assertFalse(config.parent.exists())
def test_legacy_key_and_repeated_saves(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
key = "ssh-ed25519" + "\\" * 15 + " AAAA" + "\\" * 15 + " operator"
path.write_text(': "${LAB_OCI_SSH_PUBLIC_KEY:=' + key +
'}"; export LAB_OCI_SSH_PUBLIC_KEY\n')
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
for _ in range(3):
resolver.atomic_write(path, resolver.config_text(parsed))
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
self.assertEqual(parsed["LAB_OCI_SSH_PUBLIC_KEY"], "ssh-ed25519 AAAA operator")
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_config_never_executes(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
marker = Path(directory) / "must-not-exist"
path.write_text("touch " + str(marker))
with self.assertRaises(ValueError):
resolver.read_config(path, set())
self.assertFalse(marker.exists())
def test_migration_and_repeat_load(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
config.parent.mkdir(parents=True)
fresh = config.with_name("oci-foundation-fresh.env")
state = root / "fresh.tfstate"
state.write_text(json.dumps({
"version": 4, "resources": [{
"mode": "managed", "type": "oci_core_instance", "name": "edge",
"instances": [{"index_key": 0, "attributes": {
"id": "ocid1.instance.current", "compartment_id": "ocid1.compartment.current",
"availability_domain": "AD-1", "shape": "VM.Standard.E2.1.Micro",
"public_ip": "192.0.2.10",
}}],
}],
}))
old = {"LAB_OCI_COMPUTE_ENABLED": "false", "LAB_EDGE_HOST": "192.0.2.1",
"LAB_OCI_BACKUP_BUCKET_ID": "n/test/b/backup"}
alternate = {"LAB_OCI_FOUNDATION_STATE_FILE": str(state),
"LAB_OCI_EDGE_INSTANCE_ID": "ocid1.instance.current",
"LAB_OCI_COMPUTE_ENABLED": "false"}
config.write_text(resolver.config_text(old))
fresh.write_text(resolver.config_text(alternate))
names = set(old) | set(alternate) | {
"LAB_OCI_EDGE_ENABLED", "LAB_OCI_EDGE_EXISTING_INSTANCE_ID",
"LAB_OCI_EDGE_INSTANCE_MANAGED", "LAB_OCI_EDGE_COMPARTMENT_ID",
"LAB_OCI_EDGE_AVAILABILITY_DOMAIN", "LAB_OCI_EDGE_SHAPE",
}
args = SimpleNamespace(config=config, repo=root)
with patch.object(Path, "home", return_value=root), contextlib.redirect_stdout(io.StringIO()):
resolver.load(args, names)
first = config.read_text()
resolver.load(args, names)
merged = resolver.read_config(config, names)
self.assertEqual(merged["LAB_OCI_FOUNDATION_STATE_FILE"], str(state))
self.assertEqual(merged["LAB_OCI_COMPUTE_ENABLED"], "true")
self.assertEqual(merged["LAB_EDGE_HOST"], "192.0.2.10")
self.assertEqual(merged["LAB_OCI_BACKUP_BUCKET_ID"], "n/test/b/backup")
self.assertFalse(fresh.exists())
self.assertEqual(config.read_text(), first)
self.assertTrue(list(config.parent.glob("oci-foundation-archive-*/oci-foundation.env")))
def test_discovery_rejects_ambiguity_and_access_errors(self):
with self.assertRaises(ValueError):
resolver.OCI.unique([{"id": "one"}, {"id": "two"}], "edge")
response = SimpleNamespace(returncode=1, stderr='{"status": 404, "code": "NotAuthorizedOrNotFound"}')
with patch("subprocess.run", return_value=response), self.assertRaises(ValueError):
resolver.OCI().call("compute", "instance", "get", "--instance-id", "recorded")
def test_edge_separates_dns_and_ssh(self):
client = SimpleNamespace(
instance=lambda role: {"id": "ocid1.instance.current", "compartment-id": "owner",
"lifecycle-state": "RUNNING"},
vnic=lambda vm: {"public-ip": "192.0.2.10", "private-ip": "10.50.10.103"},
)
peers = {"Peer": {"peer": {"HostName": "homelab-oci-edge", "Online": True,
"TailscaleIPs": ["100.64.0.10"]}}}
response = SimpleNamespace(stdout=json.dumps(peers))
output = io.StringIO()
with patch.dict(os.environ, {}, clear=True), patch.object(resolver, "OCI", return_value=client), \
patch("subprocess.run", return_value=response), contextlib.redirect_stdout(output):
resolver.resolve_edge()
self.assertIn("export TF_VAR_edge_host=192.0.2.10", output.getvalue())
self.assertIn("export TF_VAR_edge_ssh_host=100.64.0.10", output.getvalue())
def test_plan_rejects_delete_and_replacement(self):
for actions in (["delete"], ["delete", "create"], ["create", "delete"]):
with self.subTest(actions=actions), self.assertRaises(ValueError):
resolver.validate_plan({"resource_changes": [
{"address": "oci_core_instance.edge[0]", "change": {"actions": actions}}]})
resolver.validate_plan({"resource_changes": [
{"address": "new", "change": {"actions": ["create"]}}]})
if __name__ == "__main__":
unittest.main()