Treating cloud virtual machines and persistent storage volumes as tightly coupled infrastructure is a critical reliability failure; in cloud database architectures, compute instances must be disposable while persistent Oracle ASM storage remains self-describing and immune to procedural Day 1 automation.

TL;DR

  • Problem: Procedural Ansible Day 1 playbooks assume attached disks are blank and rely on volatile Linux /dev/sdX names, so re-running them after a hypervisor replacement overwrites Oracle ASM Block 0 headers and destroys production diskgroups.
  • Answer: Bake Oracle Grid Infrastructure and Database binaries into an immutable Azure Compute Gallery image, bind disks by hardware SCSI LUN via udev, and run a fail-closed cloud-init bootstrap agent that inspects kfed Block 0 headers before choosing Day 1 creation, Day 2 mount, or quarantine.
  • Watch out: Partial LUN attachments during Azure VM replacement or stale udev races can trigger false blank-disk detection unless the agent verifies expected LUN counts and runs udevadm settle first.

Verify ASM headers before touching any block device

Situation

Enterprise engineering teams deploying Oracle Database onto Microsoft Azure Infrastructure-as-a-Service (IaaS) routinely use Oracle Automatic Storage Management (ASM) to stripe database files across raw block devices without OS filesystem overhead. To automate provisioning, platform teams typically pair Terraform with procedural Ansible playbooks:

  1. Infrastructure Provisioning (Terraform): Terraform deploys a constrained-core Azure VM (such as Standard_E32-8s_v5) and attaches multiple Azure Managed Disks (PremiumV2_LRS or UltraSSD_LRS) across dedicated SCSI Logical Unit Numbers (LUNs) for +DATA and +RECO.
  2. Procedural Configuration (Ansible): An Ansible playbook connects over SSH to the new VM, iterates over /dev/sd* block devices, runs parted or fdisk to initialize partition tables, writes udev rules for grid:asmadmin ownership, installs Grid Infrastructure, initializes ASM disks, and runs DBCA to create the database.

During initial green-field staging deployments, every disk is genuinely blank, so the procedural pipeline succeeds cleanly. The hidden defect is that the automation encodes Day 1 assumptions into a Day 2 lifecycle.

The Problem

The failure surfaces during the first unplanned Day 2 Azure host hardware fault or automated VM replacement.

Cloud virtual machines are transient compute shells. Physical host hardware faults, uncorrectable DIMM ECC errors, or live-migration failures terminate the VM abruptly, while the attached Azure Managed Disks—persisted independently on Azure Storage clusters—remain intact and contain production data. When self-healing automation replaces the failed VM and reattaches the existing Managed Disks, four concrete constraints break procedural Day 1 playbooks:

  1. Constraint 1 — Block 0 Header Destruction: Procedural playbooks that execute parted --script /dev/sdc mklabel gpt or dd unconditionally overwrite Block 0 of the ASM disk—destroying the kfbh block header and kfdhdb disk header (ORCLDISK provisioning string and allocation unit pointers). While ASM mirrors a backup copy of the disk header in the second Allocation Unit (AU 1, block 254), parted or mkfs writes can also clobber adjacent metadata or trigger immediate diskgroup mount failure, forcing a multi-terabyte RMAN restore from backup.
  2. Constraint 2 — Non-Deterministic Linux /dev/sdX Enumeration: The Linux kernel assigns /dev/sd* letters sequentially as SCSI targets respond during PCI/hv_storvsc bus enumeration, so assignments are not guaranteed across reboots or VM replacements. A volume attached at LUN 10 (+DATA) on the original host can enumerate under a different /dev/sd* letter on the replacement host, causing hardcoded-letter scripts to format the wrong LUN or mix +DATA and +RECO members.
  3. Constraint 3 — Partial LUN Attachment Windows and Detach Leases: During automated VM replacement, Azure’s compute control plane must detach Managed Disks from the failed VM before attaching them to the replacement VM. If the replacement VM boots while one Managed Disk is still detaching, only 3 of 4 +DATA LUNs appear in sysfs at cloud-init startup—and in normal-redundancy diskgroups or external-redundancy configurations, missing a member disk prevents the diskgroup from mounting cleanly.
  4. Constraint 4 — ASMCMD and Tooling Syntax Traps: Scripts written from memory often fail on real Oracle 19c binaries—for example, asmcmd creates diskgroups via asmcmd mkdg <config.xml> (not createdg), and asmcmd expects the ASM instance and diskgroups to be mounted via SQL (ALTER DISKGROUP ... MOUNT) or srvctl, not standalone asmcmd mount on a stopped Oracle Restart stack. Similarly, initializing a multi-terabyte diskgroup with the default 1M Allocation Unit (AU_SIZE) rather than 4M increases ASM extent-map memory pressure in the ASM shared pool.

