When a database deployment spans two hyperscaler control planes, complexity grows combinatorially: provisioning Oracle Database@Azure requires Microsoft’s ARM API and Oracle’s OCI API to succeed in strict dependency order across asynchronous propagation delays, with no native cross-cloud transaction rollback.

TL;DR

  • Problem: Linear scripts and single-pass IaC runs fail across Azure ARM and OCI Database APIs when subnet delegation propagation lags, OIDC tokens expire mid-build, or OCI rejects capacity after Azure VNets are already billed.
  • Answer: Orchestrate the cross-cloud sequence with a Temporal durable state machine—driving Terraform/ARM for Azure networking and OCI APIs (via TokenExchangeSigner) for Exadata and CDBs—with async heartbeats and compensating cleanup.
  • Watch out: Never use blocking time.sleep() inside async Temporal activities, poll until all three SCAN IPs populate before writing Private DNS records, and strip subnet delegations before deleting orphaned subnets.

Durable state machines prevent orphaned dual-cloud builds

Situation

Oracle Database@Azure runs OCI-managed Exadata infrastructure physically inside Microsoft Azure data centers, projecting vNICs into an Azure Delegated Subnet (Oracle.Database/networkAttachments). Even with native Azure Resource Manager (Oracle.Database) integration in Terraform azurerm v4.x (azurerm_oracle_exadata_infrastructure and azurerm_oracle_cloud_vm_cluster), enterprise provisioning still spans two administrative planes: Azure ARM owns VNets, delegated subnets, Private DNS, and NSGs, while OCI owns Exadata compute/storage lifecycle, CDB/PDB creation, Data Guard, and Oracle-level operations.

This split also divides quotas and billing: Microsoft Azure enforces subscription-level VNet, subnet delegation, and Private DNS quotas, while OCI enforces compartment-level Exadata infrastructure, OCPU, and storage-server limits under Oracle Universal Credits or Azure Marketplace offers. A pre-flight check that validates only Azure quotas will still fail 30 minutes later if the target OCI compartment has zero remaining Exadata compute capacity.

Provisioning ComponentControlling PlaneFailure & Latency Surface
Azure VNet and Delegated SubnetAzure Resource ManagerAPI throttling, CIDR overlap, regional delegation propagation lag
Exadata InfrastructureOracle.Database ARM / OCI APILong-running async build, zone capacity limits, OCID generation
Exadata VM ClusterOracle.Database ARM / OCI APISSH key format checks, GI version, delayed SCAN IP assignment
Azure Private DNS & NSGsAzure Resource ManagerMissing VNet DNS links, stale or empty SCAN IP list
CDB / PDB & Backup PolicyOCI Database APIStorage quota, character set mismatch, PDB limits

The structural dependency loop crosses clouds twice: OCI infrastructure and VM cluster provisioning depend on the Azure delegated subnet reference, while Azure Private DNS A-records and firewall rules depend on the three SCAN IP addresses returned only after the VM cluster finishes provisioning.

The Problem

Without a durable coordination layer, cross-cloud provisioning fails across three recurring boundaries.

Constraint 1: Asynchronous Propagation Gaps. Azure’s subnet delegation API often returns HTTP 200 before delegation state finishes propagating across Azure’s regional network fabric. Firing the Exadata infrastructure or VM cluster creation call immediately after ARM returns 200 triggers intermittent “subnet not delegated” errors under regional load. Similarly, a VM cluster can report AVAILABLE briefly before all three SCAN IP addresses are populated in its API response; reading scan_ip_ids too early writes incomplete DNS records.

Constraint 2: Cross-Cloud Identity Bridging. Automation runners hosted in Azure authenticate natively with Microsoft Entra Managed Identity, whereas OCI Database API calls require an OCI principal. Embedding static OCI API private keys inside CI/CD runners creates key-rotation debt, secret-sprawl risk, and fragmented audit trails. Bridging identities cleanly requires OIDC Workload Identity Federation—exchanging an Entra Managed Identity JWT for a short-lived OCI User Principal Session Token (UPST) via oci.auth.signers.TokenExchangeSigner, while ensuring tokens refresh cleanly across 60-minute provisioning polls.

