diff --git a/docs/src/content/docs/cli/state.mdx b/docs/src/content/docs/cli/state.mdx index 4190cdde59..e04a9e3563 100644 --- a/docs/src/content/docs/cli/state.mdx +++ b/docs/src/content/docs/cli/state.mdx @@ -68,7 +68,7 @@ Output is grouped into six categories per lexicon: Drifted entries include attribute-level deltas (`status`, `physicalId`, `lastUpdated`, and each `attributes.*` key). -Lexicons that don't yet implement `describeResources()` are warn-skipped — `--live` doesn't fail the whole command for them. Today, **AWS**, **Temporal**, **K8s**, and **GCP** (via Config Connector) are covered. +Lexicons that don't yet implement `describeResources()` are warn-skipped — `--live` doesn't fail the whole command for them. Today, **AWS**, **Temporal**, **K8s**, **GCP** (via Config Connector), and **Azure** are covered. The Temporal lexicon resolves its connection via the chant config: `state snapshot ` (or `--live` against ``) looks up `temporal.profiles.` in your `chant.config.ts` and falls back to `temporal.defaultProfile`. The same profile model is used by `chant run`. With #39's entity-prop pass-through, namespaces/schedules/search-attributes are mapped back to chant entity names when the declared `props.name` (etc.) match the server-side identifier. @@ -76,6 +76,8 @@ The K8s lexicon shells out to `kubectl get [-n ] -o jso The GCP lexicon uses the same `kubectl` shell-out path against [Config Connector](https://cloud.google.com/config-connector) CRDs. The entity type's GVK derivation matches the serializer (`GCP::Storage::Bucket` → `storagebucket.storage.cnrm.cloud.google.com`), so any of the ~300 chant-supported GCP resources work without per-type configuration. `Ready=True` on the resource's status is mapped to `READY`; otherwise the condition's reason is surfaced. +The Azure lexicon shells out to `az resource show --resource-group --name --resource-type -o json` per declared entity. The `` argument is treated as the Azure resource group name. `properties.provisioningState` becomes the `status`. Top-level resources only — nested ARM types (e.g. `Microsoft.Storage/storageAccounts/blobServices`) are warn-skipped since `az resource show` doesn't accept compound type names directly. + ### Concurrent snapshots Snapshots are pushed to the orphan `chant/state` branch with `git push --force-with-lease`. If two operators (or a CI job + a human) take a snapshot for the same remote at the same time, the second push is **rejected** rather than silently overwriting the first. You'll see: diff --git a/lexicons/azure/src/describe-resources.test.ts b/lexicons/azure/src/describe-resources.test.ts new file mode 100644 index 0000000000..f44b3499ed --- /dev/null +++ b/lexicons/azure/src/describe-resources.test.ts @@ -0,0 +1,123 @@ +import { describe, test, expect, vi, beforeEach } from "vitest"; + +const execMock = vi.fn(); +vi.mock("node:child_process", async () => { + const actual = await vi.importActual("node:child_process"); + return { ...actual, exec: (cmd: string, cb: (err: Error | null, out: { stdout: string; stderr: string }) => void) => { + Promise.resolve(execMock(cmd)).then( + (out) => cb(null, out), + (err) => cb(err as Error, { stdout: "", stderr: "" }), + ); + } }; +}); + +const { describeResources } = await import("./describe-resources"); + +function makeEntities(records: Array<{ name: string; entityType: string; props: Record }>) { + return new Map(records.map((r) => [r.name, { entityType: r.entityType, props: r.props }])); +} + +describe("azure describeResources", () => { + beforeEach(() => { + execMock.mockReset(); + }); + + test("queries az resource show with rg + name + type and maps response", async () => { + let receivedCmd = ""; + execMock.mockImplementation((cmd: string) => { + receivedCmd = cmd; + return { + stdout: JSON.stringify({ + id: "/subscriptions/sub/resourceGroups/prod-rg/providers/Microsoft.Storage/storageAccounts/mydata", + name: "mydata", + type: "Microsoft.Storage/storageAccounts", + location: "eastus", + properties: { provisioningState: "Succeeded" }, + tags: { env: "prod" }, + }), + stderr: "", + }; + }); + + const entities = makeEntities([ + { name: "dataAccount", entityType: "Microsoft.Storage/storageAccounts", props: { name: "mydata" } }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["dataAccount"], entities }); + + expect(receivedCmd).toContain("az resource show"); + expect(receivedCmd).toContain("--resource-group prod-rg"); + expect(receivedCmd).toContain("--name mydata"); + expect(receivedCmd).toContain("--resource-type Microsoft.Storage/storageAccounts"); + + expect(result["dataAccount"]).toMatchObject({ + type: "Microsoft.Storage/storageAccounts", + physicalId: "/subscriptions/sub/resourceGroups/prod-rg/providers/Microsoft.Storage/storageAccounts/mydata", + status: "Succeeded", + attributes: expect.objectContaining({ location: "eastus", tags: { env: "prod" } }), + }); + }); + + test("missing provisioningState falls back to PRESENT", async () => { + execMock.mockResolvedValue({ + stdout: JSON.stringify({ id: "id", name: "x", type: "Microsoft.Network/virtualNetworks", location: "eastus", properties: {} }), + stderr: "", + }); + + const entities = makeEntities([ + { name: "vnet", entityType: "Microsoft.Network/virtualNetworks", props: { name: "x" } }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["vnet"], entities }); + + expect(result["vnet"].status).toBe("PRESENT"); + }); + + test("az failure (resource not found) leaves entity out", async () => { + execMock.mockImplementation(() => { throw new Error("ResourceNotFound: ..."); }); + + const entities = makeEntities([ + { name: "missing", entityType: "Microsoft.Storage/storageAccounts", props: { name: "missing" } }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["missing"], entities }); + + expect(result).toEqual({}); + }); + + test("nested-type entities are warn-skipped", async () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const entities = makeEntities([ + { name: "nested", entityType: "Microsoft.Storage/storageAccounts/blobServices", props: { name: "x" } }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["nested"], entities }); + + expect(result).toEqual({}); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("nested-type")); + expect(execMock).not.toHaveBeenCalled(); + warnSpy.mockRestore(); + }); + + test("non-Azure entity types are skipped", async () => { + const entities = makeEntities([ + { name: "x", entityType: "AWS::S3::Bucket", props: { name: "x" } }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["x"], entities }); + + expect(result).toEqual({}); + expect(execMock).not.toHaveBeenCalled(); + }); + + test("entity without name is silently skipped", async () => { + const entities = makeEntities([ + { name: "broken", entityType: "Microsoft.Storage/storageAccounts", props: {} }, + ]); + + const result = await describeResources({ environment: "prod-rg", buildOutput: "", entityNames: ["broken"], entities }); + + expect(result).toEqual({}); + expect(execMock).not.toHaveBeenCalled(); + }); +}); diff --git a/lexicons/azure/src/describe-resources.ts b/lexicons/azure/src/describe-resources.ts new file mode 100644 index 0000000000..06a3ddde9d --- /dev/null +++ b/lexicons/azure/src/describe-resources.ts @@ -0,0 +1,106 @@ +/** + * Live introspection of an Azure resource group via the az CLI. + * + * For each declared Azure entity, runs: + * az resource show --resource-group --name --resource-type -o json + * + * and maps the response to a ResourceMetadata entry keyed by chant entity name + * (using props.name from #39's entity-prop pass-through). The environment + * argument is treated as the Azure resource group name. + * + * Resource-not-found is silent — `state diff --live` then reports as missing. + * Nested resource types (e.g. `Microsoft.Storage/storageAccounts/blobServices`) + * are warn-skipped since `az resource show` doesn't accept them directly; they + * need a different query path. + */ + +import { exec } from "node:child_process"; +import { promisify } from "node:util"; +import type { ResourceMetadata } from "@intentius/chant/lexicon"; + +const execAsync = promisify(exec); + +interface AzResourceShowResponse { + id?: string; + name?: string; + type?: string; + location?: string; + properties?: { + provisioningState?: string; + [k: string]: unknown; + }; + tags?: Record; +} + +function pruneUndefined>(obj: T): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(obj)) { + if (v !== undefined) out[k] = v; + } + return out; +} + +/** + * Top-level ARM type — i.e. exactly one `/` separating provider from kind. + * Nested types like `Microsoft.Storage/storageAccounts/blobServices` need a + * different query path that this implementation doesn't yet support. + */ +function isTopLevelType(entityType: string): boolean { + const slashCount = (entityType.match(/\//g) ?? []).length; + return slashCount === 1; +} + +export async function describeResources(options: { + environment: string; + buildOutput: string; + entityNames: string[]; + entities: Map }>; +}): Promise> { + const result: Record = {}; + const skippedNested: string[] = []; + + for (const [entityName, { entityType, props }] of options.entities) { + if (!entityType.startsWith("Microsoft.")) continue; + + if (!isTopLevelType(entityType)) { + skippedNested.push(entityName); + continue; + } + + const name = props.name as string | undefined; + if (!name) continue; + + const cmd = [ + "az", "resource", "show", + "--resource-group", options.environment, + "--name", name, + "--resource-type", entityType, + "-o", "json", + ].join(" "); + + try { + const { stdout } = await execAsync(cmd); + const obj: AzResourceShowResponse = JSON.parse(stdout); + result[entityName] = { + type: entityType, + physicalId: obj.id, + status: obj.properties?.provisioningState ?? "PRESENT", + attributes: pruneUndefined({ + location: obj.location, + tags: obj.tags, + }), + }; + } catch { + // az returned non-zero (not found, auth, etc.) — leave entity out + } + } + + if (skippedNested.length > 0) { + // eslint-disable-next-line no-console + console.warn( + `[azure] skipped ${skippedNested.length} nested-type entity(ies) — az resource show doesn't accept compound types: ${skippedNested.slice(0, 5).join(", ")}${skippedNested.length > 5 ? ", ..." : ""}`, + ); + } + + return result; +} diff --git a/lexicons/azure/src/plugin.ts b/lexicons/azure/src/plugin.ts index 1b7f89b8ee..83ed606ba0 100644 --- a/lexicons/azure/src/plugin.ts +++ b/lexicons/azure/src/plugin.ts @@ -452,4 +452,9 @@ export const tags = defaultTags([ const { packageLexicon } = await import("./codegen/package"); return packageLexicon(opts); }, + + async describeResources(options) { + const { describeResources } = await import("./describe-resources"); + return describeResources(options); + }, };