Day 2 VM replacement destroys data if scripts assume blank disks

How do platform teams architect an automated Azure Oracle VM factory that treats compute as disposable while guaranteeing zero destructive writes against reattached ASM Managed Disks?

Options Considered

Platform teams evaluating Day 1 and Day 2 Oracle storage orchestration on Azure typically consider four approaches.

OptionDevice IdentityDay 2 Rebuild SafetyRecovery SpeedWhy Chosen or Rejected
Ansible Day-1 SSH Playbook/dev/sdX lettersUnsafe (overwrites headers)Fast until data lossRejected: Procedural script assumes blank disks; destroys Block 0 on VM replacement.
Terraform remote-exec Provisioner/dev/sdX or LUNFragile (runs on create)ModerateRejected: Requires SSH from CI runner and breaks idempotency on VM taint/replace.
Manual DBA Storage Attachudev + human checkSafe (human inspects)Slow (manual paging)Rejected: Requires DBA intervention for every Azure host hardware replacement.
Golden Image + cloud-init kfed GateHardware SCSI LUNFail-closed consensusAutomatedChosen: Separates immutable compute from persistent LUNs with zero-write quarantine.

Ansible SSH playbooks and Terraform remote-exec provisioners both couple storage initialization to VM creation events. Even if you add a guard flag like create_asm: false in Ansible variables, a single misconfigured inventory run or forgotten flag during an emergency rebuild wipes production headers. Manual DBA recovery protects data but turns routine cloud host replacement into a high-toil incident.

Compare four Oracle VM storage orchestration patterns

Packaging Oracle binaries into an Immutable Golden Image and pushing storage discovery into a local, fail-closed cloud-init bootstrap agent removes both human error and remote SSH fragility. The agent derives truth exclusively from the attached disks’ Block 0 headers and hardware SCSI LUN IDs.

The Autonomous Storage Discovery Architecture

The architecture separates the database host into three clean layers: an Ephemeral Compute Layer built from an Azure Compute Gallery golden image, a Deterministic Mapping Layer driven by udev SCSI LUN rules, and a Persistent Storage Layer on Azure Managed Disks.

  1. Immutable Golden Image (Azure Compute Gallery): OS hardening, kernel parameters (sysctl.conf), hugepages, Oracle Grid Infrastructure 19c, and Oracle Database 19c software-only homes are baked into a versioned Azure Compute Gallery image using Packer. Root OS disks hold zero database state and can be replaced at any time.
  2. Deterministic SCSI LUN Mapping (/dev/oracleasm/by-lun/lun-*): Terraform assigns fixed LUN ranges (lun = 10..19 for +DATA, lun = 20..29 for +RECO). At boot, a udev generator reads /sys/block/sd*/device/scsi_device/ to extract the hardware SCSI LUN number and creates stable symlinks owned by grid:asmadmin with mode 0660. On Azure VMs where /dev/sda is the OS disk and /dev/sdb may be a temporary resource disk (depending on VM series—Esv5 without local temp disks does not always expose /dev/sdb as temp), filtering by LUN >= 10 is far safer than hardcoding sda/sdb exclusions.
  3. Header Inspection via kfed and blkid: The bootstrap agent inspects every expected LUN device using Oracle’s kfed read <device> utility (checking for kfbh.type: KFBTYP_DISKHEAD and kfdhdb.hdrsts: KFDHDR_MEMBER with ORCLDISK in kfdhdb.driver.provstr) alongside blkid -p (probe bypassing the udev cache) to detect foreign filesystems (ext4, xfs, LVM2_member). Using kfed directly avoids brittle raw byte-offset assumptions across partitioned versus unpartitioned LUNs, while blkid -p ensures stale udev cache entries from an earlier boot never mask an existing signature.
  4. Fail-Closed Atomic Consensus Gate: Every expected LUN listed in the VM’s ExpectedLuns metadata must be present and must agree on the same state before any write occurs:
    • All LUNs have valid ASM headers: Route to Day 2 Recovery (crsctl start has, srvctl start asm, srvctl start diskgroup, and srvctl start database).
    • All LUNs are completely unformatted (zero ASM, partition, or filesystem signatures): Route to Day 1 Provisioning (CREATE DISKGROUP ... ATTRIBUTE 'au_size'='4M' via sqlplus / as sysasm or asmcmd mkdg XML).
    • Any mixed, partial, or foreign state: Route to Emergency Quarantine Halt—exit non-zero, leave the database stopped, emit a P1 alert, and modify zero disk blocks. If a single disk’s primary Block 0 was damaged but AU 1 block 254 remains intact, operators can inspect and repair it manually with kfed rather than letting automation overwrite the group.