Constraint 3: Orphaned Infrastructure and Duplicate Allocation on Partial Failure. If Azure VNet, subnet delegation, and NAT/DNS resources succeed, Azure billing and CIDR consumption begin immediately. If the subsequent OCI Exadata or CDB step fails due to regional capacity limits or SSH key validation errors (OCI VM clusters enforce specific OpenSSH RSA key formats and fail late if an unsupported key is passed), a linear script or crashed CI runner leaves orphaned Azure networking behind—and Azure ARM refuses to delete a delegated subnet unless the delegation block is explicitly stripped first. Conversely, if a client-side HTTP timeout occurs right after OCI accepts CreateCloudExadataInfrastructure, a blind retry without an opc_retry_token or persisted OCID can allocate a duplicate Exadata infrastructure rack.

Three constraints break naive dual-cloud pipelines

How do platform teams orchestrate Oracle Database@Azure builds across Azure ARM and OCI APIs—handling propagation delays, federated auth, and saga cleanup—without manual console intervention?

Options Considered

Platform teams evaluate four approaches to cross-cloud Exadata provisioning.

OptionDependency HandlingFailure CleanupFleet GovernanceVerdict
1. Dual-Portal ClickOpsManual copy-paste of IDsManual teardownZero auditabilityRejected: error-prone, unrepeatable
2. Linear CI/CD Bash/PythonSequential script stepsNone if runner crashesWeak state trackingRejected: orphans VNets on timeout
3. Terraform azurerm v4.x OnlyNative azurerm_oracle_* graphterraform destroy on retryGood for static infra; weak on CDB/sagasPartial: pair with orchestrator
4. Temporal + Terraform / SDKsDurable state machine + pollingExplicit saga compensationFleet catalog + rate limitsChosen for fleet-scale provisioning

Option 1 (Dual-Portal ClickOps) forces operators to switch between Azure Portal and OCI Console, copying subnet IDs and SCAN IPs by hand. It cannot enforce standardized tagging or repeatable CIDR checks.

Option 2 (Linear CI/CD Runner) runs Azure CLI and OCI CLI sequentially inside a single pipeline job. Because Exadata infrastructure and VM cluster builds routinely span 60+ minutes, runner timeouts or worker restarts lose in-memory resource IDs and leave half-built environments behind.

Option 3 (Terraform azurerm v4.x Only) leverages azurerm_oracle_exadata_infrastructure and azurerm_oracle_cloud_vm_cluster (or azapi_resource against Oracle.Database when targeting newly released API properties) to keep Azure and Exadata hardware in one dependency graph. However, a single terraform apply still faces multi-hour polling timeouts, does not manage OCI-side CDB/PDB and Data Guard lifecycles cleanly, and lacks compensating saga rollbacks when an upstream business gate fails mid-workflow. In addition, if an apply times out in a CI runner, Terraform state locks can remain stuck until manually force-unlocked.

Option 4 (Temporal State Machine + Terraform/SDKs) keeps Terraform for declarative VNet/subnet modules while Temporal owns the multi-hour cross-cloud state machine, persisting every resource ID, heartbeating async polls, enforcing per-region OCI rate limits, and running compensating undelegation cleanup if provisioning aborts.

Temporal plus Terraform beats scripts and raw apply alone

The Dual Control Plane State Machine

The recommended architecture models each Exadata provisioning request as a durable Temporal Workflow backed by a Fleet Catalog. Temporal persists workflow state after every activity completion, surviving worker restarts or network blips without losing the Azure VNet ID, delegated subnet OCID, or Exadata infrastructure OCID.

Temporal orchestrator bridges Azure ARM and OCI APIs

