@intentius/chant-lexicon-azure 0.124.39 → 0.124.41
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/components/arm-deploy.d.ts +81 -0
- package/dist/components/arm-deploy.d.ts.map +1 -0
- package/dist/components/arm-deploy.js +400 -0
- package/dist/components/capability-plugin.d.ts +6 -0
- package/dist/components/capability-plugin.d.ts.map +1 -0
- package/dist/components/capability-plugin.js +17 -0
- package/dist/components/index.d.ts +3 -0
- package/dist/components/index.d.ts.map +1 -0
- package/dist/components/index.js +2 -0
- package/dist/composites/container-app.d.ts.map +1 -1
- package/dist/composites/container-app.js +25 -8
- package/dist/deep-observe.d.ts +30 -0
- package/dist/deep-observe.d.ts.map +1 -1
- package/dist/deep-observe.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/integrity.json +2 -2
- package/dist/manifest.json +1 -1
- package/package.json +7 -2
- package/src/components/arm-deploy-floci.e2e.test.ts +80 -0
- package/src/components/arm-deploy.test.ts +260 -0
- package/src/components/arm-deploy.ts +493 -0
- package/src/components/capability-plugin.ts +26 -0
- package/src/components/index.ts +9 -0
- package/src/composites/composites.test.ts +39 -0
- package/src/composites/container-app.ts +30 -9
- package/src/deep-observe.ts +2 -2
- package/src/index.ts +3 -0
- package/src/plugin.test.ts +10 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `arm-deploy`: the azure lexicon's apply step for components (#4273). It
|
|
3
|
+
* applies a built ARM template into one resource group through `azApply`
|
|
4
|
+
* (../op/activities/az-apply.ts), the same per-resource applier `ApplyOp`'s
|
|
5
|
+
* `arm` target and the floci-az lane use, so a component step, an Op and the
|
|
6
|
+
* emulator run share one code path.
|
|
7
|
+
*
|
|
8
|
+
* `plan` reads each template resource live with the read client
|
|
9
|
+
* (../api/read-client.ts) and compares it with the body `azApply` would PUT,
|
|
10
|
+
* normalized with the noise rules deep observation uses
|
|
11
|
+
* (../deep-observe.ts). A resource that is not there is a create, one whose
|
|
12
|
+
* claimed properties all match is a no-op, and one that differs is an update
|
|
13
|
+
* with each changed path before and after. With `prune: true`, each
|
|
14
|
+
* chant-owned resource in the group the template no longer declares is a
|
|
15
|
+
* delete, the set `pruneArmOrphans` would delete.
|
|
16
|
+
*
|
|
17
|
+
* ARM's PUT is a create-or-update with no preview, so the plan cannot ask
|
|
18
|
+
* Azure what would change the way `cfn-deploy` asks for a change set. What
|
|
19
|
+
* holds the apply to the approved plan is the digest: `run` plans again and
|
|
20
|
+
* applies only when it gets the approved one.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { readFileSync } from "node:fs";
|
|
25
|
+
import type { Capability, CapabilityPlan, DeployContext, PlannedOutputs } from "@intentius/chant/components/capability";
|
|
26
|
+
import type { ChangeSetAttribute, ChangeSetEntry, ChangeSetHole, ChangeSetPart } from "@intentius/chant/change-set";
|
|
27
|
+
import { MASKED, UNRESOLVED, deepPathSet, flattenDeepProperties, normalizeDeepProperties } from "@intentius/chant/deep-observation";
|
|
28
|
+
import { diffDeep } from "@intentius/chant/lifecycle/deep-diff";
|
|
29
|
+
import { computePlanDigest } from "@intentius/chant/lifecycle/plan-digest";
|
|
30
|
+
import { AzureReadError, getResource, isNotFound, listResources, type AzureReadClientOptions } from "../api/read-client";
|
|
31
|
+
import { azureDeepNormalizationHooks, buildLiveProperties, type ArmResourceShowResponse } from "../deep-observe";
|
|
32
|
+
import { classifyArmFailure } from "../describe-resources";
|
|
33
|
+
import {
|
|
34
|
+
armDependencies,
|
|
35
|
+
azApply,
|
|
36
|
+
evalArm,
|
|
37
|
+
evalArmString,
|
|
38
|
+
isChantOwned,
|
|
39
|
+
orderArmResources,
|
|
40
|
+
rememberDeployed,
|
|
41
|
+
type ArmEvalCtx,
|
|
42
|
+
type ArmResource,
|
|
43
|
+
type AzHttp,
|
|
44
|
+
type AzNotPrunable,
|
|
45
|
+
} from "../op/activities/az-apply";
|
|
46
|
+
|
|
47
|
+
/** floci-az's local subscription, the applier's default too. */
|
|
48
|
+
const DEFAULT_SUBSCRIPTION = "00000000-0000-0000-0000-000000000001";
|
|
49
|
+
const DEFAULT_ENDPOINT = "https://management.azure.com";
|
|
50
|
+
const DEFAULT_LOCATION = "eastus";
|
|
51
|
+
|
|
52
|
+
export interface ArmDeployInput {
|
|
53
|
+
/** Path to the built ARM template (`deploymentTemplate.json`). */
|
|
54
|
+
template: string;
|
|
55
|
+
/** The resource group the template applies into. Default: the component's name. */
|
|
56
|
+
resourceGroup?: string;
|
|
57
|
+
/** Region for the group and for `resourceGroup().location`. Default: `eastus`. */
|
|
58
|
+
location?: string;
|
|
59
|
+
/** ARM endpoint. Default: `AZURE_ENDPOINT_URL`, else real Azure. */
|
|
60
|
+
endpoint?: string;
|
|
61
|
+
/** Subscription id. Default: `AZURE_SUBSCRIPTION_ID`, else floci-az's local subscription. */
|
|
62
|
+
subscriptionId?: string;
|
|
63
|
+
/** Delete chant-owned resources of the group the template no longer declares. Default: false. */
|
|
64
|
+
prune?: boolean;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ArmDeployOutput {
|
|
68
|
+
applied: Array<{ type: string; name: string }>;
|
|
69
|
+
pruned: Array<{ type: string; name: string; deleted: boolean }>;
|
|
70
|
+
notPrunable: AzNotPrunable[];
|
|
71
|
+
/** The template's `outputs`, evaluated against the group once it applied. */
|
|
72
|
+
outputs: Record<string, unknown>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What an `arm-deploy` plan hands `run` through `DeployContext.plans[resourceGroup]`. */
|
|
76
|
+
export interface ArmDeployPlanArtifact {
|
|
77
|
+
kind: "arm-deploy-plan";
|
|
78
|
+
resourceGroup: string;
|
|
79
|
+
planDigest: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isArmDeployPlanArtifact(value: unknown): value is ArmDeployPlanArtifact {
|
|
83
|
+
const v = value as Partial<ArmDeployPlanArtifact> | undefined;
|
|
84
|
+
return v?.kind === "arm-deploy-plan" && typeof v.resourceGroup === "string" && typeof v.planDigest === "string";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Thrown by `run` when planning again gives another digest than the approved
|
|
89
|
+
* plan: the group, the template or the endpoint moved since. Nothing is
|
|
90
|
+
* applied. `planMoved` is core's mark for a moved plan, so the command exits 3.
|
|
91
|
+
*/
|
|
92
|
+
export class ArmDeployPlanMovedError extends Error {
|
|
93
|
+
readonly planMoved = true;
|
|
94
|
+
constructor(
|
|
95
|
+
public readonly resourceGroup: string,
|
|
96
|
+
public readonly planned: string,
|
|
97
|
+
public readonly now: string,
|
|
98
|
+
) {
|
|
99
|
+
super(
|
|
100
|
+
`arm-deploy "${resourceGroup}": refusing to apply. Planning again gives ${now}, the approved plan was ${planned}; ` +
|
|
101
|
+
`the resource group or its template changed since. Plan it again.`,
|
|
102
|
+
);
|
|
103
|
+
this.name = "ArmDeployPlanMovedError";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The settings a step resolves to, environment included. Read at call time so a test or an emulator lane can set them. */
|
|
108
|
+
interface Target {
|
|
109
|
+
resourceGroup: string;
|
|
110
|
+
location: string;
|
|
111
|
+
endpoint: string;
|
|
112
|
+
subscriptionId: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function targetOf(ctx: DeployContext, input: ArmDeployInput): Target {
|
|
116
|
+
return {
|
|
117
|
+
resourceGroup: input.resourceGroup ?? ctx.component,
|
|
118
|
+
location: input.location ?? DEFAULT_LOCATION,
|
|
119
|
+
endpoint: (input.endpoint ?? process.env.AZURE_ENDPOINT_URL ?? DEFAULT_ENDPOINT).replace(/\/$/, ""),
|
|
120
|
+
subscriptionId: input.subscriptionId ?? process.env.AZURE_SUBSCRIPTION_ID ?? DEFAULT_SUBSCRIPTION,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function evalCtxOf(target: Target, http: AzHttp): ArmEvalCtx {
|
|
125
|
+
return {
|
|
126
|
+
subscriptionId: target.subscriptionId,
|
|
127
|
+
resourceGroup: target.resourceGroup,
|
|
128
|
+
location: target.location,
|
|
129
|
+
deployed: new Map(),
|
|
130
|
+
http,
|
|
131
|
+
base: target.endpoint,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function clientOf(target: Target, http: AzHttp): AzureReadClientOptions {
|
|
136
|
+
return { endpoint: target.endpoint, subscriptionId: target.subscriptionId, resourceGroup: target.resourceGroup, http };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface ArmTemplate {
|
|
140
|
+
resources?: ArmResource[];
|
|
141
|
+
outputs?: Record<string, { type?: string; value?: unknown }>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function readTemplate(path: string): ArmTemplate {
|
|
145
|
+
return JSON.parse(readFileSync(path, "utf8")) as ArmTemplate;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function templateDigest(path: string): string | null {
|
|
149
|
+
try {
|
|
150
|
+
return `sha256:${createHash("sha256").update(readFileSync(path)).digest("hex")}`;
|
|
151
|
+
} catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A 404 that means the resource is not there, as opposed to one that means the
|
|
158
|
+
* subscription is not: ARM answers `SubscriptionNotFound` with a 404 too, and
|
|
159
|
+
* planning every resource as a create on that answer would be wrong. A missing
|
|
160
|
+
* resource group is absence, since `azApply` creates the group first.
|
|
161
|
+
*/
|
|
162
|
+
function isAbsent(err: unknown): boolean {
|
|
163
|
+
return isNotFound(err) && !(err instanceof AzureReadError && /^SubscriptionNotFound$/i.test(err.code ?? ""));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── The declared side ────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/** An expression that reads a resource's runtime state, which only an apply knows. */
|
|
169
|
+
const RUNTIME_READ = /\b(reference|list[A-Za-z]*)\s*\(/;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Evaluate one string the way `azApply` would, leaving an expression that
|
|
173
|
+
* reads runtime state (`reference()`, `listKeys()`) or uses a function the
|
|
174
|
+
* evaluator lacks as written. The noise rules read a bracket expression on
|
|
175
|
+
* the declared side as unresolved, so it is never compared, and the plan
|
|
176
|
+
* makes no `listKeys` call.
|
|
177
|
+
*/
|
|
178
|
+
async function evalStaticString(s: string, ctx: ArmEvalCtx): Promise<unknown> {
|
|
179
|
+
if (!(s.startsWith("[") && s.endsWith("]")) || s.startsWith("[[")) return evalArmString(s, ctx);
|
|
180
|
+
if (RUNTIME_READ.test(s)) return s;
|
|
181
|
+
try {
|
|
182
|
+
return await evalArmString(s, ctx);
|
|
183
|
+
} catch {
|
|
184
|
+
return s;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function evalStatic(value: unknown, ctx: ArmEvalCtx): Promise<unknown> {
|
|
189
|
+
if (typeof value === "string") return evalStaticString(value, ctx);
|
|
190
|
+
if (Array.isArray(value)) return Promise.all(value.map((v) => evalStatic(v, ctx)));
|
|
191
|
+
if (value && typeof value === "object") {
|
|
192
|
+
const out: Record<string, unknown> = {};
|
|
193
|
+
for (const [k, v] of Object.entries(value)) out[String(await evalStaticString(k, ctx))] = await evalStatic(v, ctx);
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
return value;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The fields `azApply` PUTs for a resource, in the flat shape deep
|
|
201
|
+
* observation reads a live resource into. The ownership tags `azApply` adds
|
|
202
|
+
* are left out: the noise rules drop them from the live side too.
|
|
203
|
+
*/
|
|
204
|
+
async function declaredTree(resource: ArmResource, name: string, ctx: ArmEvalCtx): Promise<Record<string, unknown>> {
|
|
205
|
+
const body: ArmResourceShowResponse = { name };
|
|
206
|
+
if (resource.location !== undefined) body.location = (await evalStatic(resource.location, ctx)) as string;
|
|
207
|
+
for (const field of ["sku", "kind", "identity", "tags", "zones", "plan", "properties"] as const) {
|
|
208
|
+
if (resource[field] !== undefined) (body as Record<string, unknown>)[field] = await evalStatic(resource[field], ctx);
|
|
209
|
+
}
|
|
210
|
+
return buildLiveProperties(body, name);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── The plan ─────────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/** One template resource as the plan read it. */
|
|
216
|
+
interface PlannedResource {
|
|
217
|
+
resource: ArmResource;
|
|
218
|
+
name: string;
|
|
219
|
+
action: "create" | "update" | "no-op" | "unread";
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
interface ArmPlanResult {
|
|
223
|
+
entries: ChangeSetEntry[];
|
|
224
|
+
holes: ChangeSetHole[];
|
|
225
|
+
resources: PlannedResource[];
|
|
226
|
+
/** The live bodies read, remembered for `reference()`. */
|
|
227
|
+
live: ArmEvalCtx;
|
|
228
|
+
template: ArmTemplate;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function attributeOf(path: string, before: unknown, after: unknown, hasBefore: boolean, hasAfter: boolean): ChangeSetAttribute {
|
|
232
|
+
if (before === MASKED || after === MASKED) return { path, sensitive: true };
|
|
233
|
+
if (after === UNRESOLVED) return { path, ...(hasBefore ? { before } : {}), unknown: true };
|
|
234
|
+
return { path, ...(hasBefore ? { before } : {}), ...(hasAfter ? { after } : {}) };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Read the group and compare it with the template. Pure apart from GETs. */
|
|
238
|
+
async function readPlan(member: string, target: Target, input: ArmDeployInput, http: AzHttp): Promise<ArmPlanResult> {
|
|
239
|
+
const template = readTemplate(input.template);
|
|
240
|
+
const resources = template.resources ?? [];
|
|
241
|
+
const ctx = evalCtxOf(target, http);
|
|
242
|
+
const client = clientOf(target, http);
|
|
243
|
+
const entries: ChangeSetEntry[] = [];
|
|
244
|
+
const holes: ChangeSetHole[] = [];
|
|
245
|
+
const planned: PlannedResource[] = [];
|
|
246
|
+
const base = (type: string, name: string) => ({
|
|
247
|
+
member,
|
|
248
|
+
lexicon: "azure",
|
|
249
|
+
planner: "chant" as const,
|
|
250
|
+
address: `${type}/${name}`,
|
|
251
|
+
type,
|
|
252
|
+
name,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
for (const resource of orderArmResources(resources)) {
|
|
256
|
+
const name = String(await evalStaticString(resource.name, ctx));
|
|
257
|
+
const address = `${resource.type}/${name}`;
|
|
258
|
+
if (name.startsWith("[")) {
|
|
259
|
+
holes.push({ address, type: resource.type, reason: "the resource's name reads runtime state; known only at apply" });
|
|
260
|
+
planned.push({ resource, name, action: "unread" });
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const declaredRaw = await declaredTree(resource, name, ctx);
|
|
264
|
+
let live: ArmResourceShowResponse | undefined;
|
|
265
|
+
try {
|
|
266
|
+
live = (await getResource(client, resource.type, name, resource.apiVersion)) as ArmResourceShowResponse;
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if (!isAbsent(err)) {
|
|
269
|
+
const failure = classifyArmFailure(err);
|
|
270
|
+
holes.push({ address, type: resource.type, reason: `${failure.reason}: ${failure.detail}` });
|
|
271
|
+
planned.push({ resource, name, action: "unread" });
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const opts = { entityType: resource.type, hooks: azureDeepNormalizationHooks };
|
|
276
|
+
|
|
277
|
+
if (!live) {
|
|
278
|
+
const declared = normalizeDeepProperties(declaredRaw, { ...opts, side: "declared" });
|
|
279
|
+
const attributes = [...flattenDeepProperties(declared, { ...opts, side: "declared" })]
|
|
280
|
+
.map(([path, value]) => attributeOf(path, undefined, value, false, true))
|
|
281
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
282
|
+
entries.push({ ...base(resource.type, name), action: "create", attributes });
|
|
283
|
+
planned.push({ resource, name, action: "create" });
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
rememberDeployed(ctx, resource.type, name, live);
|
|
288
|
+
const liveRaw = buildLiveProperties(live, name);
|
|
289
|
+
const declared = normalizeDeepProperties(declaredRaw, { ...opts, side: "declared", counterpartPaths: deepPathSet(liveRaw) });
|
|
290
|
+
const liveTree = normalizeDeepProperties(liveRaw, { ...opts, side: "live", counterpartPaths: deepPathSet(declaredRaw) });
|
|
291
|
+
const diff = diffDeep({
|
|
292
|
+
declared: { [address]: { type: resource.type, properties: declared } },
|
|
293
|
+
live: { resources: { [address]: { type: resource.type, properties: liveTree } }, unobserved: {} },
|
|
294
|
+
hooks: azureDeepNormalizationHooks,
|
|
295
|
+
});
|
|
296
|
+
// A masked value ARM does not return (a password) is write-only, not a change.
|
|
297
|
+
const changes = (diff.drifted[0]?.changes ?? []).filter((c) => !(c.kind === "absent" && c.declared === MASKED));
|
|
298
|
+
const id = typeof live.id === "string" ? { id: live.id } : {};
|
|
299
|
+
if (changes.length === 0) {
|
|
300
|
+
entries.push({ ...base(resource.type, name), ...id, action: "no-op", attributes: [] });
|
|
301
|
+
planned.push({ resource, name, action: "no-op" });
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
const attributes = changes
|
|
305
|
+
.map((c) => attributeOf(c.path, c.live, c.declared, c.kind === "changed", true))
|
|
306
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
307
|
+
entries.push({ ...base(resource.type, name), ...id, action: "update", disruption: "in-place", attributes });
|
|
308
|
+
planned.push({ resource, name, action: "update" });
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (input.prune) {
|
|
312
|
+
// The set `pruneArmOrphans` deletes: chant-owned, of any type, and not declared by (type, name).
|
|
313
|
+
const keep = new Set(planned.map((p) => `${p.resource.type}\0${p.name}`));
|
|
314
|
+
try {
|
|
315
|
+
for (const item of await listResources(client)) {
|
|
316
|
+
if (typeof item.type !== "string" || typeof item.name !== "string") continue;
|
|
317
|
+
if (!isChantOwned(item.tags)) continue;
|
|
318
|
+
if (keep.has(`${item.type}\0${item.name}`)) continue;
|
|
319
|
+
entries.push({
|
|
320
|
+
...base(item.type, item.name),
|
|
321
|
+
...(typeof item.id === "string" ? { id: item.id } : {}),
|
|
322
|
+
action: "delete",
|
|
323
|
+
disruption: "destroy",
|
|
324
|
+
attributes: [],
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
} catch (err) {
|
|
328
|
+
if (!isAbsent(err)) {
|
|
329
|
+
const failure = classifyArmFailure(err);
|
|
330
|
+
holes.push({ address: target.resourceGroup, type: "Microsoft.Resources/resourceGroups", reason: `prune not read: ${failure.reason}: ${failure.detail}` });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
entries.sort((a, b) => a.address.localeCompare(b.address));
|
|
336
|
+
holes.sort((a, b) => a.address.localeCompare(b.address));
|
|
337
|
+
return { entries, holes, resources: planned, live: ctx, template };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function armPlanDigest(ctx: DeployContext, target: Target, input: ArmDeployInput, unresolved: string[], plan?: Pick<ArmPlanResult, "entries" | "holes">): string {
|
|
341
|
+
return computePlanDigest("arm-deploy-plan", {
|
|
342
|
+
env: ctx.env,
|
|
343
|
+
...target,
|
|
344
|
+
template: input.template,
|
|
345
|
+
templateDigest: templateDigest(input.template),
|
|
346
|
+
prune: input.prune ?? false,
|
|
347
|
+
unresolved,
|
|
348
|
+
...(plan ? { entries: plan.entries, holes: plan.holes } : {}),
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** The template's outputs evaluated against `ctx`, leaving out each one that evaluates to nothing. */
|
|
353
|
+
async function evaluateOutputs(
|
|
354
|
+
outputs: ArmTemplate["outputs"],
|
|
355
|
+
ctx: ArmEvalCtx,
|
|
356
|
+
only?: (name: string) => boolean,
|
|
357
|
+
): Promise<{ known: Record<string, unknown>; unknown: string[] }> {
|
|
358
|
+
const known: Record<string, unknown> = {};
|
|
359
|
+
const unknown: string[] = [];
|
|
360
|
+
for (const [name, output] of Object.entries(outputs ?? {})) {
|
|
361
|
+
if (only && !only(name)) {
|
|
362
|
+
unknown.push(name);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
let value: unknown;
|
|
366
|
+
try {
|
|
367
|
+
value = await evalArm(output?.value, ctx);
|
|
368
|
+
} catch {
|
|
369
|
+
value = undefined;
|
|
370
|
+
}
|
|
371
|
+
if (value === undefined) unknown.push(name);
|
|
372
|
+
else known[name] = value;
|
|
373
|
+
}
|
|
374
|
+
return { known, unknown: unknown.sort() };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* What the plan says of the template's outputs: an output whose value reads
|
|
379
|
+
* only resources the plan leaves as they are is known from the live read.
|
|
380
|
+
* Every other one is known only after apply.
|
|
381
|
+
*/
|
|
382
|
+
async function plannedOutputs(plan: ArmPlanResult): Promise<PlannedOutputs> {
|
|
383
|
+
const names = new Set(plan.resources.map((r) => r.resource.name));
|
|
384
|
+
const changing = new Set(plan.resources.filter((r) => r.action !== "no-op").map((r) => r.resource.name));
|
|
385
|
+
return evaluateOutputs(plan.template.outputs, plan.live, (name) => {
|
|
386
|
+
const value = plan.template.outputs?.[name]?.value;
|
|
387
|
+
const reads = armDependencies({ type: "", apiVersion: "", name: "", properties: value }, names);
|
|
388
|
+
return reads.every((r) => !changing.has(r));
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Read every template resource live and evaluate the template's outputs against them. */
|
|
393
|
+
async function liveOutputs(target: Target, input: ArmDeployInput, http: AzHttp): Promise<Record<string, unknown>> {
|
|
394
|
+
const template = readTemplate(input.template);
|
|
395
|
+
if (Object.keys(template.outputs ?? {}).length === 0) return {};
|
|
396
|
+
const ctx = evalCtxOf(target, http);
|
|
397
|
+
const client = clientOf(target, http);
|
|
398
|
+
for (const resource of orderArmResources(template.resources ?? [])) {
|
|
399
|
+
const name = String(await evalStaticString(resource.name, ctx));
|
|
400
|
+
if (name.startsWith("[")) continue;
|
|
401
|
+
try {
|
|
402
|
+
rememberDeployed(ctx, resource.type, name, await getResource(client, resource.type, name, resource.apiVersion));
|
|
403
|
+
} catch (err) {
|
|
404
|
+
if (!isAbsent(err)) throw err;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return (await evaluateOutputs(template.outputs, ctx)).known;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function planArmDeploy(http: AzHttp, ctx: DeployContext, input: ArmDeployInput): Promise<CapabilityPlan> {
|
|
411
|
+
const target = targetOf(ctx, input);
|
|
412
|
+
const member = target.resourceGroup;
|
|
413
|
+
const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
|
|
414
|
+
const memberOf = (planDigest: string, holes: ChangeSetHole[]): ChangeSetPart["member"] => ({
|
|
415
|
+
member,
|
|
416
|
+
lexicon: "azure",
|
|
417
|
+
planner: "chant",
|
|
418
|
+
status: "planned",
|
|
419
|
+
planDigest,
|
|
420
|
+
holes,
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
if (unresolved.length > 0) {
|
|
424
|
+
const planDigest = armPlanDigest(ctx, target, input, unresolved);
|
|
425
|
+
const hole = { address: member, type: "Microsoft.Resources/resourceGroups", reason: `inputs from ${unresolved.join(", ")}; re-checked on apply` };
|
|
426
|
+
return { member, planDigest, changeSet: { member: memberOf(planDigest, [hole]), entries: [] } };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const plan = await readPlan(member, target, input, http);
|
|
430
|
+
const planDigest = armPlanDigest(ctx, target, input, unresolved, plan);
|
|
431
|
+
const outputs = await plannedOutputs(plan);
|
|
432
|
+
// A plan with a hole hands `run` nothing to hold it to, as `cfn-deploy`'s does not.
|
|
433
|
+
const artifact: ArmDeployPlanArtifact | undefined = plan.holes.length === 0 ? { kind: "arm-deploy-plan", resourceGroup: member, planDigest } : undefined;
|
|
434
|
+
return {
|
|
435
|
+
member,
|
|
436
|
+
planDigest,
|
|
437
|
+
...(artifact ? { artifact } : {}),
|
|
438
|
+
changeSet: { member: memberOf(planDigest, plan.holes), entries: plan.entries },
|
|
439
|
+
outputs,
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* The `arm-deploy` capability over an injectable HTTP transport (the
|
|
445
|
+
* `AzHttp` seam `azApply` and the read client share). Tests pass a fake;
|
|
446
|
+
* the default is `fetch`. There is no rollback: like `gcp-apply`, it mutates
|
|
447
|
+
* with no undo, so COMP003 has a component acknowledge the gap.
|
|
448
|
+
*/
|
|
449
|
+
export function createArmDeployCapability(options: { http?: AzHttp } = {}): Capability<ArmDeployInput, ArmDeployOutput> {
|
|
450
|
+
const http: AzHttp = options.http ?? (async (method, url, body, signal) => {
|
|
451
|
+
const res = await fetch(url, {
|
|
452
|
+
method,
|
|
453
|
+
headers: body === undefined ? undefined : { "content-type": "application/json" },
|
|
454
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
455
|
+
signal,
|
|
456
|
+
});
|
|
457
|
+
return { status: res.status, text: await res.text() };
|
|
458
|
+
});
|
|
459
|
+
return {
|
|
460
|
+
kind: "arm-deploy",
|
|
461
|
+
rollbackPolicy: "needs-opt-out",
|
|
462
|
+
plan(ctx, input) {
|
|
463
|
+
return planArmDeploy(http, ctx, input);
|
|
464
|
+
},
|
|
465
|
+
outputs(ctx, input) {
|
|
466
|
+
return liveOutputs(targetOf(ctx, input), input, http);
|
|
467
|
+
},
|
|
468
|
+
async run(ctx, input) {
|
|
469
|
+
const target = targetOf(ctx, input);
|
|
470
|
+
const approved = ctx.plans?.[target.resourceGroup];
|
|
471
|
+
if (isArmDeployPlanArtifact(approved)) {
|
|
472
|
+
const now = await planArmDeploy(http, { env: ctx.env, component: ctx.component }, input);
|
|
473
|
+
if (now.planDigest !== approved.planDigest) throw new ArmDeployPlanMovedError(target.resourceGroup, approved.planDigest, now.planDigest);
|
|
474
|
+
}
|
|
475
|
+
const result = await azApply(
|
|
476
|
+
{
|
|
477
|
+
templatePath: input.template,
|
|
478
|
+
resourceGroup: target.resourceGroup,
|
|
479
|
+
location: target.location,
|
|
480
|
+
endpoint: target.endpoint,
|
|
481
|
+
subscriptionId: target.subscriptionId,
|
|
482
|
+
prune: input.prune ?? false,
|
|
483
|
+
},
|
|
484
|
+
undefined,
|
|
485
|
+
http,
|
|
486
|
+
);
|
|
487
|
+
return { ...result, outputs: await liveOutputs(target, input, http) };
|
|
488
|
+
},
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The default `arm-deploy` capability, over `fetch`. */
|
|
493
|
+
export const armDeployCapability: Capability<ArmDeployInput, ArmDeployOutput> = createArmDeployCapability();
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `azureCapabilityPlugin`: the azure lexicon's capability plugin (#4273). It
|
|
3
|
+
* contributes `arm-deploy` through core's `CapabilityPlugin` contract, so a
|
|
4
|
+
* project declaring `lexicons: ["azure"]` gets the verb registered when it
|
|
5
|
+
* runs components, the way the aws lexicon contributes `cfn-deploy`.
|
|
6
|
+
*/
|
|
7
|
+
import type { Capability } from "@intentius/chant/components/capability";
|
|
8
|
+
import { ownPackageVersion, type CapabilityPlugin } from "@intentius/chant/components/capability-plugin";
|
|
9
|
+
import { armDeployCapability } from "./arm-deploy";
|
|
10
|
+
|
|
11
|
+
export const AZURE_VERB_FAMILIES = {
|
|
12
|
+
apply: ["arm-deploy"],
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
export const azureCapabilityPlugin: CapabilityPlugin = {
|
|
16
|
+
name: "azure",
|
|
17
|
+
get version(): string {
|
|
18
|
+
return ownPackageVersion(import.meta.url);
|
|
19
|
+
},
|
|
20
|
+
capabilities(): Array<Capability<never, unknown>> {
|
|
21
|
+
return [armDeployCapability as Capability<never, unknown>];
|
|
22
|
+
},
|
|
23
|
+
families(): Record<string, readonly string[]> {
|
|
24
|
+
return AZURE_VERB_FAMILIES;
|
|
25
|
+
},
|
|
26
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { azureCapabilityPlugin, AZURE_VERB_FAMILIES } from "./capability-plugin";
|
|
2
|
+
export {
|
|
3
|
+
armDeployCapability,
|
|
4
|
+
createArmDeployCapability,
|
|
5
|
+
ArmDeployPlanMovedError,
|
|
6
|
+
type ArmDeployInput,
|
|
7
|
+
type ArmDeployOutput,
|
|
8
|
+
type ArmDeployPlanArtifact,
|
|
9
|
+
} from "./arm-deploy";
|
|
@@ -777,6 +777,45 @@ describe("ContainerAppNetwork", () => {
|
|
|
777
777
|
const { virtualNetwork } = ContainerAppNetwork({ name: "web", defaults: { virtualNetwork: { location: "westeurope" } } });
|
|
778
778
|
expect(p(virtualNetwork).location).toBe("westeurope");
|
|
779
779
|
});
|
|
780
|
+
|
|
781
|
+
type Inline = { name: string; properties: Record<string, unknown> };
|
|
782
|
+
|
|
783
|
+
test("defaults.subnet reaches the inline entry as well as the Subnet resource", () => {
|
|
784
|
+
const nsg = { id: "[resourceId('Microsoft.Network/networkSecurityGroups', 'web-nsg')]" };
|
|
785
|
+
const routeTable = { id: "[resourceId('Microsoft.Network/routeTables', 'web-rt')]" };
|
|
786
|
+
const { virtualNetwork, subnet } = ContainerAppNetwork({
|
|
787
|
+
name: "web",
|
|
788
|
+
defaults: { subnet: { networkSecurityGroup: nsg, routeTable } as any },
|
|
789
|
+
});
|
|
790
|
+
const inline = (p(virtualNetwork).subnets as Inline[])[0];
|
|
791
|
+
expect(p(subnet).networkSecurityGroup).toEqual(nsg);
|
|
792
|
+
expect(inline.properties.networkSecurityGroup).toEqual(nsg);
|
|
793
|
+
expect(inline.properties.routeTable).toEqual(routeTable);
|
|
794
|
+
const { name: _n, ...flat } = p(subnet);
|
|
795
|
+
expect(inline.properties).toEqual(flat);
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
test("defaults.virtualNetwork.subnets adds subnets after apps and keeps its delegation", () => {
|
|
799
|
+
const { virtualNetwork } = ContainerAppNetwork({
|
|
800
|
+
name: "web",
|
|
801
|
+
defaults: { virtualNetwork: { subnets: [{ name: "db", properties: { addressPrefix: "10.0.2.0/24" } }] } as any },
|
|
802
|
+
});
|
|
803
|
+
const subnets = p(virtualNetwork).subnets as Inline[];
|
|
804
|
+
expect(subnets.map((s) => s.name)).toEqual(["apps", "db"]);
|
|
805
|
+
const delegations = subnets[0].properties.delegations as Array<{ properties: { serviceName: string } }>;
|
|
806
|
+
expect(delegations[0].properties.serviceName).toBe("Microsoft.App/environments");
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
test("a caller's own apps entry in defaults.virtualNetwork.subnets is replaced by the merged one", () => {
|
|
810
|
+
const { virtualNetwork } = ContainerAppNetwork({
|
|
811
|
+
name: "web",
|
|
812
|
+
defaults: { virtualNetwork: { subnets: [{ name: "apps", properties: { addressPrefix: "10.9.0.0/23" } }] } as any },
|
|
813
|
+
});
|
|
814
|
+
const subnets = p(virtualNetwork).subnets as Inline[];
|
|
815
|
+
expect(subnets).toHaveLength(1);
|
|
816
|
+
expect(subnets[0].properties.addressPrefix).toBe("10.0.0.0/23");
|
|
817
|
+
expect(subnets[0].properties.delegations).toBeDefined();
|
|
818
|
+
});
|
|
780
819
|
});
|
|
781
820
|
|
|
782
821
|
// --- ContainerAppSite ---
|
|
@@ -65,25 +65,46 @@ export const ContainerAppNetwork = Composite((props: ContainerAppNetworkProps) =
|
|
|
65
65
|
const vnetName = `${name}-vnet`;
|
|
66
66
|
const delegations = [{ name: "apps", properties: { serviceName: "Microsoft.App/environments" } }];
|
|
67
67
|
|
|
68
|
+
const subnet = new Subnet(mergeDefaults({
|
|
69
|
+
name: `${vnetName}/apps`,
|
|
70
|
+
addressPrefix: subnetPrefix,
|
|
71
|
+
delegations,
|
|
72
|
+
}, defaults?.subnet), { apiVersion: "2023-05-01" });
|
|
73
|
+
|
|
68
74
|
// The subnet is also listed inline, as VnetDefault does, so a later
|
|
69
|
-
// deployment of the VNet does not try to remove it.
|
|
75
|
+
// deployment of the VNet does not try to remove it. The inline entry is
|
|
76
|
+
// built from the Subnet resource's merged props, so `defaults.subnet`
|
|
77
|
+
// reaches both copies. The apps entry always comes first; a caller's
|
|
78
|
+
// `defaults.virtualNetwork.subnets` adds the other subnets after it, and
|
|
79
|
+
// an entry of theirs named "apps" is replaced by this one.
|
|
80
|
+
const { subnets: extraSubnets, ...vnetDefaults } = (defaults?.virtualNetwork ?? {}) as {
|
|
81
|
+
subnets?: Array<{ name?: string }>;
|
|
82
|
+
} & Record<string, unknown>;
|
|
70
83
|
const virtualNetwork = new VirtualNetwork(mergeDefaults({
|
|
71
84
|
name: vnetName,
|
|
72
85
|
location,
|
|
73
86
|
tags: mergedTags,
|
|
74
87
|
addressSpace: { addressPrefixes: [addressSpace] },
|
|
75
|
-
subnets: [
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
addressPrefix: subnetPrefix,
|
|
81
|
-
delegations,
|
|
82
|
-
}, defaults?.subnet), { apiVersion: "2023-05-01" });
|
|
88
|
+
subnets: [
|
|
89
|
+
inlineSubnet("apps", subnetProps(subnet)),
|
|
90
|
+
...(extraSubnets ?? []).filter((s) => s?.name !== "apps"),
|
|
91
|
+
],
|
|
92
|
+
}, vnetDefaults), { apiVersion: "2023-05-01" });
|
|
83
93
|
|
|
84
94
|
return { virtualNetwork, subnet };
|
|
85
95
|
}, "ContainerAppNetwork");
|
|
86
96
|
|
|
97
|
+
/** A Subnet resource's props, flat or under `properties`. */
|
|
98
|
+
function subnetProps(subnet: InstanceType<typeof Subnet>): Record<string, unknown> {
|
|
99
|
+
return (subnet as unknown as { props: Record<string, unknown> }).props;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The VNet's inline entry for a subnet, from that Subnet resource's props. */
|
|
103
|
+
function inlineSubnet(name: string, props: Record<string, unknown>) {
|
|
104
|
+
const { name: _name, id: _id, properties, ...flat } = props;
|
|
105
|
+
return { name, properties: { ...flat, ...(properties as Record<string, unknown> | undefined) } };
|
|
106
|
+
}
|
|
107
|
+
|
|
87
108
|
export interface ContainerAppSiteProps {
|
|
88
109
|
/** Environment name; the workspace is `<name>-logs` and the identity `<name>-<app>`. */
|
|
89
110
|
name: string;
|
package/src/deep-observe.ts
CHANGED
|
@@ -67,7 +67,7 @@ import { AZURE_TAG_OWNERSHIP_KEYS } from "./ownership";
|
|
|
67
67
|
|
|
68
68
|
|
|
69
69
|
/** The full `az resource show -o json` shape this reader reads (a superset of the thin path's `AzResourceShowResponse`). */
|
|
70
|
-
interface ArmResourceShowResponse {
|
|
70
|
+
export interface ArmResourceShowResponse {
|
|
71
71
|
id?: string;
|
|
72
72
|
name?: string;
|
|
73
73
|
type?: string;
|
|
@@ -96,7 +96,7 @@ interface ArmResourceShowResponse {
|
|
|
96
96
|
* returned 200 is the declared name. The leaf is folded back to the declared
|
|
97
97
|
* spelling; a name that is not the leaf of the query is kept as returned.
|
|
98
98
|
*/
|
|
99
|
-
function buildLiveProperties(obj: ArmResourceShowResponse, queriedName?: string): Record<string, unknown> {
|
|
99
|
+
export function buildLiveProperties(obj: ArmResourceShowResponse, queriedName?: string): Record<string, unknown> {
|
|
100
100
|
const out: Record<string, unknown> = {};
|
|
101
101
|
if (obj.name !== undefined) {
|
|
102
102
|
out.name =
|
package/src/index.ts
CHANGED
|
@@ -17,6 +17,9 @@ export { defaultTags, type TagEntry, type DefaultTags } from "./default-tags";
|
|
|
17
17
|
export { deploymentScope, isDeploymentScope, type DeploymentScope, type DeployScope } from "./deploy-scopes";
|
|
18
18
|
export { azureSerializer } from "./serializer";
|
|
19
19
|
export { azurePlugin } from "./plugin";
|
|
20
|
+
// Core's capability-plugin loader scans this package's exports and loads
|
|
21
|
+
// `azureCapabilityPlugin` when a project's chant.config lists this lexicon (#4273).
|
|
22
|
+
export { azureCapabilityPlugin } from "./components/capability-plugin";
|
|
20
23
|
export { Parameter } from "./parameter";
|
|
21
24
|
|
|
22
25
|
// Deep observation (#1086): the `az resource show` reader and the noise
|