Decouple immutable compute from persistent SCSI LUN storage

How It Rolls Out

Deploying autonomous ASM discovery into an existing estate should follow a staged rollout so legacy hosts are never disrupted.

  1. Phase 1 — Bake Golden Image and Validate LUN Mapping: Build the Packer image with GI 19c and Database 19c binaries, deploy a sandbox VM with PremiumV2_LRS disks on LUNs 10–19 and 20–29, and verify /dev/oracleasm/by-lun/lun-* symlinks match Azure LUNs. Validation gate: kfed and udevadm info confirm grid:asmadmin ownership on every expected LUN. Rollback: Destroy sandbox VM; production untouched.
  2. Phase 2 — Dry-Run Discovery on Existing Hosts: Run the header-inspection script in read-only --dry-run mode against staging VMs to verify it classifies existing ASM disks as Day 2 Recovery with 100% accuracy. Validation gate: Zero false-negative empty classifications across 10 consecutive reboots. Rollback: Remove dry-run script; no storage changes.
  3. Phase 3 — Enable Day 2 Auto-Mount on Standby Nodes: Replace procedural Ansible post-boot hooks on a Data Guard physical standby with the cloud-init bootstrap agent, then taint and replace the standby VM in Terraform. Validation gate: Replacement standby VM boots, discovers +DATA and +RECO, mounts ASM, and resumes Redo Apply automatically. Rollback: Reattach disks to a manual recovery VM using the prior runbook.
  4. Phase 4 — Enforce Fail-Closed Quarantine and Decommission Day-1 Playbooks: Remove destructive parted/mkfs tasks from Ansible and CI/CD pipelines, and wire the bootstrap agent’s exit-code 2 alert into PagerDuty/Azure Monitor. Validation gate: Simulated partial-LUN attach triggers Quarantine Halt with zero block writes. Rollback: Re-enable manual DBA intervention gate in Terraform.

Fail-closed consensus gate routes Day 1, Day 2, or Quarantine

In Practice

I have not published internal production telemetry from this factory, but the documented implementation pattern combines Terraform LUN pinning, udev SCSI symlink generation, and a kfed-backed Python state engine.

1. Terraform Immutable VM and Disk Attachment

resource "azurerm_linux_virtual_machine" "oracle_node" {
  name                = "vm-oradb-prod-01"
  resource_group_name = var.resource_group_name
  location            = var.location
  zone                = var.availability_zone
  size                = "Standard_E32-8s_v5"
  admin_username      = "azureuser"

  network_interface_ids = [azurerm_network_interface.oracle_nic.id]
  source_image_id       = var.oracle_golden_image_id
  custom_data           = filebase64("${path.module}/scripts/bootstrap_asm.sh")

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Premium_LRS"
  }

  tags = {
    Workload     = "Oracle"
    DatabaseName = "PRODDB"
    ExpectedLuns = "10,11,20"
  }
}

resource "azurerm_virtual_machine_data_disk_attachment" "data_disk_01" {
  managed_disk_id    = azurerm_managed_disk.asm_data_01.id
  virtual_machine_id = azurerm_linux_virtual_machine.oracle_node.id
  lun                = 10
  caching            = "None"
}

2. Deterministic LUN-to-Udev Rule Generator (generate_asm_udev.sh)

#!/usr/bin/env bash
set -euo pipefail

UDEV_RULE_FILE="/etc/udev/rules.d/99-oracle-asmdevices.rules"
: > "${UDEV_RULE_FILE}"