flowchart TD
    A[Provisioning Request — db_name, region, shape, CIDR] --> B[Step 1 — Azure VNet and Subnet via ARM]
    B --> C[Step 2 — Delegate Subnet to Oracle.Database/networkAttachments]
    C --> D[Wait — Poll delegation provisioningState == Succeeded]
    D --> E[Step 3 — Extract Delegated Subnet ID / OCID]
    E --> F[Step 4 — OCI ExadataInfrastructure Provisioning]
    F --> G[Wait — Async Heartbeat Poll until AVAILABLE]
    G --> H[Step 5 — OCI VmCluster Provisioning]
    H --> I[Wait — Async Poll until AVAILABLE and 3 SCAN IPs Populated]
    I --> J[Step 6 — Azure Private DNS A Records for SCAN IPs]
    J --> K[Step 7 — Azure NSG and Firewall Rules for TCP 1521 and 2484]
    K --> L[Step 8 — OCI CDB Creation and Fleet Catalog AVAILABLE]

    F -->|Retry Exhausted| M[Saga Compensation — Undelegate Subnet then Delete VNet]
    M --> N[Alert Platform Team — Zero Orphaned Resources]

Core Orchestration Controls

  1. Non-Blocking Async Polling with Heartbeats and opc_retry_token: Long-running OCI activities (CreateCloudExadataInfrastructure and CreateCloudVmCluster) run as async def Temporal activities using await asyncio.sleep(30) rather than blocking time.sleep(), calling activity.heartbeat(state) on every poll iteration. Passing a deterministic opc_retry_token derived from the Temporal workflow ID guarantees that transient network retries never allocate a duplicate Exadata rack. If a worker pod restarts, Temporal detects the missed heartbeat and resumes polling from the persisted OCID.
  2. Deterministic Workflow Boundaries: All Azure ARM calls, OCI SDK calls, and clock checks live strictly inside @activity.defn functions, keeping @workflow.run deterministic so Temporal can replay event history safely after any worker crash.
  3. Entra-to-OCI Token Exchange (TokenExchangeSigner): Instead of storing static OCI API keys, the automation’s Azure Managed Identity obtains an Entra OIDC token and passes it to OCI’s TokenExchangeSigner, which exchanges it for a short-lived UPST token scoped to the target OCI compartment. Token refresh runs automatically inside the signer, preventing 401 failures during 60-minute builds.
  4. Global Per-Region Rate Limiting: Bulk provisioning requests pass through a Temporal rate limiter or Redis token bucket capping concurrent CreateCloudExadataInfrastructure calls per region so parallel workflows do not trigger OCI HTTP 429 throttling.
  5. Undelegate-Before-Delete Compensation and Orphan Reaper: When a saga rollback fires, the cleanup activity explicitly strips the Oracle.Database/networkAttachments delegation from the Azure subnet and awaits completion before calling subnets.begin_delete and virtual_networks.begin_delete. As a defense in depth, a scheduled reconciliation job scans Fleet Catalog entries stuck in PENDING beyond four hours and flags or cleans up Azure VNets that lack a matching Exadata OCID.

How It Rolls Out

Deploying a new Oracle Database@Azure cluster through the state machine executes in four sequential phases with explicit validation gates.

