cdk-real-drift 0.4.5 → 0.4.7

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/README.md CHANGED
@@ -355,25 +355,25 @@ CI (with `--yes`).
355
355
  leave cells natural-width. Don't chase pixel alignment at the cost of a
356
356
  readable diff. -->
357
357
 
358
- | option | meaning |
359
- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
360
- | `--region <r>` | a stack's own `env.region` ALWAYS wins; for an env-AGNOSTIC stack (no `env`) it falls back to `--region` (or `$AWS_REGION` / `$AWS_DEFAULT_REGION`), else the `--profile`'s region |
361
- | `--profile <p>` | AWS profile (or `$AWS_PROFILE`) |
362
- | `-a, --app <cmd\|cdk.out>` | CDK app command or pre-synthesized assembly dir (or `$CDKRD_APP` / cdk.json `"app"`); stack auto-discovery + construct paths |
363
- | `-c, --context key=value` | context for synth (repeatable; cdk.json is the base layer) |
364
- | `--all` | target every stack the app defines (the default when no `<stack>` is named; overrides any positional names) |
365
- | `--json` | machine-readable output (see [JSON contract](#json-output-contract)) |
366
- | `--fail` | (check) exit 1 on drift and never prompt; for scripts/CI. Without it, check reports drift but exits 0 |
367
- | `--strict` | (check) exit 1 when coverage is incomplete. A coverage gap is always surfaced loudly; `--strict` makes it CI-failing. Orthogonal to `--fail` |
368
- | `--show-all` | (check) inventory mode: show all current undeclared state, ignoring the baseline |
369
- | `--verbose` / `-v` | (check) expand the `info:` footer tiers / (revert) expand the not-revertable summary to full lists; (record) itemizes nested sub-keys in the multiselect |
370
- | `--pre-deploy` | (check) compare live vs the LOCAL synth template: the declared drift your next `cdk deploy` would silently overwrite |
371
- | `--undeclared-only` | (check) undeclared drift only: pair cdkrd with `cdk drift` for the declared side |
372
- | `--declared-only` | (check) declared drift vs the deployed template only (undeclared tier skipped; baseline untouched). Not `--pre-deploy` |
373
- | `--dry-run` | (revert) print the plan; make no changes |
374
- | `--wait[=DURATION]` | (revert) on a transient "resource is mid-update" error (e.g. Route53Resolver `RSLVR-00705`) keep retrying until it settles, up to DURATION (default `10m`; e.g. `--wait=5m`, `--wait=90s`) |
375
- | `--remove-unrecorded` | (revert, and check for its inline revert) REMOVE unrecorded values + DELETE unrecorded added resources in a no-prompt run (`--yes`/CI); an interactive revert already lists them |
376
- | `--yes` / `-y` | skip confirmations (revert apply; record records all without the multiselect) |
358
+ | option | meaning |
359
+ | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
360
+ | `--region <r>` | a stack's own `env.region` ALWAYS wins; for an env-AGNOSTIC stack (no `env`) it falls back to `--region` (or `$AWS_REGION` / `$AWS_DEFAULT_REGION`), else the AWS-CLI/cdk region chain — the active profile's region, then the `[default]` profile's region, then EC2 IMDS |
361
+ | `--profile <p>` | AWS profile (or `$AWS_PROFILE`) |
362
+ | `-a, --app <cmd\|cdk.out>` | CDK app command or pre-synthesized assembly dir (or `$CDKRD_APP` / cdk.json `"app"`); stack auto-discovery + construct paths |
363
+ | `-c, --context key=value` | context for synth (repeatable; cdk.json is the base layer) |
364
+ | `--all` | target every stack the app defines (the default when no `<stack>` is named; overrides any positional names) |
365
+ | `--json` | machine-readable output (see [JSON contract](#json-output-contract)) |
366
+ | `--fail` | (check) exit 1 on drift and never prompt; for scripts/CI. Without it, check reports drift but exits 0 |
367
+ | `--strict` | (check) exit 1 when coverage is incomplete. A coverage gap is always surfaced loudly; `--strict` makes it CI-failing. Orthogonal to `--fail` |
368
+ | `--show-all` | (check) inventory mode: show all current undeclared state, ignoring the baseline |
369
+ | `--verbose` / `-v` | (check) expand the `info:` footer tiers / (revert) expand the not-revertable summary to full lists; (record) itemizes nested sub-keys in the multiselect |
370
+ | `--pre-deploy` | (check) compare live vs the LOCAL synth template: the declared drift your next `cdk deploy` would silently overwrite |
371
+ | `--undeclared-only` | (check) undeclared drift only: pair cdkrd with `cdk drift` for the declared side |
372
+ | `--declared-only` | (check) declared drift vs the deployed template only (undeclared tier skipped; baseline untouched). Not `--pre-deploy` |
373
+ | `--dry-run` | (revert) print the plan; make no changes |
374
+ | `--wait[=DURATION]` | (revert) on a transient "resource is mid-update" error (e.g. Route53Resolver `RSLVR-00705`) keep retrying until it settles, up to DURATION (default `10m`; e.g. `--wait=5m`, `--wait=90s`) |
375
+ | `--remove-unrecorded` | (revert, and check for its inline revert) REMOVE unrecorded values + DELETE unrecorded added resources in a no-prompt run (`--yes`/CI); an interactive revert already lists them |
376
+ | `--yes` / `-y` | skip confirmations (revert apply; record records all without the multiselect) |
377
377
 
378
378
  Unknown options (`--apq`) and options missing their value (`--app` at the end of
379
379
  the line) are errors (exit `2`): a typo'd flag never silently becomes a stack name.
package/dist/cli.js CHANGED
@@ -4,13 +4,14 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
6
6
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
7
+ import { homedir } from "node:os";
7
8
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, Toolkit } from "@aws-cdk/toolkit-lib";
8
9
  import { CloudFormationClient, DescribeStackResourcesCommand, DescribeStacksCommand, DescribeTypeCommand, GetTemplateCommand, ListExportsCommand, ListStackResourcesCommand } from "@aws-sdk/client-cloudformation";
9
10
  import { KMSClient, ListAliasesCommand } from "@aws-sdk/client-kms";
10
11
  import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand, UpdateRestApiCommand } from "@aws-sdk/client-api-gateway";
11
12
  import { AppConfigClient, ListConfigurationProfilesCommand, ListEnvironmentsCommand } from "@aws-sdk/client-appconfig";
12
13
  import { AppSyncClient, ListApiKeysCommand, ListDataSourcesCommand, ListFunctionsCommand, ListResolversCommand, ListTypesCommand } from "@aws-sdk/client-appsync";
13
- import { ApiGatewayV2Client, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand, UpdateStageCommand } from "@aws-sdk/client-apigatewayv2";
14
+ import { ApiGatewayV2Client, DeleteAccessLogSettingsCommand, DeleteRouteSettingsCommand, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand, UpdateStageCommand } from "@aws-sdk/client-apigatewayv2";
14
15
  import { CloudWatchLogsClient, DescribeMetricFiltersCommand, DescribeSubscriptionFiltersCommand, PutBearerTokenAuthenticationCommand, PutMetricFilterCommand } from "@aws-sdk/client-cloudwatch-logs";
15
16
  import { CognitoIdentityProviderClient, ListGroupsCommand, ListResourceServersCommand, ListUserPoolClientsCommand } from "@aws-sdk/client-cognito-identity-provider";
16
17
  import { DescribeAddressesCommand, DescribeClientVpnAuthorizationRulesCommand, DescribeClientVpnEndpointsCommand, DescribeClientVpnTargetNetworksCommand, DescribeLaunchTemplateVersionsCommand, DescribeNetworkAclsCommand, DescribeRouteTablesCommand, DescribeSubnetsCommand, EC2Client, ModifyClientVpnEndpointCommand } from "@aws-sdk/client-ec2";
@@ -989,15 +990,68 @@ async function discoverStacks(app, opts = {}) {
989
990
 
990
991
  //#endregion
991
992
  //#region src/commands/resolve-stacks.ts
993
+ function regionFromIniFile(path, section) {
994
+ let text;
995
+ try {
996
+ text = readFileSync(path, "utf8");
997
+ } catch {
998
+ return;
999
+ }
1000
+ let inSection = false;
1001
+ for (const raw of text.split(/\r?\n/)) {
1002
+ const line = raw.trim();
1003
+ if (!line || line.startsWith("#") || line.startsWith(";")) continue;
1004
+ const header = /^\[([^\]]+)\]$/.exec(line);
1005
+ if (header) {
1006
+ inSection = header[1].trim() === section;
1007
+ continue;
1008
+ }
1009
+ if (inSection) {
1010
+ const m = /^region\s*=\s*(\S+)/.exec(line);
1011
+ if (m) return m[1];
1012
+ }
1013
+ }
1014
+ }
1015
+ function defaultProfileRegionFromIni() {
1016
+ const home = homedir();
1017
+ const credPath = process.env.AWS_SHARED_CREDENTIALS_FILE || join(home, ".aws", "credentials");
1018
+ const cfgPath = process.env.AWS_CONFIG_FILE || join(home, ".aws", "config");
1019
+ return regionFromIniFile(credPath, "default") ?? regionFromIniFile(cfgPath, "default");
1020
+ }
1021
+ async function regionFromImds() {
1022
+ if (process.env.AWS_EC2_METADATA_DISABLED === "true") return void 0;
1023
+ const base = "http://169.254.169.254";
1024
+ const ac = new AbortController();
1025
+ const timer = setTimeout(() => ac.abort(), 1e3);
1026
+ try {
1027
+ const tokenRes = await fetch(`${base}/latest/api/token`, {
1028
+ method: "PUT",
1029
+ headers: { "x-aws-ec2-metadata-token-ttl-seconds": "60" },
1030
+ signal: ac.signal
1031
+ });
1032
+ const headers = {};
1033
+ if (tokenRes.ok) headers["x-aws-ec2-metadata-token"] = (await tokenRes.text()).trim();
1034
+ const regionRes = await fetch(`${base}/latest/meta-data/placement/region`, {
1035
+ headers,
1036
+ signal: ac.signal
1037
+ });
1038
+ if (!regionRes.ok) return void 0;
1039
+ const region = (await regionRes.text()).trim();
1040
+ return region.length > 0 ? region : void 0;
1041
+ } catch {
1042
+ return;
1043
+ } finally {
1044
+ clearTimeout(timer);
1045
+ }
1046
+ }
992
1047
  async function resolveProfileRegion(profile) {
993
1048
  try {
994
1049
  const client = new CloudControlClient(profile ? { profile } : {});
995
1050
  const region = await client.config.region();
996
1051
  client.destroy();
997
- return typeof region === "string" && region.length > 0 ? region : void 0;
998
- } catch {
999
- return;
1000
- }
1052
+ if (typeof region === "string" && region.length > 0) return region;
1053
+ } catch {}
1054
+ return defaultProfileRegionFromIni() ?? await regionFromImds();
1001
1055
  }
1002
1056
  async function resolveStacks(a) {
1003
1057
  const app = resolveApp(a.app);
@@ -11754,16 +11808,46 @@ const writeApiGatewayV2Stage = async (ctx, ops) => {
11754
11808
  if (!apiId || !stageName) throw new Error("cannot resolve ApiId|StageName for ApiGatewayV2 Stage revert");
11755
11809
  const desired = applyOps({ ...ctx.declared }, ops);
11756
11810
  const touched = new Set(ops.map((o) => o.path.replace(/^\//, "").split("/")[0]).filter((p) => !!p));
11811
+ const isCleared = (field) => desired[field] === void 0 && ops.some((o) => o.op === "remove" && o.path.replace(/^\//, "").split("/")[0] === field);
11812
+ const clearedSubKeys = (field) => {
11813
+ const keys = /* @__PURE__ */ new Set();
11814
+ for (const o of ops) {
11815
+ if (o.op !== "remove") continue;
11816
+ const segs = o.path.replace(/^\//, "").split("/");
11817
+ if (segs[0] !== field) continue;
11818
+ if (segs.length >= 2 && segs[1]) keys.add(segs[1]);
11819
+ else for (const k of Object.keys(asRecord(o.prior))) keys.add(k);
11820
+ }
11821
+ return [...keys];
11822
+ };
11823
+ const client = new ApiGatewayV2Client({ region: ctx.region });
11824
+ if (touched.has("AccessLogSettings") && isCleared("AccessLogSettings")) await client.send(new DeleteAccessLogSettingsCommand({
11825
+ ApiId: apiId,
11826
+ StageName: stageName
11827
+ }));
11828
+ if (touched.has("RouteSettings") && isCleared("RouteSettings")) for (const routeKey of clearedSubKeys("RouteSettings")) await client.send(new DeleteRouteSettingsCommand({
11829
+ ApiId: apiId,
11830
+ StageName: stageName,
11831
+ RouteKey: routeKey
11832
+ }));
11757
11833
  const input = {
11758
11834
  ApiId: apiId,
11759
11835
  StageName: stageName
11760
11836
  };
11761
11837
  for (const p of touched) {
11762
11838
  if (!APIGWV2_STAGE_UPDATE_FIELDS.has(p)) continue;
11839
+ if (p === "AccessLogSettings" && isCleared("AccessLogSettings")) continue;
11840
+ if (p === "RouteSettings" && isCleared("RouteSettings")) continue;
11841
+ if (p === "StageVariables" && isCleared("StageVariables")) {
11842
+ const tombstones = {};
11843
+ for (const k of clearedSubKeys("StageVariables")) tombstones[k] = "";
11844
+ if (Object.keys(tombstones).length > 0) input.StageVariables = tombstones;
11845
+ continue;
11846
+ }
11847
+ if (isCleared(p)) continue;
11763
11848
  input[p] = desired[p];
11764
11849
  }
11765
- if (Object.keys(input).length <= 2) return;
11766
- await new ApiGatewayV2Client({ region: ctx.region }).send(new UpdateStageCommand(input));
11850
+ if (Object.keys(input).length > 2) await client.send(new UpdateStageCommand(input));
11767
11851
  };
11768
11852
  const writeApiGatewayRestApiPolicy = async (ctx) => {
11769
11853
  const restApiId = str(ctx.physicalId) ?? str(ctx.declared["RestApiId"]);