for dev_path in /sys/block/sd*; do
  [ -e "${dev_path}" ] || continue
  dev_name=$(basename "${dev_path}")
  scsi_dir=$(echo "${dev_path}/device/scsi_device/"*)
  [ -e "${scsi_dir}" ] || continue

  lun_id=$(basename "${scsi_dir}" | awk -F':' '{print $4}')
  # Only bind LUNs >= 10 reserved for Oracle ASM (+DATA / +RECO)
  if [ "${lun_id}" -lt 10 ]; then
    continue
  fi

  echo "SUBSYSTEM==\"block\", KERNEL==\"${dev_name}\", ENV{DEVTYPE}==\"disk\", SYMLINK+=\"oracleasm/by-lun/lun-${lun_id}\", OWNER=\"grid\", GROUP=\"asmadmin\", MODE=\"0660\"" >> "${UDEV_RULE_FILE}"
done

udevadm control --reload-rules
udevadm trigger --subsystem-match=block
udevadm settle --timeout=30

3. Autonomous State Engine (bootstrap_agent.py)

#!/usr/bin/env python3
import glob, logging, subprocess, sys

logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s: %(message)s")
KFED_BIN = "/u01/app/19.0.0.0/grid/bin/kfed"

def check_asm_header(device_path):
    """Verify ASM disk header via kfed rather than raw byte offsets."""
    res = subprocess.run([KFED_BIN, "read", device_path], capture_output=True, text=True)
    if res.returncode != 0:
        return False
    return "KFBTYP_DISKHEAD" in res.stdout and "ORCLDISK" in res.stdout

def is_device_empty(device_path):
    """Confirm zero filesystem, LVM, or partition signatures via blkid."""
    res = subprocess.run(["blkid", "-p", device_path], capture_output=True, text=True)
    return res.returncode == 2 and res.stdout.strip() == ""

def execute_day2_recovery():
    subprocess.run(["/u01/app/19.0.0.0/grid/bin/crsctl", "start", "has"], check=True)
    subprocess.run(["su", "-", "grid", "-c", "srvctl start asm"], check=True)
    subprocess.run(["su", "-", "grid", "-c", "srvctl start diskgroup -g DATA"], check=True)
    subprocess.run(["su", "-", "grid", "-c", "srvctl start diskgroup -g RECO"], check=True)
    subprocess.run(["su", "-", "oracle", "-c", "srvctl start database -d PRODDB"], check=True)

def main():
    devices = sorted(glob.glob("/dev/oracleasm/by-lun/lun-*"))
    if not devices:
        logging.error("No Oracle ASM LUNs found in /dev/oracleasm/by-lun/.")
        sys.exit(1)

    asm_flags = [check_asm_header(d) for d in devices]
    empty_flags = [is_device_empty(d) for d in devices]

    if all(asm_flags):
        logging.info("All LUNs carry valid ASM headers. Running Day 2 recovery.")
        execute_day2_recovery()
    elif all(empty_flags):
        logging.info("All LUNs are completely blank. Ready for Day 1 CREATE DISKGROUP.")
        # Invoke SQL*Plus SYSASM or asmcmd mkdg XML with AU_SIZE 4M
    else:
        logging.critical("FAIL-CLOSED: Mixed or foreign disk state detected. Halting.")
        sys.exit(2)

if __name__ == "__main__":
    main()

Note also two documented architectural details when operating this pattern. First, keep the database SPFILE and orapw password file inside +DATA (or fetch orapw${ORACLE_SID} from Azure Key Vault at boot) and store only a one-line init${ORACLE_SID}.ora pointer (SPFILE='+DATA/PRODDB/PARAMETERFILE/spfilePRODDB.ora') in $ORACLE_HOME/dbs; otherwise, an ephemeral replacement VM loses ALTER SYSTEM parameter changes and Data Guard SYS authentication. Second, for workloads that do not require self-managed IaaS VMs, Oracle Database@Azure runs OCI Exadata infrastructure inside Azure data centers and eliminates self-managed Linux udev and ASM diskgroup bootstrapping entirely.

Where It Breaks

Moving storage orchestration into a host-level cloud-init agent eliminates remote Ansible wipe risks, but introduces local boot-time race conditions and Azure control-plane edge cases.

