Skip to content

The Migration Script That Ran Fine on the Wrong Host

Adityo Guni Waluyo

Dangerous migration scripts need mechanical refusal, not conventions: local-only guards, strict mode, sha256 manifests, pre-import snapshots, and rollback.

TL;DR

A one-shot migration script can't tell which host it's hitting, so warnings in READMEs weren't enough. The fix moved into code: strict bash mode, a guard that greps local-only scripts for ssh, scp, rsync, or a forbidden host and dies on any hit. Snapshots, SHA-256 manifests, wp search-replace, and a capped parity crawl make results verifiable.

# The Migration Script That Ran Fine on the Wrong Host

04-import-database.sh rebuilds a WordPress database from scratch and rewrites every URL inside it. I wrote it as part of a WordPress-to-headless migration, where the import stage runs exactly once against a fresh database and every mistake is destructive. The commands in that file do not care which host receives them. One wrong terminal tab, or one environment variable still pointing at the previous target, and the same pipeline becomes an incident.

What the warnings could not do

My first line of defense was documentation. A capital-letter warning in the README, a comment block at the top of every script, a habit of running pwd before anything destructive. None of those survive a rushed afternoon. They are reminders, not barriers, and they depend on the operator being careful at the precise moment care matters most.

So the defense moved into code: mechanical guards that refuse to run when something looks wrong, instead of prose asking someone to double-check.

Strict mode and a script audit

Every script sources lib/common.sh, which starts with set -euo pipefail. The three flags each cover a different way a script can fail silently.

The -e flag exits when a pipeline, list, or compound command returns a non-zero status. The -u flag treats an unset variable as an error during parameter expansion, sending the error to stderr and exiting in a non-interactive shell. The pipefail flag makes a pipeline's status the last non-zero status in that pipeline, or zero if all commands succeed, and all three are disabled by default in Bash [1]. A script without them can skip a failed step and continue happily into the next one.

On top of strict mode, a require_local guard re-scans the calling script for remote-execution patterns and stops on any hit.

# lib/common.sh, generalized version
readonly FORBIDDEN_HOST="192.0.2.10"  # match pattern, never dialed

require_local() {
  local caller="${BASH_SOURCE[1]:-${1:-unknown}}"
  local hits
  hits="$(grep -nE "(ssh[[:space:]]|scp[[:space:]]|rsync[[:space:]].*@|${FORBIDDEN_HOST})" "$caller" \
          | grep -v "guard-ok" || true)"
  [ -n "$hits" ] && die "LOCAL-ONLY violation in ${caller}: ${hits}"
  ok "guard: ${caller##*/} is local-only"
}

The preflight stage, 01-preflight.sh, repeats the same audit over the entire scripts directory, not just the file being run. A script that intentionally contains such a pattern carries a guard-ok comment tag to be skipped. Everything else stops before a single command executes.

The honest limit: text patterns cannot catch everything. A plain call to a remote API contains none of these tokens and passes the audit. The guard covers the common mistake class, remote shell execution from a script meant to stay local, and that is where these local-only migration scripts are most likely to bite.

Checksums as the only content proof

The media stage copies 58,959 files, about 8.6 GB, from a local uploads mirror. rsync by default runs a "quick check" that judges a file as unchanged by size or last-modified time alone [3]. A file with the same size and timestamp but different content transfers nothing and reports success.

That is why the pipeline writes a per-file SHA-256 manifest, media-checksum.json, and re-verifies after the copy. It is the only layer that proves content. SHA-256 replaces MD5 deliberately: the GNU coreutils documentation states that MD5 detects accidental corruption but should not be considered secure against malicious tampering, and recommends the SHA-2 family for stronger guarantees [4]. The preflight also asserts that the database dump exists, that a gzip integrity check passes on it, and that the compose file parses.

Rewrites, snapshots, and a bounded crawl

Before any write, the import stage takes a snapshot, pre-import-<ts>, covering both the database and uploads. Then a three-phase orchestrator runs: a throwaway compose stack over the legacy dump, a rendered extract fed to the converter, and a wp-cli import into a fresh WordPress. Fail anywhere in the middle and the target is left clean rather than half-migrated.

URL rewriting goes through wp search-replace, which understands PHP serialized data, does not change primary key values, and also replaces JSON-encoded variants of the search string [2]. A naive stream editor pass corrupts serialized string lengths, turning working data into broken data with no error at rewrite time. --dry-run runs first to show the report without saving anything [2]. A redirect map forwards old addresses to new ones, and the rollback script restores the database and uploads from the snapshot when a check fails.

The parity crawl in 06-verify.sh is bounded at VERIFY_CAP 500 pages and exits with status 1 on any mismatch, so verification either finishes or fails loudly.

The pattern list inside the guard is a living responsibility: add a new remote tool to the team's workflow, add it to the list. What changed for me is where migration confidence lives. It no longer sits in the feeling that things went fine. It sits in artifacts that can be opened and checked: the checksum manifest, the snapshot, the parity report.

Sources

Related articles