Azure Oracle Storage Planes: Automated ASM Orchestration via Immutable Compute
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/sdXnames, 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-closedcloud-initbootstrap agent that inspectskfedBlock 0 headers before choosing Day 1 creation, Day 2 mount, or quarantine.- Watch out: Partial LUN attachments during Azure VM replacement or stale
udevraces can trigger false blank-disk detection unless the agent verifies expected LUN counts and runsudevadm settlefirst.
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:
- Infrastructure Provisioning (Terraform): Terraform deploys a constrained-core Azure VM (such as
Standard_E32-8s_v5) and attaches multiple Azure Managed Disks (PremiumV2_LRSorUltraSSD_LRS) across dedicated SCSI Logical Unit Numbers (LUNs) for+DATAand+RECO. - Procedural Configuration (Ansible): An Ansible playbook connects over SSH to the new VM, iterates over
/dev/sd*block devices, runspartedorfdiskto initialize partition tables, writesudevrules forgrid:asmadminownership, 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:
- Constraint 1 — Block 0 Header Destruction: Procedural playbooks that execute
parted --script /dev/sdc mklabel gptorddunconditionally overwrite Block 0 of the ASM disk—destroying thekfbhblock header andkfdhdbdisk header (ORCLDISKprovisioning string and allocation unit pointers). While ASM mirrors a backup copy of the disk header in the second Allocation Unit (AU 1, block 254),partedormkfswrites can also clobber adjacent metadata or trigger immediate diskgroup mount failure, forcing a multi-terabyte RMAN restore from backup. - Constraint 2 — Non-Deterministic Linux
/dev/sdXEnumeration: 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+DATAand+RECOmembers. - 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
+DATALUNs appear in sysfs atcloud-initstartup—and in normal-redundancy diskgroups or external-redundancy configurations, missing a member disk prevents the diskgroup from mounting cleanly. - Constraint 4 —
ASMCMDand Tooling Syntax Traps: Scripts written from memory often fail on real Oracle 19c binaries—for example,asmcmdcreates diskgroups viaasmcmd mkdg <config.xml>(notcreatedg), andasmcmdexpects the ASM instance and diskgroups to be mounted via SQL (ALTER DISKGROUP ... MOUNT) orsrvctl, not standaloneasmcmd mounton a stopped Oracle Restart stack. Similarly, initializing a multi-terabyte diskgroup with the default1MAllocation Unit (AU_SIZE) rather than4Mincreases ASM extent-map memory pressure in the ASM shared pool.
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.
| Option | Device Identity | Day 2 Rebuild Safety | Recovery Speed | Why Chosen or Rejected |
|---|---|---|---|---|
| Ansible Day-1 SSH Playbook | /dev/sdX letters | Unsafe (overwrites headers) | Fast until data loss | Rejected: Procedural script assumes blank disks; destroys Block 0 on VM replacement. |
Terraform remote-exec Provisioner | /dev/sdX or LUN | Fragile (runs on create) | Moderate | Rejected: Requires SSH from CI runner and breaks idempotency on VM taint/replace. |
| Manual DBA Storage Attach | udev + human check | Safe (human inspects) | Slow (manual paging) | Rejected: Requires DBA intervention for every Azure host hardware replacement. |
Golden Image + cloud-init kfed Gate | Hardware SCSI LUN | Fail-closed consensus | Automated | Chosen: 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.
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.
- 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. - Deterministic SCSI LUN Mapping (
/dev/oracleasm/by-lun/lun-*): Terraform assigns fixed LUN ranges (lun = 10..19for+DATA,lun = 20..29for+RECO). At boot, audevgenerator reads/sys/block/sd*/device/scsi_device/to extract the hardware SCSI LUN number and creates stable symlinks owned bygrid:asmadminwith mode0660. On Azure VMs where/dev/sdais the OS disk and/dev/sdbmay be a temporary resource disk (depending on VM series—Esv5without local temp disks does not always expose/dev/sdbas temp), filtering byLUN >= 10is far safer than hardcodingsda/sdbexclusions. - Header Inspection via
kfedandblkid: The bootstrap agent inspects every expected LUN device using Oracle’skfed read <device>utility (checking forkfbh.type: KFBTYP_DISKHEADandkfdhdb.hdrsts: KFDHDR_MEMBERwithORCLDISKinkfdhdb.driver.provstr) alongsideblkid -p(probe bypassing the udev cache) to detect foreign filesystems (ext4,xfs,LVM2_member). Usingkfeddirectly avoids brittle raw byte-offset assumptions across partitioned versus unpartitioned LUNs, whileblkid -pensures stale udev cache entries from an earlier boot never mask an existing signature. - Fail-Closed Atomic Consensus Gate: Every expected LUN listed in the VM’s
ExpectedLunsmetadata 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, andsrvctl start database). - All LUNs are completely unformatted (zero ASM, partition, or filesystem signatures): Route to Day 1 Provisioning (
CREATE DISKGROUP ... ATTRIBUTE 'au_size'='4M'viasqlplus / as sysasmorasmcmd mkdgXML). - 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
kfedrather than letting automation overwrite the group.
- All LUNs have valid ASM headers: Route to Day 2 Recovery (
How It Rolls Out
Deploying autonomous ASM discovery into an existing estate should follow a staged rollout so legacy hosts are never disrupted.
- 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_LRSdisks on LUNs 10–19 and 20–29, and verify/dev/oracleasm/by-lun/lun-*symlinks match Azure LUNs. Validation gate:kfedandudevadm infoconfirmgrid:asmadminownership on every expected LUN. Rollback: Destroy sandbox VM; production untouched. - Phase 2 — Dry-Run Discovery on Existing Hosts: Run the header-inspection script in read-only
--dry-runmode against staging VMs to verify it classifies existing ASM disks asDay 2 Recoverywith 100% accuracy. Validation gate: Zero false-negativeemptyclassifications across 10 consecutive reboots. Rollback: Remove dry-run script; no storage changes. - 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-initbootstrap agent, then taint and replace the standby VM in Terraform. Validation gate: Replacement standby VM boots, discovers+DATAand+RECO, mounts ASM, and resumes Redo Apply automatically. Rollback: Reattach disks to a manual recovery VM using the prior runbook. - Phase 4 — Enforce Fail-Closed Quarantine and Decommission Day-1 Playbooks: Remove destructive
parted/mkfstasks from Ansible and CI/CD pipelines, and wire the bootstrap agent’s exit-code2alert 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.
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.
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Transient read timeout on Block 0 | kfed 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 replace | Azure 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 boot | bootstrap_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 attach | Shared 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 reboot | Simultaneous 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 build | Creating +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 image | Replacement 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. |
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/sdXdevice letters are non-deterministic across reboots and Azure VM replacements; bind ASM devices strictly by hardware SCSI LUN IDs usingudevrules (/dev/oracleasm/by-lun/lun-*) and filter on reserved LUN ranges (>= 10). - Use Oracle’s
kfed read(KFBTYP_DISKHEAD/ORCLDISK) paired withblkid -pto 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:
asmcmdusesmkdg <xml>(notcreatedg), and Oracle Restart mounts diskgroups viasrvctl start diskgroupor SQLALTER DISKGROUP ... MOUNT. - Always verify expected LUN counts against VM metadata and run
udevadm settle --timeout=30before scanning, because partial Azure disk attachments andudevraces 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/sdXnames 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-closedcloud-initbootstrap agent usingkfedandblkid -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+DATAand+RECOwithout formatting a single block. - Action: Grep your infrastructure repositories today for
parted,fdisk,mkfs, andddtargeting database volumes, and replace any unguarded Day 1 disk task with akfed+udevLUN-verified consensus gate.
Sources to Verify
- Oracle Corporation: Oracle Automatic Storage Management Administrator’s Guide 19c (
kfedutility,asmcmd mkdg,CREATE DISKGROUP ... ATTRIBUTE 'au_size'='4M', andsrvctl 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).
Interactive tools for this topic