@intentius/chant-lexicon-terraform 0.124.76 → 0.124.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drift-record.d.ts +24 -0
- package/dist/drift-record.d.ts.map +1 -1
- package/dist/drift-record.js +52 -0
- package/dist/drift-rows.d.ts +49 -4
- package/dist/drift-rows.d.ts.map +1 -1
- package/dist/drift-rows.js +87 -19
- package/dist/integrity.json +2 -2
- package/dist/manifest.json +1 -1
- package/dist/pr-env.d.ts +138 -0
- package/dist/pr-env.d.ts.map +1 -0
- package/dist/pr-env.js +248 -0
- package/dist/state/gitlab.d.ts +74 -0
- package/dist/state/gitlab.d.ts.map +1 -0
- package/dist/state/gitlab.js +275 -0
- package/dist/state/index.d.ts +2 -0
- package/dist/state/index.d.ts.map +1 -1
- package/dist/state/index.js +2 -0
- package/dist/state/store.d.ts +2 -1
- package/dist/state/store.d.ts.map +1 -1
- package/dist/state/versions.d.ts +39 -0
- package/dist/state/versions.d.ts.map +1 -0
- package/dist/state/versions.js +85 -0
- package/dist/state-migration.d.ts +85 -0
- package/dist/state-migration.d.ts.map +1 -0
- package/dist/state-migration.js +296 -0
- package/dist/state-ops.d.ts +54 -87
- package/dist/state-ops.d.ts.map +1 -1
- package/dist/state-ops.js +120 -77
- package/package.json +2 -2
- package/src/__fixtures__/drift-rows/refresh-plan-module.json +48 -0
- package/src/drift-record.test.ts +62 -0
- package/src/drift-record.ts +58 -0
- package/src/drift-rows.test.ts +90 -1
- package/src/drift-rows.ts +89 -18
- package/src/pr-env.test.ts +132 -0
- package/src/pr-env.ts +312 -0
- package/src/state/gitlab.test.ts +226 -0
- package/src/state/gitlab.ts +318 -0
- package/src/state/index.ts +2 -0
- package/src/state/store.ts +2 -1
- package/src/state/versions.ts +103 -0
- package/src/state-export-unlock.test.ts +230 -0
- package/src/state-migration.test.ts +236 -0
- package/src/state-migration.ts +353 -0
- package/src/state-ops.ts +132 -130
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A state migration between Terraform roots (#4762), for chant core's
|
|
3
|
+
* gated migration (`@intentius/chant/state-migration`): what `moved`,
|
|
4
|
+
* `import` and `removed` blocks cannot do, because each works inside one
|
|
5
|
+
* root's state.
|
|
6
|
+
*
|
|
7
|
+
* moves resources (`[module.<m>.]<type>.<name>`) or module calls
|
|
8
|
+
* (`module.<m>`), with every instance, from one root's state to
|
|
9
|
+
* the same address in another's
|
|
10
|
+
* restores a root's state put back to a version a migration recorded (a
|
|
11
|
+
* revert), refused when the state moved past what that
|
|
12
|
+
* migration left
|
|
13
|
+
*
|
|
14
|
+
* Planning (planTerraformMigration) initialises each root in a data dir of
|
|
15
|
+
* its own, reads its backend version id and pulls its state, keeps only
|
|
16
|
+
* their digests, builds each new state in the work dir, and plans each root
|
|
17
|
+
* against its new state through a local-backend override file and another
|
|
18
|
+
* data dir, so the root's own `.terraform` and its real state are not
|
|
19
|
+
* touched. The engine it returns writes the new states for core under each
|
|
20
|
+
* stored state's lock (s3's lock file, the gcs lock object, the azurerm
|
|
21
|
+
* lease, as `./state/locks.ts` takes them): `state push -lock=false`, or a
|
|
22
|
+
* write under the lease on azurerm, the roots that gain resources first, so
|
|
23
|
+
* a write that stops half way leaves a resource in two states rather than
|
|
24
|
+
* in none. Then each root plans against its real backend.
|
|
25
|
+
*
|
|
26
|
+
* State contents never leave the work dir. The record holds version ids and
|
|
27
|
+
* digests.
|
|
28
|
+
*
|
|
29
|
+
* Lifted from terragucci's `migrate.ts` (`moveResources`, `addressMatches`,
|
|
30
|
+
* `derivedLineage`, `stateDigest`, `resourceChanges`, `backendBlock`,
|
|
31
|
+
* `proofPlan`, `planMigration`'s moves and reverts, `applyMigration`,
|
|
32
|
+
* `movedSince`), so terragucci deletes its copy. A backend move (a state
|
|
33
|
+
* read from another backend, a TFE workspace or an exported file) and a
|
|
34
|
+
* migration of choudoufu's live estates stay terragucci's for now.
|
|
35
|
+
*/
|
|
36
|
+
import { createHash } from "node:crypto";
|
|
37
|
+
import { hostname } from "node:os";
|
|
38
|
+
import { join, resolve } from "node:path";
|
|
39
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
40
|
+
import type { MigrationCheck, MigrationRootPlan, MigrationStateAt, StateMigrationEngine } from "@intentius/chant/state-migration";
|
|
41
|
+
import { initRoot, planStateCheck, pushStateFile, type RootRun } from "./state-ops";
|
|
42
|
+
import { isRefused, isStored, stateLocation, stateObject, type LockableState } from "./state/backend";
|
|
43
|
+
import { pullState, runBinary, type BinaryExec, type StateFile, type StateResource } from "./state/exec";
|
|
44
|
+
import { takeLocksWithSources, type LockOperation } from "./state/locks";
|
|
45
|
+
import type { StoreFetch } from "./state/object-store";
|
|
46
|
+
import { stateStore, type StateStore } from "./state/store";
|
|
47
|
+
import { stateVersionSource } from "./state/versions";
|
|
48
|
+
|
|
49
|
+
/** Resources that move from one root's state to another's. */
|
|
50
|
+
export interface Move {
|
|
51
|
+
from: string;
|
|
52
|
+
to: string;
|
|
53
|
+
addresses: string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A root's state put back to a version a migration recorded. */
|
|
57
|
+
export interface Restore {
|
|
58
|
+
root: string;
|
|
59
|
+
/** Where the state is, as the migration recorded it. */
|
|
60
|
+
location: string;
|
|
61
|
+
/** The version to put back; null when the root had no state before, so it gets an empty one. */
|
|
62
|
+
version_id: string | null;
|
|
63
|
+
/** The version the migration left: a state that moved past it is refused. */
|
|
64
|
+
from_version_id: string | null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A migration that cannot be planned: an address in no state, a root that is refused. Nothing was written. */
|
|
68
|
+
export class MigrationError extends Error {
|
|
69
|
+
constructor(message: string) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.name = "MigrationError";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const sha = (text: string): string => `sha256:${createHash("sha256").update(text).digest("hex")}`;
|
|
76
|
+
|
|
77
|
+
/** A state's digest: sha256 of its JSON as parsed and written back, so whitespace never moves it. */
|
|
78
|
+
export const stateDigest = (s: StateFile): string => sha(JSON.stringify(s));
|
|
79
|
+
|
|
80
|
+
/** A resource entry's address without instance keys: `module.a.module.b.type.name`, module keys dropped. */
|
|
81
|
+
const resourceAddress = (r: StateResource): string => `${r.module ? `${r.module.replace(/\[[^\]]*\]/g, "")}.` : ""}${r.mode === "data" ? "data." : ""}${r.type}.${r.name}`;
|
|
82
|
+
const moduleOf = (r: StateResource): string => (r.module ?? "").replace(/\[[^\]]*\]/g, "");
|
|
83
|
+
|
|
84
|
+
/** Whether a migration address names a state entry: the managed resource itself, or a module call it sits in, with its data sources. */
|
|
85
|
+
export function addressMatches(address: string, r: StateResource): boolean {
|
|
86
|
+
if (/(^|\.)module\.[A-Za-z_][\w-]*$/.test(address)) return moduleOf(r) === address || moduleOf(r).startsWith(`${address}.`);
|
|
87
|
+
return r.mode === "managed" && resourceAddress(r) === address;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A lineage that a migration and a root always give the same: a state planned twice has one digest. */
|
|
91
|
+
export function derivedLineage(...parts: string[]): string {
|
|
92
|
+
const h = createHash("sha256").update(parts.join("\n")).digest("hex");
|
|
93
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const emptyState = (lineage: string, serial: number, terraformVersion = "1.0.0"): StateFile => ({ version: 4, terraform_version: terraformVersion, serial, lineage, outputs: {}, resources: [], check_results: null });
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The states after the moves. `before` holds each affected root's state, or
|
|
100
|
+
* null when it has none. A changed state keeps its lineage and gets the next
|
|
101
|
+
* serial; a root with no state gets a new one, its lineage derived from the
|
|
102
|
+
* migration and the root. Throws MigrationError naming every address that
|
|
103
|
+
* is in no state, or already in the root it moves to.
|
|
104
|
+
*/
|
|
105
|
+
export function moveResources(name: string, moves: readonly Move[], before: ReadonlyMap<string, StateFile | null>): Map<string, StateFile> {
|
|
106
|
+
const after = new Map<string, StateFile>();
|
|
107
|
+
const take = (root: string, from?: StateFile | null): StateFile => {
|
|
108
|
+
const held = after.get(root);
|
|
109
|
+
if (held) return held;
|
|
110
|
+
const was = before.get(root) ?? null;
|
|
111
|
+
const s: StateFile = was ? { ...structuredClone(was), serial: was.serial + 1 } : emptyState(derivedLineage(name, root), 1, from?.terraform_version);
|
|
112
|
+
after.set(root, s);
|
|
113
|
+
return s;
|
|
114
|
+
};
|
|
115
|
+
const problems: string[] = [];
|
|
116
|
+
for (const m of moves) {
|
|
117
|
+
const src = before.get(m.from) ?? null;
|
|
118
|
+
if (!src) {
|
|
119
|
+
problems.push(`${m.from} has no state to move ${m.addresses.join(", ")} from`);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const from = take(m.from);
|
|
123
|
+
const to = take(m.to, src);
|
|
124
|
+
for (const address of m.addresses) {
|
|
125
|
+
const found = from.resources.filter((r) => addressMatches(address, r));
|
|
126
|
+
if (found.length === 0) {
|
|
127
|
+
problems.push(`${address} is not in the state of ${m.from}`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (to.resources.some((r) => addressMatches(address, r))) {
|
|
131
|
+
problems.push(`${address} is already in the state of ${m.to}`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
from.resources = from.resources.filter((r) => !found.includes(r));
|
|
135
|
+
to.resources.push(...found);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (problems.length > 0) throw new MigrationError(`migration ${name}:\n ${problems.join("\n ")}`);
|
|
139
|
+
return after;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The resource changes of a plan's JSON, as `<address>: <actions>`; no-ops and reads are not changes. */
|
|
143
|
+
export function resourceChanges(plan: unknown): string[] {
|
|
144
|
+
const rc = (plan as { resource_changes?: { address?: string; change?: { actions?: string[] } }[] } | undefined)?.resource_changes ?? [];
|
|
145
|
+
return rc
|
|
146
|
+
.filter((c) => {
|
|
147
|
+
const a = c.change?.actions ?? [];
|
|
148
|
+
return !(a.length === 1 && (a[0] === "no-op" || a[0] === "read"));
|
|
149
|
+
})
|
|
150
|
+
.map((c) => `${c.address}: ${(c.change?.actions ?? []).join("+")}`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A terraform block whose backend is the local file `path`, for the proof plan's override file. Terraform and OpenTofu merge any `*_override.tf` over the root's files. */
|
|
154
|
+
export const localBackendOverride = (path: string): string => `terraform {\n backend "local" {\n path = ${JSON.stringify(path)}\n }\n}\n`;
|
|
155
|
+
|
|
156
|
+
/** The override file a proof plan writes into a root, and removes, unless the product names its own. */
|
|
157
|
+
export const DEFAULT_OVERRIDE_FILE = "chant_migrate_override.tf";
|
|
158
|
+
|
|
159
|
+
/** What a migration's lock says, unless the product names its own. */
|
|
160
|
+
export const DEFAULT_MIGRATE_LOCK: LockOperation = { operation: "chant migrate", info: "a state migration is writing this state" };
|
|
161
|
+
|
|
162
|
+
/** One root a migration reads or writes. */
|
|
163
|
+
export interface MigrationRootRun extends Omit<RootRun, "exec"> {
|
|
164
|
+
/** Run `init` in a data dir of the migration's own (default), or false for a root another tool initialised in `dir` with `env`. */
|
|
165
|
+
init?: boolean;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface TerraformMigrationInput {
|
|
169
|
+
/** The migration's name: what its gate is called, and what a new root's lineage derives from. */
|
|
170
|
+
name: string;
|
|
171
|
+
/** Resources that move between roots. */
|
|
172
|
+
moves?: Move[];
|
|
173
|
+
/** States put back to a version a migration recorded. */
|
|
174
|
+
restores?: Restore[];
|
|
175
|
+
/** Every root the moves or restores name. */
|
|
176
|
+
roots: MigrationRootRun[];
|
|
177
|
+
/** The work dir: new states, plans and data dirs. The caller removes it. */
|
|
178
|
+
work: string;
|
|
179
|
+
exec?: BinaryExec;
|
|
180
|
+
fetch?: StoreFetch;
|
|
181
|
+
/** What the migration's lock says. */
|
|
182
|
+
lock?: LockOperation;
|
|
183
|
+
/** Who the lock names. Default `chant@<host>`. */
|
|
184
|
+
who?: string;
|
|
185
|
+
/** The proof plan's override file. Default {@link DEFAULT_OVERRIDE_FILE}. */
|
|
186
|
+
overrideFile?: string;
|
|
187
|
+
log?: (line: string) => void;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A planned migration: each root's plan for core, and the engine that writes it. */
|
|
191
|
+
export interface TerraformMigrationPlan {
|
|
192
|
+
roots: MigrationRootPlan[];
|
|
193
|
+
engine: StateMigrationEngine;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
interface Planned {
|
|
197
|
+
run: MigrationRootRun & { env: NodeJS.ProcessEnv };
|
|
198
|
+
object: LockableState;
|
|
199
|
+
file: string;
|
|
200
|
+
gained: number;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** A root's version id now, when its store keeps versions. `pin` lets an azurerm blob with snapshots only take one to name it. */
|
|
204
|
+
async function versionNow(o: LockableState, fetchFn: StoreFetch | undefined, pin: boolean): Promise<string | undefined> {
|
|
205
|
+
const src = stateVersionSource(o, fetchFn, { pin });
|
|
206
|
+
if ("refused" in src) return undefined;
|
|
207
|
+
return (await src.current()).versionId;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Plan a migration: read every affected state and its version, build the new
|
|
212
|
+
* states in `work`, and plan each root against its new state. Throws
|
|
213
|
+
* MigrationError for a root that is refused or a move that does not fit.
|
|
214
|
+
*/
|
|
215
|
+
export async function planTerraformMigration(input: TerraformMigrationInput): Promise<TerraformMigrationPlan> {
|
|
216
|
+
const exec = input.exec ?? runBinary;
|
|
217
|
+
const log = input.log ?? (() => {});
|
|
218
|
+
const lockOp = input.lock ?? DEFAULT_MIGRATE_LOCK;
|
|
219
|
+
const override = input.overrideFile ?? DEFAULT_OVERRIDE_FILE;
|
|
220
|
+
if (!!input.moves?.length === !!input.restores?.length) throw new MigrationError(`migration ${input.name}: give it moves or restores, one of the two`);
|
|
221
|
+
mkdirSync(input.work, { recursive: true });
|
|
222
|
+
const named = [...new Set(input.moves ? input.moves.flatMap((m) => [m.from, m.to]) : input.restores!.map((r) => r.root))].sort();
|
|
223
|
+
const byName = new Map(input.roots.map((r) => [r.root, r]));
|
|
224
|
+
const missing = named.filter((n) => !byName.has(n));
|
|
225
|
+
if (missing.length > 0) throw new MigrationError(`migration ${input.name}: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not among its roots`);
|
|
226
|
+
|
|
227
|
+
const runs = new Map<string, Planned["run"]>();
|
|
228
|
+
const objects = new Map<string, LockableState>();
|
|
229
|
+
const versions = new Map<string, string | undefined>();
|
|
230
|
+
const before = new Map<string, StateFile | null>();
|
|
231
|
+
for (const [i, name] of named.entries()) {
|
|
232
|
+
const r = byName.get(name)!;
|
|
233
|
+
let env = r.env ?? process.env;
|
|
234
|
+
if (r.init !== false) {
|
|
235
|
+
env = { ...env, TF_DATA_DIR: join(input.work, `data-${i}`) };
|
|
236
|
+
await initRoot({ ...r, env, exec, reconfigure: true });
|
|
237
|
+
}
|
|
238
|
+
const o = stateObject(r.dir, env, undefined, r.binary);
|
|
239
|
+
if (isRefused(o)) throw new MigrationError(`migration ${input.name} cannot run: ${name}: ${o.reason}`);
|
|
240
|
+
runs.set(name, { ...r, env });
|
|
241
|
+
objects.set(name, o);
|
|
242
|
+
versions.set(name, await versionNow(o, input.fetch, false));
|
|
243
|
+
before.set(name, await pullState(exec, r.binary, name, r.dir, env));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const after = new Map<string, StateFile>();
|
|
247
|
+
if (input.moves) {
|
|
248
|
+
for (const [root, s] of moveResources(input.name, input.moves, before)) after.set(root, s);
|
|
249
|
+
} else {
|
|
250
|
+
for (const r of input.restores!) {
|
|
251
|
+
const o = objects.get(r.root)!;
|
|
252
|
+
const location = stateLocation(o);
|
|
253
|
+
if (location !== r.location) throw new MigrationError(`migration ${input.name}: ${r.root}'s state is at ${location}, and the revert restores ${r.location}`);
|
|
254
|
+
const v = versions.get(r.root);
|
|
255
|
+
if ((r.from_version_id ?? undefined) !== v) throw new MigrationError(`migration ${input.name}: ${r.root}'s state is at version ${v ?? "none"}, and the migration it reverts left ${r.from_version_id ?? "none"}; it moved since, so putting the older version back would undo that change too`);
|
|
256
|
+
const now = before.get(r.root) ?? null;
|
|
257
|
+
const lineage = now?.lineage || derivedLineage(input.name, r.root);
|
|
258
|
+
const serial = (now?.serial ?? 0) + 1;
|
|
259
|
+
if (r.version_id === null) {
|
|
260
|
+
after.set(r.root, emptyState(lineage, serial, now?.terraform_version));
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const src = stateVersionSource(o, input.fetch);
|
|
264
|
+
if ("refused" in src) throw new MigrationError(`migration ${input.name}: ${r.root}: ${src.refused}`);
|
|
265
|
+
const text = await src.readVersion(r.version_id);
|
|
266
|
+
if (text === undefined) throw new MigrationError(`migration ${input.name}: ${r.location} has no version ${r.version_id}; a lifecycle rule may have expired it`);
|
|
267
|
+
const old = JSON.parse(typeof text === "string" ? text : Buffer.from(text).toString("utf-8")) as StateFile;
|
|
268
|
+
after.set(r.root, { ...old, resources: Array.isArray(old.resources) ? old.resources : [], lineage, serial });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const planned = new Map<string, Planned>();
|
|
273
|
+
const roots: MigrationRootPlan[] = [];
|
|
274
|
+
for (const [i, name] of named.entries()) {
|
|
275
|
+
const state = after.get(name);
|
|
276
|
+
if (!state) continue;
|
|
277
|
+
const run = runs.get(name)!;
|
|
278
|
+
const file = join(input.work, `${i}.tfstate`);
|
|
279
|
+
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
|
|
280
|
+
planned.set(name, { run, object: objects.get(name)!, file, gained: state.resources.length - (before.get(name)?.resources.length ?? 0) });
|
|
281
|
+
const proof = await proofPlan(run, exec, file, join(input.work, `proof-${i}`), override);
|
|
282
|
+
log(`${name}: ${proof.changes.length === 0 ? "no changes against its new state" : `${proof.changes.length} change${proof.changes.length === 1 ? "" : "s"} against its new state: ${proof.changes.join(", ")}`}`);
|
|
283
|
+
const was = before.get(name) ?? null;
|
|
284
|
+
const v = versions.get(name);
|
|
285
|
+
const location = stateLocation(objects.get(name)!);
|
|
286
|
+
roots.push({ root: name, ...(location ? { location } : {}), before: { ...(v ? { version_id: v } : {}), digest: was ? stateDigest(was) : null }, after: { digest: stateDigest(state) }, proof });
|
|
287
|
+
}
|
|
288
|
+
return { roots, engine: migrationEngine(planned, input, exec, lockOp) };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Plan a root against a state file: an override file switches its backend to
|
|
293
|
+
* that local file, in a data dir of its own, so the root's `.terraform` and
|
|
294
|
+
* its real state are never touched. The override file is removed whatever
|
|
295
|
+
* happens.
|
|
296
|
+
*/
|
|
297
|
+
async function proofPlan(run: Planned["run"], exec: BinaryExec, file: string, data: string, override: string): Promise<MigrationCheck> {
|
|
298
|
+
const at = join(run.dir, override);
|
|
299
|
+
const env = { ...run.env, TF_DATA_DIR: data };
|
|
300
|
+
writeFileSync(at, localBackendOverride(resolve(file)));
|
|
301
|
+
try {
|
|
302
|
+
await initRoot({ ...run, env, exec, reconfigure: true });
|
|
303
|
+
const read = await planStateCheck({ ...run, env, exec, planFile: `${data}.tfplan` });
|
|
304
|
+
return { changes: resourceChanges(read.json), summary: read.summary };
|
|
305
|
+
} finally {
|
|
306
|
+
rmSync(at, { force: true });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function migrationEngine(planned: Map<string, Planned>, input: TerraformMigrationInput, exec: BinaryExec, lockOp: LockOperation): StateMigrationEngine {
|
|
311
|
+
const log = input.log ?? (() => {});
|
|
312
|
+
const stores = new Map<string, StateStore>();
|
|
313
|
+
for (const [root, p] of planned) if (isStored(p.object)) stores.set(root, stateStore(p.object, p.run.dir, input.fetch));
|
|
314
|
+
const pinned = new Map<string, string>();
|
|
315
|
+
return {
|
|
316
|
+
async lock() {
|
|
317
|
+
const got = await takeLocksWithSources({ sources: [], stores: [...stores].map(([root, store]) => ({ root, store })), now: new Date().toISOString(), op: lockOp, who: input.who ?? `chant@${hostname()}` });
|
|
318
|
+
return async () => {
|
|
319
|
+
for (const l of got.locks.reverse()) await l.release().catch((e: unknown) => log(`${l.root}: the lock could not be released: ${(e as Error).message}`));
|
|
320
|
+
};
|
|
321
|
+
},
|
|
322
|
+
async current(root): Promise<MigrationStateAt> {
|
|
323
|
+
const p = planned.get(root)!;
|
|
324
|
+
const v = await versionNow(p.object, input.fetch, false);
|
|
325
|
+
const s = await pullState(exec, p.run.binary, root, p.run.dir, p.run.env);
|
|
326
|
+
return { ...(v ? { version_id: v } : {}), digest: s ? stateDigest(s) : null };
|
|
327
|
+
},
|
|
328
|
+
async write() {
|
|
329
|
+
// An azurerm state named by no version gets a snapshot first, so the record names what it was.
|
|
330
|
+
for (const [root, p] of planned) {
|
|
331
|
+
if (p.object.backend !== "azurerm") continue;
|
|
332
|
+
if (await versionNow(p.object, input.fetch, false)) continue;
|
|
333
|
+
const v = await versionNow(p.object, input.fetch, true);
|
|
334
|
+
if (v) pinned.set(root, v);
|
|
335
|
+
}
|
|
336
|
+
const order = [...planned].sort(([a, pa], [b, pb]) => pb.gained - pa.gained || (a < b ? -1 : 1));
|
|
337
|
+
for (const [root, p] of order) {
|
|
338
|
+
const store = stores.get(root);
|
|
339
|
+
// A state whose lock keeps the binary out (azurerm's lease) is written under it; the binary writes the others with the lock held for it.
|
|
340
|
+
if (store?.write) await store.write(readFileSync(p.file, "utf-8"));
|
|
341
|
+
else await pushStateFile({ ...p.run, exec, file: p.file, ...(store ? { lock: false } : {}) });
|
|
342
|
+
log(`${root}: wrote its new state`);
|
|
343
|
+
}
|
|
344
|
+
},
|
|
345
|
+
async verify(root) {
|
|
346
|
+
const p = planned.get(root)!;
|
|
347
|
+
const read = await planStateCheck({ ...p.run, exec, planFile: join(input.work, `verify-${root.replace(/[^\w.-]/g, "_")}.tfplan`), ...(stores.has(root) ? { lock: false } : {}) });
|
|
348
|
+
const v = await versionNow(p.object, input.fetch, true);
|
|
349
|
+
const was = pinned.get(root);
|
|
350
|
+
return { changes: resourceChanges(read.json), summary: read.summary, ...(v ? { version_id: v } : {}), ...(was ? { before_version_id: was } : {}) };
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
}
|