@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
package/src/drift-record.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* | `live-plan -json` | `ownership` | `bound[]`: in-sync, owned by its `source`. `unowned[]` and `adoptable[]`: unclaimed. `ABSENT`: pending. Any other omission: not-observed. `foreign[]`: undeclared, foreign. `controller_held[]`: runtime |
|
|
12
12
|
* | `live-ls -json` | `ownership` | `declared: false`: undeclared. A gap no live-plan row answers: not-observed |
|
|
13
13
|
* | live-plan and a plan together | `plan` | bound with a planned update or replace: drifted with paths, the live-plan ownership kept |
|
|
14
|
+
* | `show -json` of a live root's full plan | `plan` | planned create: missing. Planned delete or forget: undeclared. Update or any pair of actions: drifted with paths, declared then live. No-op: in-sync |
|
|
14
15
|
*
|
|
15
16
|
* A state read never says in-sync or drifted: `driftRecord` refuses it.
|
|
16
17
|
*
|
|
@@ -206,6 +207,63 @@ export function terraformPlanDriftRecords(input: TerraformPlanDriftInput): Drift
|
|
|
206
207
|
});
|
|
207
208
|
}
|
|
208
209
|
|
|
210
|
+
export interface TerraformLivePlanDriftInput extends DriftAdapterBase {
|
|
211
|
+
/** The engine that planned the root. Default `choudoufu`, which plans a live root. */
|
|
212
|
+
engine?: "choudoufu" | "terraform" | "tofu";
|
|
213
|
+
/** `show -json <planfile>` of the root's full plan, parsed. */
|
|
214
|
+
plan: unknown;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* A live root's records from its full plan, read as drift (#4812). A root
|
|
219
|
+
* under live resource markers takes no refresh-only plan, and its plan reads
|
|
220
|
+
* the live system, so what the plan would change is what moved outside the
|
|
221
|
+
* code: one record per managed instance in `resource_changes`, a planned
|
|
222
|
+
* create missing (the object no longer exists), a planned delete or forget
|
|
223
|
+
* undeclared (it exists outside the code), an update or any pair of actions
|
|
224
|
+
* drifted with the plan's paths, declared before and live after, and a
|
|
225
|
+
* no-op in-sync. A path whose declared value is known only after the apply
|
|
226
|
+
* is not a difference and is left out. `resource_drift` is not read.
|
|
227
|
+
*
|
|
228
|
+
* The rules are drift-rows' `live: true` read (`./drift-rows.ts`), so the
|
|
229
|
+
* records that are not in-sync are its rows. `choudoufuLivePlusPlanDriftRecords`
|
|
230
|
+
* is the read for a root whose `live-plan -json` was taken too: it keeps
|
|
231
|
+
* live-plan's ownership, which a plan alone does not give.
|
|
232
|
+
*/
|
|
233
|
+
export function terraformLivePlanDriftRecords(input: TerraformLivePlanDriftInput): DriftRecord[] {
|
|
234
|
+
const engine = input.engine ?? "choudoufu";
|
|
235
|
+
const doc = isObject(input.plan) ? input.plan : {};
|
|
236
|
+
const version = input.version ?? asString(doc.terraform_version);
|
|
237
|
+
const evidence: DriftEvidence = { tool: engine, ...(version ? { version } : {}), command: `${engine} show -json` };
|
|
238
|
+
const index = indexPlan(input.plan);
|
|
239
|
+
const types = new Map<string, string>();
|
|
240
|
+
for (const entry of asArray(doc.resource_changes)) {
|
|
241
|
+
if (isObject(entry) && asString(entry.address) && asString(entry.type)) types.set(entry.address as string, entry.type as string);
|
|
242
|
+
}
|
|
243
|
+
const out: DriftRecord[] = [];
|
|
244
|
+
for (const [address, change] of index.changes) {
|
|
245
|
+
if (isDataAddress(address)) continue;
|
|
246
|
+
const type = types.get(address);
|
|
247
|
+
const at = { ...common(input, engine, "plan", address), ...(type ? { resourceType: type } : {}), evidence };
|
|
248
|
+
const actions = change.actions.filter((a) => a !== "no-op" && a !== "read");
|
|
249
|
+
if (actions.length === 0) {
|
|
250
|
+
out.push(driftRecord({ ...at, status: "in-sync" }));
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (change.actions.length === 1 && actions[0] === "create") {
|
|
254
|
+
out.push(driftRecord({ ...at, status: "missing" }));
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (change.actions.length === 1 && (actions[0] === "delete" || actions[0] === "forget")) {
|
|
258
|
+
out.push(driftRecord({ ...at, status: "undeclared" }));
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const attributes = change.changes.filter((c) => c.after !== KNOWN_AFTER_APPLY).map((c) => attributeOf(c, true));
|
|
262
|
+
out.push(driftRecord({ ...at, status: "drifted", ...(attributes.length > 0 ? { attributes } : {}) }));
|
|
263
|
+
}
|
|
264
|
+
return out.sort(byAddress);
|
|
265
|
+
}
|
|
266
|
+
|
|
209
267
|
// ── choudoufu live-plan ────────────────────────────────────────────────────────
|
|
210
268
|
|
|
211
269
|
const BOUND_SOURCES: readonly DriftOwnershipBy[] = ["marker", "record", "derived", "cache"];
|
package/src/drift-rows.test.ts
CHANGED
|
@@ -10,16 +10,30 @@
|
|
|
10
10
|
import { readFileSync } from "node:fs";
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { describe, expect, test } from "vitest";
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
terraformDriftPlan,
|
|
15
|
+
terraformLivePlanDrift,
|
|
16
|
+
terraformPlanDriftChanges,
|
|
17
|
+
terraformPlanDriftCount,
|
|
18
|
+
terraformPlanDriftNames,
|
|
19
|
+
terraformPlanDriftRows,
|
|
20
|
+
} from "./drift-rows";
|
|
14
21
|
|
|
15
22
|
const FIX = join(import.meta.dirname, "__fixtures__", "drift-rows");
|
|
16
23
|
const read = (name: string): unknown => JSON.parse(readFileSync(join(FIX, name), "utf-8"));
|
|
24
|
+
const readAt = (...path: string[]): unknown => JSON.parse(readFileSync(join(import.meta.dirname, "__fixtures__", ...path), "utf-8"));
|
|
17
25
|
|
|
18
26
|
// ── terragucci's rules, copied as they are, for the parity checks ─────────────
|
|
19
27
|
|
|
20
28
|
type Json = Record<string, unknown>;
|
|
21
29
|
const FLIP: Record<string, string> = { create: "delete", delete: "create" };
|
|
22
30
|
|
|
31
|
+
function driftPlan(plan: unknown): unknown {
|
|
32
|
+
if (plan === null || typeof plan !== "object" || Array.isArray(plan)) return plan;
|
|
33
|
+
const p = plan as Json;
|
|
34
|
+
return { ...p, resource_changes: Array.isArray(p.resource_drift) ? p.resource_drift : [] };
|
|
35
|
+
}
|
|
36
|
+
|
|
23
37
|
function liveDrift(plan: unknown): unknown {
|
|
24
38
|
if (plan === null || typeof plan !== "object" || Array.isArray(plan)) return plan;
|
|
25
39
|
const p = plan as Json;
|
|
@@ -133,3 +147,78 @@ describe("documents with nothing to read", () => {
|
|
|
133
147
|
}
|
|
134
148
|
});
|
|
135
149
|
});
|
|
150
|
+
|
|
151
|
+
// ── the whole changes (#4812) ─────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
describe("whole changes", () => {
|
|
154
|
+
const stock = ["refresh-plan.json", "refresh-plan-module.json"].map(read);
|
|
155
|
+
const live = [read("live-root-plan.json"), readAt("live-plan-depth", "show-plan.json"), readAt("live-plan-depth", "show-plan-sensitive.json")];
|
|
156
|
+
|
|
157
|
+
test("a refresh-only plan's drift report plan is byte-identical to terragucci's driftPlan", () => {
|
|
158
|
+
for (const plan of stock) expect(JSON.stringify(terraformDriftPlan(plan))).toBe(JSON.stringify(driftPlan(plan)));
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test("a live root's full plan read as drift is byte-identical to terragucci's liveDrift", () => {
|
|
162
|
+
for (const plan of live) expect(JSON.stringify(terraformLivePlanDrift(plan))).toBe(JSON.stringify(liveDrift(plan)));
|
|
163
|
+
// And then as a drift report's plan, as terragucci's stage reads a live root.
|
|
164
|
+
for (const plan of live) expect(JSON.stringify(terraformDriftPlan(terraformLivePlanDrift(plan)))).toBe(JSON.stringify(driftPlan(liveDrift(plan))));
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("a stock change keeps module, index, deposed, the provider and the masks as the plan has them", () => {
|
|
168
|
+
const plan = read("refresh-plan-module.json") as { resource_drift: unknown[] };
|
|
169
|
+
const changes = terraformPlanDriftChanges(plan);
|
|
170
|
+
expect(changes).toEqual(plan.resource_drift);
|
|
171
|
+
expect(changes[0]).toMatchObject({ module_address: "module.service", index: "orders", provider_name: "registry.terraform.io/hashicorp/aws" });
|
|
172
|
+
expect(changes[0]!.change).toMatchObject({ before_sensitive: { kms_data_key: true }, after_sensitive: { kms_data_key: true }, after_unknown: {} });
|
|
173
|
+
expect(changes[1]).toMatchObject({ address: "aws_instance.web", deposed: "00000001", change: { actions: ["delete"], after: null } });
|
|
174
|
+
// Code waiting on main is not drift.
|
|
175
|
+
expect((terraformDriftPlan(plan) as { resource_changes: { address: string }[] }).resource_changes.map((c) => c.address)).toEqual([
|
|
176
|
+
'module.service.aws_sqs_queue.jobs["orders"]',
|
|
177
|
+
"aws_instance.web",
|
|
178
|
+
]);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("a live change is seen from the other side: code before, live after, masks swapped, an unknown taking the live value", () => {
|
|
182
|
+
const changes = terraformPlanDriftChanges(read("live-root-plan.json"), { live: true });
|
|
183
|
+
expect(changes.map((c) => [c.address, (c.change as { actions: string[] }).actions])).toEqual([
|
|
184
|
+
["aws_s3_bucket.assets", ["delete"]],
|
|
185
|
+
["aws_sqs_queue.stray", ["create"]],
|
|
186
|
+
["aws_lambda_function.api", ["update"]],
|
|
187
|
+
["aws_iam_role.deployer", ["update"]],
|
|
188
|
+
["aws_security_group.edge", ["update"]],
|
|
189
|
+
]);
|
|
190
|
+
expect(changes[2]!.change).toEqual({
|
|
191
|
+
actions: ["update"],
|
|
192
|
+
before: { function_name: "acme-api", memory_size: 512, version: "7" },
|
|
193
|
+
after: { function_name: "acme-api", memory_size: 256, version: "7" },
|
|
194
|
+
before_sensitive: false,
|
|
195
|
+
after_sensitive: false,
|
|
196
|
+
});
|
|
197
|
+
const sensitive = terraformPlanDriftChanges(readAt("live-plan-depth", "show-plan-sensitive.json"), { live: true });
|
|
198
|
+
const vpc = sensitive.find((c) => c.address === "aws_vpc.main")!.change as Json;
|
|
199
|
+
const source = (readAt("live-plan-depth", "show-plan-sensitive.json") as { resource_changes: { address: string; change: Json }[] }).resource_changes.find((c) => c.address === "aws_vpc.main")!.change;
|
|
200
|
+
expect(vpc.before_sensitive).toEqual(source.after_sensitive);
|
|
201
|
+
expect(vpc.after_sensitive).toEqual(source.before_sensitive);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test("one row per whole change, the same count either way", () => {
|
|
205
|
+
for (const plan of stock) expect(terraformPlanDriftRows(plan).map((r) => r.address)).toEqual(terraformPlanDriftChanges(plan).map((c) => c.address));
|
|
206
|
+
for (const plan of live) {
|
|
207
|
+
expect(terraformPlanDriftRows(plan, { live: true }).map((r) => r.address)).toEqual(terraformPlanDriftChanges(plan, { live: true }).map((c) => c.address));
|
|
208
|
+
expect(terraformPlanDriftCount(terraformLivePlanDrift(plan))).toBe(terraformPlanDriftCount(plan, { live: true }));
|
|
209
|
+
expect(terraformPlanDriftNames(terraformLivePlanDrift(plan))).toEqual(terraformPlanDriftNames(plan, { live: true }));
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test("a missing or malformed plan is returned as it is, with no changes", () => {
|
|
214
|
+
for (const plan of [undefined, null, "plan", []]) {
|
|
215
|
+
expect(terraformDriftPlan(plan)).toBe(plan);
|
|
216
|
+
expect(terraformLivePlanDrift(plan)).toBe(plan);
|
|
217
|
+
expect(terraformPlanDriftChanges(plan)).toEqual([]);
|
|
218
|
+
}
|
|
219
|
+
for (const plan of [{}, { resource_drift: "x" }]) {
|
|
220
|
+
expect(terraformDriftPlan(plan)).toEqual(driftPlan(plan));
|
|
221
|
+
expect(terraformLivePlanDrift(plan)).toEqual(liveDrift(plan));
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
});
|
package/src/drift-rows.ts
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Drift rows (#4580): one row per object a plan found drifted, by address,
|
|
3
3
|
* with its action and the object's real name, counted the way a product's
|
|
4
4
|
* drift report counts. `./drift-record.ts` answers a different question (the
|
|
5
|
-
* status of each instance the plan names), so it skips create
|
|
6
|
-
*
|
|
5
|
+
* status of each instance the plan names, redacted), so it skips create
|
|
6
|
+
* rows and carries no names.
|
|
7
7
|
*
|
|
8
8
|
* A stock root's refresh-only plan reports drift as `resource_drift`, and
|
|
9
9
|
* every entry there is one row, data blocks and creates included. A full
|
|
@@ -14,8 +14,15 @@
|
|
|
14
14
|
* Data blocks, no-op and read entries are not drift.
|
|
15
15
|
*
|
|
16
16
|
* These are terragucci's rules (packages/terragucci/src/report/drift.ts:
|
|
17
|
-
* `liveDrift`, `driftCount`, `driftNames`), so a row count here
|
|
18
|
-
* count its report gives for the same plan.
|
|
17
|
+
* `driftPlan`, `liveDrift`, `driftCount`, `driftNames`), so a row count here
|
|
18
|
+
* equals the count its report gives for the same plan.
|
|
19
|
+
*
|
|
20
|
+
* Behind every row is a whole change (#4812): the plan's entry for the
|
|
21
|
+
* object, shaped as a `resource_changes[]` entry with its actions, full
|
|
22
|
+
* before and after and their masks (`terraformPlanDriftChanges`). A drift
|
|
23
|
+
* report is a plan report over those changes: `terraformDriftPlan` puts a
|
|
24
|
+
* refresh-only plan's drift in place of its changes, and
|
|
25
|
+
* `terraformLivePlanDrift` reads a live root's full plan as drift.
|
|
19
26
|
*
|
|
20
27
|
* A row carries no attribute values. Its `name` is the first non-empty
|
|
21
28
|
* string among `name`, `id`, `bucket`, `function_name` and `arn`, read from
|
|
@@ -85,43 +92,107 @@ function stockAction(actions: readonly string[]): string {
|
|
|
85
92
|
return "update";
|
|
86
93
|
}
|
|
87
94
|
|
|
88
|
-
/**
|
|
89
|
-
function
|
|
90
|
-
|
|
91
|
-
return list.map((entry) => {
|
|
95
|
+
/** One row per whole change. */
|
|
96
|
+
function rowsOf(changes: readonly unknown[]): TerraformDriftRow[] {
|
|
97
|
+
return changes.map((entry) => {
|
|
92
98
|
const ch = isObject(entry) && isObject(entry.change) ? entry.change : {};
|
|
93
99
|
const actions = Array.isArray(ch.actions) ? ch.actions.map(String) : [];
|
|
94
100
|
return rowOf(entry, stockAction(actions), [ch.after, ch.before]);
|
|
95
101
|
});
|
|
96
102
|
}
|
|
97
103
|
|
|
98
|
-
/**
|
|
99
|
-
|
|
104
|
+
/**
|
|
105
|
+
* A live root's full plan, its changes read as drift: each one the plan
|
|
106
|
+
* would make, seen from the other side, as terragucci's `liveDrift` builds
|
|
107
|
+
* it. The code's value is before and the live value after, the masks swap
|
|
108
|
+
* with them, and a value the plan knows only after the apply takes the live
|
|
109
|
+
* one, since it is not a difference.
|
|
110
|
+
*/
|
|
111
|
+
function liveChanges(doc: Json): Json[] {
|
|
100
112
|
const list = Array.isArray(doc.resource_changes) ? doc.resource_changes : [];
|
|
101
|
-
const out:
|
|
113
|
+
const out: Json[] = [];
|
|
102
114
|
for (const entry of list) {
|
|
103
115
|
if (!isObject(entry) || entry.mode === "data") continue;
|
|
104
116
|
const ch = isObject(entry.change) ? entry.change : {};
|
|
105
117
|
const actions = Array.isArray(ch.actions) ? ch.actions.map(String) : [];
|
|
106
118
|
if (actions.length === 0 || actions.every((a) => a === "no-op" || a === "read")) continue;
|
|
107
119
|
const action = actions.length === 1 ? (FLIP[actions[0]!] ?? actions[0]!) : "update";
|
|
108
|
-
const live =
|
|
109
|
-
let code =
|
|
110
|
-
// A value the plan knows only after the apply is not a difference: the live one stands for it.
|
|
120
|
+
const live = (ch.before ?? null) as unknown;
|
|
121
|
+
let code = (ch.after ?? null) as unknown;
|
|
111
122
|
const unknown = isObject(ch.after_unknown) ? ch.after_unknown : {};
|
|
112
|
-
if (code
|
|
113
|
-
|
|
123
|
+
if (isObject(code) && isObject(live)) {
|
|
124
|
+
const known = live;
|
|
125
|
+
code = { ...code, ...Object.fromEntries(Object.keys(unknown).filter((k) => unknown[k] === true && k in known).map((k) => [k, known[k]])) };
|
|
126
|
+
}
|
|
127
|
+
out.push({
|
|
128
|
+
...entry,
|
|
129
|
+
change: { actions: [action], before: code, after: live, before_sensitive: ch.after_sensitive ?? false, after_sensitive: ch.before_sensitive ?? false },
|
|
130
|
+
});
|
|
114
131
|
}
|
|
115
132
|
return out;
|
|
116
133
|
}
|
|
117
134
|
|
|
135
|
+
/** A refresh-only plan's `resource_drift`, each entry as the plan has it. */
|
|
136
|
+
function stockChanges(doc: Json): Json[] {
|
|
137
|
+
return (Array.isArray(doc.resource_drift) ? [...doc.resource_drift] : []) as Json[];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The drift a plan (`show -json`, parsed) found as whole changes (#4812),
|
|
142
|
+
* one per drifted object in the plan's order, each shaped as a
|
|
143
|
+
* `resource_changes[]` entry: `address`, `mode`, `type`, `name`,
|
|
144
|
+
* `module_address`, `index`, `deposed` and `provider_name` as the plan has
|
|
145
|
+
* them, and `change` with its actions, its full before and after, and their
|
|
146
|
+
* masks. A stock root's are its `resource_drift` entries unchanged. A live
|
|
147
|
+
* root's are its full plan's changes seen from the other side: a create
|
|
148
|
+
* there is a `delete` (the object no longer exists), a delete a `create`
|
|
149
|
+
* (an object exists outside the code), any pair of actions an `update`, the
|
|
150
|
+
* code's value before and the live one after, the sensitive masks swapped
|
|
151
|
+
* with them and an unknown value replaced by the live one.
|
|
152
|
+
*
|
|
153
|
+
* Values are not redacted: a change carries what the plan carries, masks
|
|
154
|
+
* included, for a report that renders the plan. A drift record
|
|
155
|
+
* (`./drift-record.ts`) is the redacted read.
|
|
156
|
+
*
|
|
157
|
+
* Its length is the drift count, and `terraformPlanDriftRows` is one row
|
|
158
|
+
* per entry. A malformed `resource_drift` entry that is not an object is
|
|
159
|
+
* passed on as the plan has it, and its row has the address `""`.
|
|
160
|
+
*/
|
|
161
|
+
export function terraformPlanDriftChanges(plan: unknown, options: TerraformPlanDriftRowsOptions = {}): Record<string, unknown>[] {
|
|
162
|
+
if (!isObject(plan)) return [];
|
|
163
|
+
return options.live ? liveChanges(plan) : stockChanges(plan);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* A refresh-only plan as its drift report reads it: the drift found in place
|
|
168
|
+
* of the changes proposed, so the report is built from the same JSON as a
|
|
169
|
+
* plan's and code waiting on the default branch never shows in it.
|
|
170
|
+
* `resource_changes` becomes `terraformPlanDriftChanges(plan)`; the rest of
|
|
171
|
+
* the document is kept. Anything not an object is returned as it is.
|
|
172
|
+
*/
|
|
173
|
+
export function terraformDriftPlan(plan: unknown): unknown {
|
|
174
|
+
if (!isObject(plan)) return plan;
|
|
175
|
+
return { ...plan, resource_changes: terraformPlanDriftChanges(plan) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* A full plan of a root under live resource markers, as drift: its
|
|
180
|
+
* `resource_drift` becomes `terraformPlanDriftChanges(plan, { live: true })`
|
|
181
|
+
* and the rest of the document is kept, so it reads as a refresh-only plan
|
|
182
|
+
* would (`terraformDriftPlan`, and every function here without `live`).
|
|
183
|
+
* Anything not an object is returned as it is.
|
|
184
|
+
*/
|
|
185
|
+
export function terraformLivePlanDrift(plan: unknown): unknown {
|
|
186
|
+
if (!isObject(plan)) return plan;
|
|
187
|
+
return { ...plan, resource_drift: terraformPlanDriftChanges(plan, { live: true }) };
|
|
188
|
+
}
|
|
189
|
+
|
|
118
190
|
/**
|
|
119
191
|
* The drift a plan (`show -json`, parsed) found, one row per drifted object
|
|
120
192
|
* in the plan's order. Its length is the drift count.
|
|
121
193
|
*/
|
|
122
194
|
export function terraformPlanDriftRows(plan: unknown, options: TerraformPlanDriftRowsOptions = {}): TerraformDriftRow[] {
|
|
123
|
-
|
|
124
|
-
return options.live ? liveRows(plan) : stockRows(plan);
|
|
195
|
+
return rowsOf(terraformPlanDriftChanges(plan, options));
|
|
125
196
|
}
|
|
126
197
|
|
|
127
198
|
/** How many objects a plan found drifted: `terraformPlanDriftRows(plan, options).length`. */
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #4762: a pull request's copy of Terraform roots through chant core's
|
|
3
|
+
* prEnvUp and prEnvDown, with the binary faked (it records its arguments and
|
|
4
|
+
* answers a plan with the actions it is told) and the ports in memory. No
|
|
5
|
+
* binary, backend or ledger is reached.
|
|
6
|
+
*/
|
|
7
|
+
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { describe, expect, test } from "vitest";
|
|
11
|
+
import { prEnvDown, prEnvUp, type PrEnvApproval, type PrEnvPorts } from "@intentius/chant/components/pr-env-run";
|
|
12
|
+
import type { PrEnvRecord } from "@intentius/chant/components/pr-environment";
|
|
13
|
+
import { carriesSuffix, copyBackend, CopyRefusedError, suffixedKey, terraformPrEnvAdapter, terraformPrEnvTeardown, type CopyRoot } from "./pr-env";
|
|
14
|
+
import type { BinaryExec } from "./state/exec";
|
|
15
|
+
|
|
16
|
+
const HEAD = "b".repeat(40);
|
|
17
|
+
const tmp = (): string => mkdtempSync(join(tmpdir(), "chant-pr-env-"));
|
|
18
|
+
|
|
19
|
+
function ports(approval: PrEnvApproval, records: PrEnvRecord[] = []): PrEnvPorts & { records: PrEnvRecord[] } {
|
|
20
|
+
return { records, readRecords: async () => [...records], appendRecord: async (r) => void records.push(r), decideGate: async () => approval };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The binary: every call recorded with its root's directory; a plan of `actions`, a destroy of one delete. */
|
|
24
|
+
function fakeBinary(actions: string[] = ["create"]) {
|
|
25
|
+
const calls: string[] = [];
|
|
26
|
+
const exec: BinaryExec = async (_bin, args, dir) => {
|
|
27
|
+
calls.push(`${dir.split("/").at(-1)}: ${args.join(" ")}`);
|
|
28
|
+
if (args[0] === "show") {
|
|
29
|
+
const destroy = calls.some((c) => c.includes("-destroy") && c.includes(args.at(-1)!));
|
|
30
|
+
const acts = destroy ? ["delete"] : actions;
|
|
31
|
+
return { code: 0, stdout: JSON.stringify({ resource_changes: acts.map((a, i) => ({ address: `null_resource.r${i}`, mode: "managed", type: "null_resource", name: `r${i}`, change: { actions: [a], before: a === "create" ? null : {}, after: a === "delete" ? null : {} } })) }), out: "" };
|
|
32
|
+
}
|
|
33
|
+
return { code: 0, stdout: "", out: args[0] === "plan" ? "Plan: 1 to add, 0 to change, 0 to destroy." : "" };
|
|
34
|
+
};
|
|
35
|
+
return { exec, calls };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A root directory whose code declares `backend`. */
|
|
39
|
+
function rootWith(repo: string, name: string, backend: string): CopyRoot {
|
|
40
|
+
const dir = join(repo, name);
|
|
41
|
+
mkdirSync(dir, { recursive: true });
|
|
42
|
+
writeFileSync(join(dir, "main.tf"), `terraform {\n${backend}\n}\n`);
|
|
43
|
+
return { root: name, dir, binary: "terraform", env: {} };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe("a copy's backend", () => {
|
|
47
|
+
test("suffixes a key before .tfstate, a gcs prefix at its end, and a GitLab state's name and lock", () => {
|
|
48
|
+
expect(suffixedKey("envs/dev/terraform.tfstate", "pr-7")).toBe("envs/dev/terraform-pr-7.tfstate");
|
|
49
|
+
expect(suffixedKey("envs/dev/", "pr-7")).toBe("envs/dev-pr-7");
|
|
50
|
+
expect(carriesSuffix("s3://acme/net-pr-7.tfstate", "pr-7")).toBe(true);
|
|
51
|
+
expect(carriesSuffix("s3://acme/net-pr-70.tfstate", "pr-7")).toBe(false);
|
|
52
|
+
const repo = tmp();
|
|
53
|
+
const gcs = rootWith(repo, "net", 'backend "gcs" {\n bucket = "acme"\n prefix = "envs/net"\n}');
|
|
54
|
+
expect(copyBackend(gcs.dir, "net", "pr-7")).toEqual({ type: "gcs", attribute: "prefix", key: "envs/net-pr-7", location: "gs://acme/envs/net-pr-7" });
|
|
55
|
+
const a = "https://gitlab.example.com/api/v4/projects/7/terraform/state/net";
|
|
56
|
+
const http = rootWith(repo, "gl", `backend "http" {\n address = "${a}"\n lock_address = "${a}/lock"\n}`);
|
|
57
|
+
expect(copyBackend(http.dir, "gl", "pr-7")).toEqual({ type: "http", attribute: "address", key: `${a}-pr-7`, location: `${a}-pr-7`, extra: { lock_address: `${a}-pr-7/lock` } });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("refuses a cloud block, a backend with no key attribute, and a block that names no key", () => {
|
|
61
|
+
const repo = tmp();
|
|
62
|
+
expect(() => copyBackend(rootWith(repo, "c", 'cloud {\n organization = "acme"\n}').dir, "c", "pr-7")).toThrow(CopyRefusedError);
|
|
63
|
+
expect(() => copyBackend(rootWith(repo, "p", 'backend "pg" {\n conn_str = "x"\n}').dir, "p", "pr-7")).toThrow(/backend is pg/);
|
|
64
|
+
expect(() => copyBackend(rootWith(repo, "s", 'backend "s3" {\n bucket = "acme"\n}').dir, "s", "pr-7")).toThrow(/names no key/);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe("terraformPrEnvAdapter and terraformPrEnvTeardown", () => {
|
|
69
|
+
const S3 = (key: string) => `backend "s3" {\n bucket = "acme"\n key = "${key}"\n use_lockfile = true\n}`;
|
|
70
|
+
|
|
71
|
+
test("each root's copy inits under its suffixed key, waits at the gate, applies its saved plan, and is destroyed in reverse order", async () => {
|
|
72
|
+
const repo = tmp();
|
|
73
|
+
const roots = [rootWith(repo, "network", S3("network.tfstate")), rootWith(repo, "app", S3("app/terraform.tfstate"))];
|
|
74
|
+
const bin = fakeBinary();
|
|
75
|
+
const work = tmp();
|
|
76
|
+
const adapter = () => terraformPrEnvAdapter({ roots: async () => roots, work, exec: bin.exec, lockTimeout: false });
|
|
77
|
+
const waiting = await prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter: adapter(), ports: ports({ status: "pending" }) });
|
|
78
|
+
expect(waiting.exit).toBe(3);
|
|
79
|
+
expect(bin.calls.filter((c) => c.includes("apply"))).toEqual([]);
|
|
80
|
+
const p = ports({ status: "approved", approvedBy: ["bo"] });
|
|
81
|
+
const applied = await prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter: adapter(), ports: p });
|
|
82
|
+
expect(applied.exit).toBe(0);
|
|
83
|
+
expect(bin.calls).toContain("network: init -input=false -no-color -reconfigure -backend-config=key=network-pr-7.tfstate");
|
|
84
|
+
expect(bin.calls).toContain("app: init -input=false -no-color -reconfigure -backend-config=key=app/terraform-pr-7.tfstate");
|
|
85
|
+
expect(bin.calls.filter((c) => c.includes(": apply")).map((c) => c.split(":")[0])).toEqual(["network", "app"]);
|
|
86
|
+
expect(p.records[0]!.locations).toEqual({ network: "s3://acme/network-pr-7.tfstate", app: "s3://acme/app/terraform-pr-7.tfstate" });
|
|
87
|
+
|
|
88
|
+
bin.calls.length = 0;
|
|
89
|
+
let done = 0;
|
|
90
|
+
const teardown = terraformPrEnvTeardown({ name: "product", checkout: async () => ({ roots, done: () => void done++ }), work, exec: bin.exec, lockTimeout: false });
|
|
91
|
+
const down = await prEnvDown({ pr: 7, reason: "closed", ports: p, adapters: [teardown], commit: HEAD });
|
|
92
|
+
expect(down.report.status).toBe("destroyed");
|
|
93
|
+
expect(bin.calls.filter((c) => c.includes(": plan")).every((c) => c.includes("-destroy"))).toBe(true);
|
|
94
|
+
expect(bin.calls.filter((c) => c.includes(": apply")).map((c) => c.split(":")[0])).toEqual(["app", "network"]);
|
|
95
|
+
expect(done).toBe(1);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("a prepared root plans with no init of its own, and is refused when its recorded key is its own", async () => {
|
|
99
|
+
const repo = tmp();
|
|
100
|
+
const bin = fakeBinary();
|
|
101
|
+
const prepared = (key: string): CopyRoot => ({
|
|
102
|
+
root: "unit",
|
|
103
|
+
dir: join(repo, "unit"),
|
|
104
|
+
binary: "terraform",
|
|
105
|
+
prepare: async () => {
|
|
106
|
+
const dir = join(repo, "unit-cache");
|
|
107
|
+
mkdirSync(join(dir, ".terraform"), { recursive: true });
|
|
108
|
+
writeFileSync(join(dir, ".terraform", "terraform.tfstate"), JSON.stringify({ version: 3, backend: { type: "s3", config: { bucket: "acme", key } } }));
|
|
109
|
+
return { dir, env: {} };
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
const ok = terraformPrEnvAdapter({ roots: async () => [prepared("unit/terraform-pr-7.tfstate")], work: tmp(), exec: bin.exec, lockTimeout: false });
|
|
113
|
+
const r = await prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter: ok, ports: ports({ status: "approved" }) });
|
|
114
|
+
expect(r.exit).toBe(0);
|
|
115
|
+
expect(bin.calls.some((c) => c.includes("init"))).toBe(false);
|
|
116
|
+
const own = terraformPrEnvAdapter({ roots: async () => [prepared("unit/terraform.tfstate")], work: tmp(), exec: bin.exec, hint: "make remote_state read the suffix" });
|
|
117
|
+
const refused = await prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter: own, ports: ports({ status: "approved" }) });
|
|
118
|
+
expect(refused.report.status).toBe("plan-failed");
|
|
119
|
+
expect(own.refused).toBeInstanceOf(CopyRefusedError);
|
|
120
|
+
expect(own.refused!.message).toMatch(/root's own state, so its copy is refused; make remote_state read the suffix$/);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("a root no copy can be made of refuses the environment, and nothing plans", async () => {
|
|
124
|
+
const repo = tmp();
|
|
125
|
+
const bin = fakeBinary();
|
|
126
|
+
const adapter = terraformPrEnvAdapter({ roots: async () => [rootWith(repo, "c", 'cloud {\n organization = "acme"\n}')], work: tmp(), exec: bin.exec });
|
|
127
|
+
const r = await prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter, ports: ports({ status: "approved" }) });
|
|
128
|
+
expect(r.report.status).toBe("plan-failed");
|
|
129
|
+
expect(adapter.refused).toBeInstanceOf(CopyRefusedError);
|
|
130
|
+
expect(bin.calls).toEqual([]);
|
|
131
|
+
});
|
|
132
|
+
});
|