Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/src/content/docs/cli/state.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,16 @@ 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 <env>` (or `--live` against `<env>`) looks up `temporal.profiles.<env>` 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.

The K8s lexicon shells out to `kubectl get <kind> <name> [-n <namespace>] -o json` per declared entity. The cluster context comes from the user's `kubeconfig` — there's no separate profile model. Twenty common resource types (Deployment, Service, ConfigMap, Secret, Namespace, Pod, PVC, ServiceAccount, Job, CronJob, Ingress, NetworkPolicy, RBAC roles + bindings, ReplicaSet, StatefulSet, DaemonSet) are covered out of the box; CRDs and uncommon types are warn-skipped.

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 <env> --name <name> --resource-type <type> -o json` per declared entity. The `<env>` 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:
Expand Down
123 changes: 123 additions & 0 deletions lexicons/azure/src/describe-resources.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("node:child_process")>("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<string, unknown> }>) {
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();
});
});
106 changes: 106 additions & 0 deletions lexicons/azure/src/describe-resources.ts
Original file line number Diff line number Diff line change
@@ -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 <env> --name <name> --resource-type <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<string, string>;
}

function pruneUndefined<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {
const out: Record<string, unknown> = {};
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<string, { entityType: string; props: Record<string, unknown> }>;
}): Promise<Record<string, ResourceMetadata>> {
const result: Record<string, ResourceMetadata> = {};
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;
}
5 changes: 5 additions & 0 deletions lexicons/azure/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
};
Loading