Four-phase workflow sequences Azure, OCI, and DNS

  1. Phase 1 — Pre-Flight Quotas, VNet & Delegation Gate: Verify that the Oracle.Database resource provider is registered in the Azure subscription, confirm OCI compartment Exadata limits have headroom, pre-validate the RSA OpenSSH key format (ssh-keygen -l), and confirm the /24 CIDR does not overlap Hub or Spoke VNets. Then create the Database VNet, apply Oracle.Database/networkAttachments delegation, and poll ARM until both provisioningState and delegations[0].provisioningState equal Succeeded. Rollback: strip delegation and delete VNet.
  2. Phase 2 — Exadata Infrastructure & VM Cluster: Submit infrastructure and VM cluster creation (either via azurerm_oracle_* / Oracle.Database ARM or OCI Database API) using federated TokenExchangeSigner auth, polling asynchronously with Temporal heartbeats until AVAILABLE. Rollback: trigger compensating cleanup of Azure networking if infrastructure creation fails before allocation.
  3. Phase 3 — SCAN IP Extraction & Private DNS: Poll the VM cluster until all three SCAN IP addresses are populated, write the Azure Private DNS A-records, verify VNet DNS links exist for both Hub and Database VNets, and open TCP 1521/2484 firewall/NSG rules. Rollback: remove DNS A-records and revert rule changes.
  4. Phase 4 — CDB Provisioning & Catalog Activation: Create the initial CDB/PDBs, verify SQL*Net connectivity to the SCAN hostname from a spoke probe, apply standardized cost-center tags across both Azure and OCI, and flip the Fleet Catalog status from PENDING to AVAILABLE.

In Practice

Based on Temporal’s Python SDK (temporalio), Azure’s ManagedIdentityCredential, and OCI’s TokenExchangeSigner workload identity federation, the workflow separates durable orchestration from cloud-specific activities.

1. Temporal Workflow Definition

from dataclasses import dataclass
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy

@dataclass
class ProvisioningRequest:
    db_name: str
    azure_region: str
    vnet_cidr: str
    delegated_subnet_cidr: str
    exadata_shape: str  # e.g., "Exadata.X9M"
    ocpu_count: int
    storage_tb: int
    ssh_public_key: str

@workflow.defn
class OracleAzureProvisioningWorkflow:
    @workflow.run
    async def run(self, req: ProvisioningRequest) -> dict:
        resource_ids = {}
        try:
            net = await workflow.execute_activity(
                create_azure_vnet_and_delegation,
                args=[req.azure_region, req.vnet_cidr, req.delegated_subnet_cidr],
                start_to_close_timeout=timedelta(minutes=15),
                retry_policy=RetryPolicy(maximum_attempts=5, backoff_coefficient=2.0),
            )
            resource_ids.update(net)

            infra_ocid = await workflow.execute_activity(
                provision_oci_exadata_infrastructure,
                args=[net["oracle_cloud_subnet_id"], req.azure_region, req.exadata_shape],
                start_to_close_timeout=timedelta(hours=2),
                heartbeat_timeout=timedelta(minutes=5),
                retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(minutes=5)),
            )
            resource_ids["infra_ocid"] = infra_ocid

            cluster = await workflow.execute_activity(
                provision_oci_vmcluster,
                args=[infra_ocid, req.ocpu_count, req.storage_tb, req.ssh_public_key],
                start_to_close_timeout=timedelta(hours=3),
                heartbeat_timeout=timedelta(minutes=5),
                retry_policy=RetryPolicy(maximum_attempts=2, initial_interval=timedelta(minutes=10)),
            )
            resource_ids["vmcluster_ocid"] = cluster["ocid"]

            await workflow.execute_activity(
                configure_azure_dns_and_nsg,
                args=[req.db_name, cluster["scan_ips"], net["vnet_id"]],
                start_to_close_timeout=timedelta(minutes=15),
            )
            return resource_ids
        except Exception:
            if "vnet_id" in resource_ids and "infra_ocid" not in resource_ids:
                await workflow.execute_activity(
                    cleanup_azure_resources_on_failure,
                    args=[resource_ids["vnet_id"], resource_ids["subnet_id"]],
                    start_to_close_timeout=timedelta(minutes=10),
                )
            raise

2. Async OCI Polling with TokenExchangeSigner and Heartbeats

