Declarative Database Topologies: Orchestrating OCI DB Systems via Kubernetes Operators
Terraform is designed for infrastructure where resources can be destroyed and recreated on a diff; applying monolithic, push-based Terraform workspaces to stateful Oracle database fleets guarantees state-lock contention, out-of-band drift collisions, and catastrophic accidental replacements.
TL;DR
- Problem: Monolithic Terraform pipelines hold exclusive state locks during 45–90 minute RAC or Exadata provisioning runs, mark immutable
oci_database_db_systemfields (db_name,character_set) asforces replacement, and silently revert emergency console scaling on the next unrelated PR.- Answer: Keep Terraform for static foundational networking (VCNs, subnets, NSGs, Exadata infrastructure), and hand day-2 database lifecycles to a Kubernetes Operator (OCI Service Operator for Kubernetes /
OraOperator) backed by admission webhooks,WorkRequestpolling, and deletion-protection policies.- Watch out: Kubernetes Operators introduce their own failure modes—tight reconciliation loops can trigger OCI
429 TooManyRequeststhrottling, and naivecpuCoreCountreconciliation will fight OCI Autonomous Auto-Scaling.
Situation
Enterprise platform teams running workloads on Oracle Cloud Infrastructure (OCI) manage heterogeneous database fleets: VM DB Systems, Bare Metal DB Systems, Exadata Cloud Service, and Autonomous Database instances. These databases anchor transactional ledgers, ERP systems, and customer-facing APIs.
To standardize provisioning, platform teams typically adopt HashiCorp Terraform with the oracle/oci provider. Shared HCL modules encapsulate Virtual Cloud Networks (VCNs), private database subnets, Network Security Groups (NSGs), backup policies, and OCI Vault keys. Application teams submit pull requests with variable overrides, and CI/CD runners execute terraform plan and terraform apply against a remote state file (terraform.tfstate).
At small scale—a few static databases managed by one infrastructure squad—this push-based workflow is predictable. As the estate grows across dozens of product teams making concurrent schema, compute, and network changes, the mismatch between Terraform’s point-in-time graph execution and long-lived, stateful database operations surfaces as pipeline queues and production risk.
The Problem
Governing a large OCI database fleet through monolithic Terraform workspaces exposes four structural constraints:
- The
ForceNewReplacement Constraint: In theoracle/ociTerraform provider, core creation-time attributes nested insideoci_database_db_system(db_home.database.db_name,character_set,nchar_character_set,availability_domain, andshapetransitions across incompatible families) cannot be modified in place via OCI’s update APIs. Terraform marks these attributes asforces replacement. If a shared module refactor or variable typo alters one of those fields across multiple databases,terraform planschedules a destroy-and-recreate (TerminateDbSystemfollowed byLaunchDbSystem). Under review fatigue on a massive plan output, approving that apply permanently destroys live databases and forces emergency point-in-time recovery. - Exclusive State-Lock Contention: Provisioning an Oracle RAC DB System or Exadata VM cluster on OCI routinely takes 45 to 90 minutes while OCI allocates block volumes, formats Grid Infrastructure ASM disk groups, and initializes database instances. Throughout the apply, Terraform holds an exclusive lock on the workspace’s
terraform.tfstate(when using a locking backend such as Terraform Cloud, OCI Resource Manager, or a lock-enabled backend). Every other team targeting that workspace is blocked withError acquiring the state lockuntil the storage operation finishes. Conversely, teams that store state in OCI Object Storage via its S3-compatible API without an external DynamoDB-compatible lock table lose state locking altogether—exposing concurrent applies to silent state corruption. - Out-of-Band Drift Collisions: Production incidents force out-of-band console changes. During a traffic spike, an on-call engineer scales an Autonomous Database from 4 OCPUs to 16 OCPUs in the OCI Console to relieve CPU saturation. Later, another engineer merges an unrelated PR updating a cost-center tag in Git. Terraform reads the live state (
16OCPUs), compares it to Git (4OCPUs), treats the emergency mitigation as configuration drift, and scales the database back down to4OCPUs—re-triggering the outage. - Absence of Continuous Self-Healing: Terraform only runs when a CI/CD pipeline is triggered. If an engineer weakens an NSG ingress rule, disables automatic backups, or changes a Vault key binding directly in OCI, Terraform detects nothing until the next commit days or weeks later.
How can database platform architects eliminate monolithic state-lock bottlenecks and accidental ForceNew terminations while adding continuous, self-healing drift control for OCI databases?
Options Considered
Platform teams evaluating how to fix monolithic Terraform pipelines generally compare four architectures:
| Option | Mechanism | What It Gets Right | Where It Breaks | Verdict |
|---|---|---|---|---|
| Monolithic Terraform Workspace | Single root module and shared tfstate | Centralized governance and module reuse | 45–90 minute state locks and multi-DB ForceNew blast radius | Rejected |
| Per-Database Split Workspaces | One state file per database instance | Isolates state locks and plan diffs to one DB | Remains point-in-time push execution; zero continuous drift healing | Partial |
| OCI Resource Manager Stacks | Managed Terraform execution inside OCI | Eliminates self-hosted runners and state setup | Retains HCL ForceNew semantics; drift detection is still manual | Partial |
| Terraform Network + K8s Operator | Terraform owns VCN/subnets; OSOK/OraOperator owns DBs | Per-DB etcd keys, zero global locks, continuous 60s reconciliation | Requires running HA OKE control plane and tuning OCI API rate limits | Chosen |
Splitting Terraform into per-database workspaces solves the shared state-lock queue, and OCI Resource Manager removes runner maintenance and provides on-demand drift reports, but neither gives you a continuous control loop. Both remain vulnerable to out-of-band console drift reverting on unrelated commits and lack Kubernetes-native admission webhooks that reject immutable-field edits before they reach a plan phase. Separating responsibilities—Terraform for slow-changing VCNs, subnets, and Exadata racks, and a Kubernetes Operator for database lifecycles, start/stop schedules, and OCPU scaling—gives each tool the workload it was built for.
The Kubernetes Operator Architecture
In the hybrid control-plane architecture, a dedicated, multi-AZ Oracle Container Engine for Kubernetes (OKE) management cluster runs the OCI Service Operator for Kubernetes (OSOK) or the Oracle Database Operator for Kubernetes (OraOperator) under the database.oracle.com API group. Application teams declare database specifications as Kubernetes Custom Resources (CRDs) synced via GitOps (such as ArgoCD), while the controller continuously reconciles desired state in etcd against live OCI APIs.
1. Declarative Custom Resource and Admission Guards
Each database is represented as an independent Custom Resource in its owning namespace (kubectl explain autonomousdatabase.spec confirms the exact schema for your installed operator release):
# Illustrative resource shape. Oracle's OraOperator AutonomousDatabase CRD nests these
# fields under spec.details and its apiVersion differs by release; check the CRD you install.
apiVersion: database.oracle.com/v1beta1
kind: AutonomousDatabase
metadata:
name: billing-core-db
namespace: finance-platform
annotations:
# Enforced by Kyverno/OPA admission policy to block accidental kubectl delete
database.oracle.com/termination-protection: "true"
spec:
compartmentId: "ocid1.compartment.oc1..aaaaaaaexample"
displayName: "Billing Core Production"
dbName: "BILLING"
cpuCoreCount: 8
dataStorageSizeInTBs: 4
dbWorkload: "OLTP"
isAutoScalingEnabled: true
licenseModel: "BRING_YOUR_OWN_LICENSE"
adminPassword:
k8sSecret:
name: billing-db-admin-secret
Two mechanisms prevent the “15,000-line plan” disaster:
- Admission Webhook Validation: A Kubernetes
ValidatingWebhookConfiguration(or Kyverno/OPA policy) inspects everyUPDATEandDELETEonAutonomousDatabaseandDbSystemresources. Any commit attempting to mutate immutable fields (dbName,characterSet,compartmentId) is rejected synchronously atkubectl apply/ ArgoCD sync time—never queued for a destructive replacement. - Namespace and
etcdIsolation: Because each database is its own key inetcd, modifyingbilling-core-dbcannot touch databases in any other namespace, andetcdserializes concurrent updates across hundreds of teams in milliseconds without a global state lock.
2. Asynchronous WorkRequest Reconciliation Loop
Because OCI database operations (provisioning, storage expansion, cloning) are asynchronous and take minutes to hours, a production controller pattern must never block a worker goroutine waiting for completion. Instead, the reconciler submits the OCI SDK call, records the returned opc-work-request-id in .status, and returns ctrl.Result{RequeueAfter: 30 * time.Second}:
// Illustrative controller-runtime reconciliation pattern for OCI AutonomousDatabase
func (r *ADBReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
adb := &databasev1beta1.AutonomousDatabase{}
if err := r.Get(ctx, req.NamespacedName, adb); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
ociResp, err := r.DatabaseClient.GetAutonomousDatabase(ctx, database.GetAutonomousDatabaseRequest{
AutonomousDatabaseId: &adb.Status.OCID,
})
if err != nil {
return r.createOrBindAutonomousDatabase(ctx, adb)
}
actual := ociResp.AutonomousDatabase
if actual.LifecycleState == database.AutonomousDatabaseLifecycleStateUpdating ||
actual.LifecycleState == database.AutonomousDatabaseLifecycleStateProvisioning {
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
// Only reconcile OCPU count when Autonomous Auto-Scaling is disabled
if !adb.Spec.IsAutoScalingEnabled && *actual.CpuCoreCount != adb.Spec.CpuCoreCount {
_, err := r.DatabaseClient.UpdateAutonomousDatabase(ctx, database.UpdateAutonomousDatabaseRequest{
AutonomousDatabaseId: actual.Id,
UpdateAutonomousDatabaseDetails: database.UpdateAutonomousDatabaseDetails{
CpuCoreCount: &adb.Spec.CpuCoreCount,
},
})
if err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
return ctrl.Result{RequeueAfter: 60 * time.Second}, nil
}
Notice the guard on IsAutoScalingEnabled: if OCI Autonomous Auto-Scaling is active, OCI dynamically scales compute up to 3x the base OCPU count under load. A naive controller that compares *actual.CpuCoreCount != adb.Spec.CpuCoreCount without checking auto-scaling status will fight OCI’s autoscaler every 60 seconds.
3. Finalizers and Deletion Governance
In Kubernetes, deleting a Custom Resource (kubectl delete -f adb.yaml or kubectl delete namespace) triggers controller cleanup via metadata.finalizers. Without a policy gate, a finalizer will faithfully call OCI’s DeleteAutonomousDatabase API. To prevent accidental data loss:
- Admission-Level Delete Block: Enforce a Kyverno or OPA Gatekeeper policy that denies
DELETErequests on anyAutonomousDatabasecarryingdatabase.oracle.com/termination-protection: "true". Admission policies intercept the API call before the Kubernetes API server setsmetadata.deletionTimestamp, so the controller never enters its finalizer deletion branch. - Orphan vs. Terminate Semantics: Support explicit
unbind/ orphan behavior so detaching a Kubernetes object from the cluster does not automatically terminate the underlying OCI database unless an authorized break-glass annotation is removed first. Even if a termination call reaches OCI, Autonomous Database retains terminated instances for a short recovery window, though DB Systems terminate immediately without a soft-delete grace period.
How It Rolls Out
Migrating an existing Terraform-managed OCI database estate to a Kubernetes Operator requires four staged phases so live databases are never recreated during cutover:
- Phase 01 — Freeze Database Terraform Modules: Add
lifecycle { prevent_destroy = true }to everyoci_database_db_systemandoci_database_autonomous_databaseblock in existing Terraform code. Keep VCNs, subnets, route tables, and NSGs in Terraform. Gate:terraform planshows zero replacements or destroys across all workspaces. - Phase 02 — Deploy HA OKE Control Plane and Policies: Provision a dedicated, multi-AZ OKE management cluster running OSOK /
OraOperatorwith exponential backoff configured on the controller manager. Install Kyverno/OPA policies blocking immutable field edits and protectedDELETEoperations. Gate: dry-run webhook tests rejectdbNameedits and protected deletes. - Phase 03 — Bind Existing Databases by OCID: Author CRDs referencing each live database’s existing
ocid1.autonomousdatabase...(binding/adopting the existing OCI resource rather than creating a new one), verify the operator populates.status.lifecycleState = AVAILABLEand confirms zero pendingWorkRequestIDs, and then runterraform state rm <resource_address>to detach the database from Terraform state without callingTerminateDbSystem. Always run a follow-upterraform planin the legacy workspace to confirm Terraform no longer tracks the detached database. Rollback: re-import the OCID into Terraform viaterraform import. - Phase 04 — Enable GitOps Sync and Rate-Limit Monitoring: Point ArgoCD at the CRD repository with
RequeueAftertuned to 60–120 seconds, and alert on OCI429 TooManyRequestsAPI responses in controller metrics. Rollback: pause ArgoCD auto-sync while keeping the database online in OCI.
In Practice
The architectural division between Terraform and Kubernetes Operators is reflected directly in Oracle’s own tooling and multi-cloud reference architectures:
- OCI Service Operator for Kubernetes (OSOK) &
OraOperator: Oracle maintains bothoracle/oci-service-operator(for OCI control-plane resources includingAutonomousDatabase) andoracle/oracle-database-operator(forAutonomousDatabase, containerized databases, Sharding, and Data Guard topologies across OKE, AKS, and EKS). Both follow the controller-runtime pattern: each resource is reconciled independently inetcd, eliminating shared state locks, and long-running OCI operations are tracked asynchronously via OCIWorkRequestpolling rather than holding global locks.OraOperatoralso automates wallet and mTLS secret synchronization directly into application namespaces, so rotating database connection wallets updates KubernetesSecretobjects without requiring manual DBA distribution. - Terraform
oracle/ociForceNewMechanics: In the officialoracle/ociprovider documentation foroci_database_db_system, attributes underdb_home.databasesuch asdb_nameandcharacter_setare documented as creation-time parameters that cannot be updated in place—meaning any HCL change to those fields forces resource replacement. Pairingprevent_destroy = truein Terraform with admission-webhook validation in Kubernetes is the standard defense against accidental replacement. Even when a team attempts to recover from aForceNewplan usingterraform state mvor targeted-replace, the underlying HCL coupling between network, compute, and database blocks in a shared root module keeps review risk high. - Multi-Cloud Split (Oracle Database@Azure and Database@AWS): In Oracle’s multi-cloud deployments co-located inside Azure and AWS data centers, macro infrastructure—Exadata Infrastructure, Exadata VM Clusters, and ODB networks—is provisioned via Terraform (
azurerm/azapi,aws, andociproviders), whileOraOperatorruns inside AKS or EKS to manage Kubernetes-plane database lifecycles, wallet secrets, and application connectivity.
Where It Breaks
| Failure Scenario | Failure Mechanism | Operational Consequence | Mitigation |
|---|---|---|---|
OCI API 429 Reconciliation Storm | Tight error requeue loop across hundreds of CRDs | Exhausts OCI tenancy API rate limits, blocking all cloud automation | Set RequeueAfter to 60–120s and enable exponential backoff with jitter |
| Auto-Scaling OCPU Thrashing | Controller enforces static cpuCoreCount while isAutoScalingEnabled is true | Operator scales DB down while OCI scales up under load | Skip cpuCoreCount drift updates when auto-scaling is enabled |
| Namespace Delete Triggers Termination | kubectl delete namespace runs controller finalizer without policy guard | Operator calls OCI delete API against production database | Enforce Kyverno/OPA delete blocks on termination-protection: "true" |
Synchronous WorkRequest Blocking | Controller thread blocks waiting 60m for ASM/storage provisioning | Exhausts MaxConcurrentReconciles worker pool; other DBs stall | Poll WorkRequest status asynchronously via RequeueAfter |
| OKE Control Plane Outage | Management cluster loses etcd quorum or API availability | Existing OCI DBs stay online, but all GitOps changes/scaling halt | Run Operator on dedicated multi-AZ OKE cluster; back up etcd |
| Immutable Field Reconcile Loop | User edits dbName without admission webhook; OCI rejects update | CRD stuck in Error state, firing continuous failed API calls | Reject immutable-field mutations synchronously in ValidatingWebhook |
| Plaintext Secrets in Git | Admin password committed in CRD YAML instead of Secret/Vault ref | Credentials exposed in Git history and ArgoCD diffs | Use External Secrets Operator or OCI Vault references |
Key Takeaways
- Use Terraform for networks, Operators for databases: Terraform excels at static VCNs, subnets, and Exadata racks; Kubernetes Operators excel at per-database day-2 lifecycles without global
tfstatelocks. - Prevent
ForceNewreplacement before it hitsapply:oci_database_db_systemfields likedb_nameandcharacter_setforce full destruction on change; block those edits in admission webhooks and keepprevent_destroy = trueon legacy Terraform blocks. - Poll OCI
WorkRequests asynchronously: Never block controller worker threads on 45–90 minute RAC or storage operations; returnRequeueAfterand check lifecycle state on the next tick. - Respect OCI Autonomous Auto-Scaling: Reconcile
cpuCoreCountonly whenisAutoScalingEnabledisfalse, or the Operator will actively fight OCI’s elastic compute scaling. - Detach via
terraform state rm, neverdestroy: When migrating live OCI databases from Terraform to OSOK/OraOperator, bind the existing OCID in the CRD first and remove the resource from Terraform state cleanly.
What to Do Next
- Problem: Monolithic Terraform workspaces lock out concurrent database deployments and expose live OCI databases to
ForceNewreplacement and console drift reverts. - Solution: Freeze database resources in Terraform with
prevent_destroy = true, keep networking in Terraform, and move database lifecycles to OSOK orOraOperatorbehind admission webhooks. - Proof: Audit your existing
oci_database_db_systemandoci_database_autonomous_databaseTerraform states for shared lock wait times and anyforces replacementattributes. - Action: Deploy OSOK or
OraOperatorin a non-production OKE cluster this week, bind one non-prodAutonomousDatabaseby OCID, and verify that an out-of-band console tag or OCPU change reconciles without touching other namespaces.
Sources to Verify
- Oracle Cloud Infrastructure Documentation: OCI Service Operator for Kubernetes (OSOK) (
docs.oracle.com/en-us/iaas/Content/ContEng/Tasks/contengusingosok.htm) - Oracle Database Operator for Kubernetes (
oracle/oracle-database-operator): AutonomousDatabase CRD & Controller (github.com/oracle/oracle-database-operator) - Terraform Registry (
oracle/oci):oci_database_db_systemResource Reference (registry.terraform.io/providers/oracle/oci/latest/docs/resources/database_db_system) - Kubernetes Documentation: The Operator Pattern & Validating Admission Webhooks (
kubernetes.io/docs/concepts/extend-kubernetes/operator/)
Interactive tools for this topic