ConditionBreaks HowDetectMitigate
Transient read timeout on Block 0kfed read fails on one LUN during boot; if treated as blank, could misclassify disk.kfed stderr I/O timeout in /var/log/cloud-init-output.log.Require explicit blkid -p exit code 2 (no signature found) before classifying any disk as blank, and retry kfed 3 times.
Partial LUN attachment on VM replaceAzure attaches 3 of 4 +DATA disks while the 4th is still detaching from the dead host.Expected LUN list in VM tags (ExpectedLuns) does not match /dev/oracleasm/by-lun/.Assert exact LUN count and IDs against ExpectedLuns metadata before running header consensus.
udev symlink race at bootbootstrap_agent.py runs before systemd-udevd finishes creating /dev/oracleasm/by-lun/lun-*.Agent exits 1 with “No Oracle ASM LUNs found” immediately after boot.Order systemd unit After=systemd-udevd.service and run udevadm settle --timeout=30 before Python starts.
Split-brain concurrent disk attachShared disk or delayed detach lets two VMs mount the same ASM diskgroup simultaneously.ASM alert log ORA-15020 or block corruption across instances.Confirm the failed VM is fully Deallocated / deleted before attaching disks to the replacement VM.
IMDS rate limiting on fleet rebootSimultaneous host reboots hit Azure IMDS (169.254.169.254) HTTP 429 limits if querying metadata APIs.HTTP 429 responses in bootstrap logs.Pass static expected LUN metadata via custom_data or retry IMDS queries with exponential backoff.
Wrong au_size on Day 1 buildCreating +DATA with default 1M AU size instead of 4M bloats ASM shared pool memory on large DBs.SELECT name, allocation_unit_size FROM v$asm_diskgroup; shows 1048576.Hardcode ATTRIBUTE 'au_size'='4M' in Day 1 CREATE DISKGROUP SQL / asmcmd mkdg XML.
Missing password file on golden imageReplacement VM boots without the instance-specific orapwPRODDB file, breaking Data Guard redo transport.ORA-16191 in primary alert log during standby recovery.Fetch orapw${ORACLE_SID} from Azure Key Vault via Managed Identity during cloud-init.

Where autonomous ASM discovery breaks in production

Key Takeaways

  • Never run procedural Day 1 formatting tools (parted, fdisk, mkfs) against cloud block devices without first inspecting Block 0 headers; on a Day 2 VM replacement, those scripts destroy live Oracle ASM metadata.
  • Linux /dev/sdX device letters are non-deterministic across reboots and Azure VM replacements; bind ASM devices strictly by hardware SCSI LUN IDs using udev rules (/dev/oracleasm/by-lun/lun-*) and filter on reserved LUN ranges (>= 10).
  • Use Oracle’s kfed read (KFBTYP_DISKHEAD / ORCLDISK) paired with blkid -p to enforce a fail-closed consensus gate: mount only if 100% of expected LUNs carry ASM headers, initialize only if 100% are blank, and halt in quarantine on any mismatch.
  • Verify real Oracle 19c CLI semantics in automation: asmcmd uses mkdg <xml> (not createdg), and Oracle Restart mounts diskgroups via srvctl start diskgroup or SQL ALTER DISKGROUP ... MOUNT.
  • Always verify expected LUN counts against VM metadata and run udevadm settle --timeout=30 before scanning, because partial Azure disk attachments and udev races are the most common Day 2 boot failures.

What to Do Next

  • Problem: Procedural Day 1 Ansible playbooks that assume blank disks and hardcoded /dev/sdX names destroy Oracle ASM Block 0 headers when cloud automation replaces a failed Azure VM.
  • Solution: Move Oracle binaries into an immutable Azure Compute Gallery golden image, bind disks by hardware SCSI LUN via udev, and run a fail-closed cloud-init bootstrap agent using kfed and blkid -p.
  • Proof: Taint and replace a Data Guard standby VM in staging; the replacement node should map identical /dev/oracleasm/by-lun/lun-* symlinks, classify all LUNs as Day 2 Recovery, and mount +DATA and +RECO without formatting a single block.
  • Action: Grep your infrastructure repositories today for parted, fdisk, mkfs, and dd targeting database volumes, and replace any unguarded Day 1 disk task with a kfed + udev LUN-verified consensus gate.

Sources to Verify

  • Oracle Corporation: Oracle Automatic Storage Management Administrator’s Guide 19c (kfed utility, asmcmd mkdg, CREATE DISKGROUP ... ATTRIBUTE 'au_size'='4M', and srvctl start diskgroup).
  • Microsoft Corporation: Azure Virtual Machines Documentation: Attach a data disk to a Linux VM and SCSI LUN mapping (Microsoft Learn).
  • Linux Kernel / systemd: udevadm(8) and persistent block device naming rules (Linux man-pages / systemd documentation).