To eliminate static .oci/config private keys, configure an OCI IAM Identity Domain OIDC trust pointing to your Microsoft Entra ID issuer (https://login.microsoftonline.com/<tenant-id>/v2.0) and grant an OCI IAM policy to the federated workload identity on the target database compartment. Inside the Temporal worker, ManagedIdentityCredential fetches a short-lived Entra token and TokenExchangeSigner exchanges it for an OCI User Principal Session Token (UPST) automatically.

import asyncio
import oci
from azure.identity import ManagedIdentityCredential
from temporalio import activity

@activity.defn
async def provision_oci_exadata_infrastructure(
    azure_subnet_ocid: str, azure_region: str, shape: str
) -> str:
    # Exchange Azure Entra Managed Identity JWT for an OCI UPST token
    azure_token = ManagedIdentityCredential().get_token(OCI_FEDERATION_SCOPE).token
    signer = oci.auth.signers.TokenExchangeSigner(
        jwt_or_func=lambda: ManagedIdentityCredential().get_token(OCI_FEDERATION_SCOPE).token,
        oci_domain_id=OCI_DOMAIN_URL,
        client_id=OCI_APP_CLIENT_ID,
    )
    db_client = oci.database.DatabaseClient({}, signer=signer)

    resp = db_client.create_cloud_exadata_infrastructure(
        oci.database.models.CreateCloudExadataInfrastructureDetails(
            availability_domain=map_azure_region_to_oci_ad(azure_region),
            compartment_id=OCI_COMPARTMENT_ID,
            display_name=f"exadata-{azure_region}",
            shape=shape,
            compute_count=2,
            storage_count=3,
        )
    )
    infra_ocid = resp.data.id

    for _ in range(120):
        infra = db_client.get_cloud_exadata_infrastructure(infra_ocid).data
        activity.heartbeat(infra.lifecycle_state)
        if infra.lifecycle_state == "AVAILABLE":
            return infra_ocid
        if infra.lifecycle_state in ("FAILED", "TERMINATED"):
            raise RuntimeError(f"ExadataInfrastructure {infra_ocid} state={infra.lifecycle_state}")
        await asyncio.sleep(30)

    raise TimeoutError(f"ExadataInfrastructure {infra_ocid} timed out")

3. Compensating Undelegation Cleanup

Because Temporal activities may retry on transient ARM 429 or 503 responses, the cleanup activity must be idempotent: if the subnet or VNet was already deleted on an earlier attempt, handle ResourceNotFoundError as a clean no-op rather than failing the compensation step. Notice also that delegations must be cleared and persisted via begin_create_or_update before begin_delete is called on the subnet, otherwise Azure ARM rejects the deletion with InUseSubnetCannotBeDeleted. Similarly, during initial provisioning, the ARM activity must poll client.subnets.get(...) until both subnet.provisioning_state and subnet.delegations[0].provisioning_state report "Succeeded" (followed by a short regional settle wait) before returning the subnet OCID to the OCI provisioning activity.

@activity.defn
async def cleanup_azure_resources_on_failure(resource_group: str, vnet_name: str, subnet_name: str) -> None:
    import azure.mgmt.network as network_mgmt
    from azure.identity import ManagedIdentityCredential

    client = network_mgmt.NetworkManagementClient(ManagedIdentityCredential(), AZURE_SUBSCRIPTION_ID)
    subnet = client.subnets.get(resource_group, vnet_name, subnet_name)
    subnet.delegations = []  # Strip delegation before ARM permits subnet deletion
    client.subnets.begin_create_or_update(resource_group, vnet_name, subnet_name, subnet).result()
    client.subnets.begin_delete(resource_group, vnet_name, subnet_name).result()
    client.virtual_networks.begin_delete(resource_group, vnet_name).result()

4. Native Terraform azurerm v4.x Option

For teams managing static Exadata hardware declaratively alongside Azure VNets, azurerm v4.x provides azurerm_oracle_exadata_infrastructure and azurerm_oracle_cloud_vm_cluster (wrapping Oracle.Database ARM APIs). Because Terraform links cloud_exadata_infrastructure_id between the two resources, terraform destroy automatically deletes the VM cluster before tearing down the underlying Exadata infrastructure. Even when Terraform manages those two resources, Temporal remains valuable for orchestrating pre-flight CIDR/SSH checks, waiting on DNS propagation, and automating CDB/PDB creation and Fleet Catalog registration.

Where It Breaks

Dual-control-plane workflows fail at propagation boundaries, token lifetimes, and cleanup ordering. Because every provisioning run crosses two independent cloud APIs, log correlation requires capturing both Azure’s x-ms-request-id and OCI’s opc-request-id inside Temporal’s structured activity logs; without both correlation IDs, support escalations across Microsoft and Oracle stall while teams reconstruct which cloud rejected the call. In addition, tag schemas must be normalized at the Temporal workflow boundary before either cloud API is invoked so FinOps chargeback reports can reconcile Azure networking charges against OCI Exadata compute consumption.

Where dual-control-plane provisioning breaks

Failure ModeBreaks HowDetectMitigate
Delegation Propagation RaceOCI API called immediately after Azure ARM returns 200; regional fabric not yet synced.Exadata creation fails with “subnet not delegated” error.Poll delegations[0].provisioningState == Succeeded + settle wait.
OIDC Token Expiry Mid-PollExchanged OCI UPST expires during a 60-minute cluster build loop.OCI polling call fails with HTTP 401 mid-workflow.Pass refreshable token callback to TokenExchangeSigner.
Blocked Event Loop in Async ActivityUsing time.sleep(30) inside async def blocks Temporal heartbeats.Temporal marks activity timed out and spawns duplicate build.Use await asyncio.sleep(30) and call activity.heartbeat().
SCAN IP Assignment DelayVmCluster reports AVAILABLE before all three SCAN IPs populate.Azure Private DNS A-record creation fails on empty IP list.Poll scan_ip_ids until length == 3 before DNS activity.
Blocked Subnet CleanupCompensating delete calls subnets.begin_delete without removing delegation.Azure ARM rejects deletion with InUseSubnetCannotBeDeleted.Strip subnet.delegations = [] and update before deleting subnet.
Cross-Cloud Tag DriftAzure and OCI resources receive mismatched cost-center tag keys.Chargeback reports fail to reconcile Azure and OCI billing.Inject shared {environment, cost-center, db-name} map from catalog.

Key Takeaways

  • Provisioning Oracle Database@Azure spans two independent control planes (Azure ARM and OCI) with a bidirectional dependency loop: OCI needs the delegated subnet, and Azure DNS needs OCI’s SCAN IPs.
  • Wrap cross-cloud provisioning in a Temporal durable workflow so multi-hour builds survive worker restarts and execute compensating undelegation cleanup if OCI fails.
  • Use oci.auth.signers.TokenExchangeSigner with an Entra Managed Identity token callback rather than static OCI API keys, avoiding secret sprawl and mid-poll 401 expirations.
  • Inside async def Temporal activities, always use await asyncio.sleep() with activity.heartbeat() instead of blocking time.sleep() so workers stay responsive.
  • Strip Oracle.Database/networkAttachments delegations from an Azure subnet before attempting to delete the subnet or VNet during rollback.

What to Do Next

  • Problem: Linear CI scripts and single-pass Terraform runs fail across Azure ARM and OCI APIs when subnet delegation lags, tokens expire mid-poll, or partial failures leave orphaned VNets behind.
  • Solution: Coordinate Azure networking, OCI Exadata/VmCluster/CDB provisioning, and Private DNS updates inside a Temporal durable workflow using TokenExchangeSigner federation, async heartbeats, and saga undelegation cleanup.
  • Proof: Run a test workflow in a non-production subscription and intentionally fail the OCI step (or trigger cancellation) to verify that the compensating activity strips the subnet delegation and deletes the VNet cleanly with zero orphaned resources.
  • Action: Audit your current Oracle Database@Azure automation this week: replace any static OCI API keys with Entra-to-OCI TokenExchangeSigner federation, and add an explicit delegations[0].provisioningState poll before invoking Exadata creation.