@grada-run/grada 0.40.17 → 0.41.0
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/package.json +1 -1
- package/src/commands/add.js +2 -1
- package/src/commands/apply.js +114 -6
- package/src/commands/doctor.js +39 -24
- package/src/commands/drift.js +13 -0
- package/src/commands/gc.js +81 -14
- package/src/commands/init.js +4 -2
- package/src/core/parser.js +13 -6
- package/src/utils/aws.js +27 -22
- package/src/utils/file-lock.js +0 -22
- package/src/utils/hcl.js +5 -2
- package/src/utils/reconcile.js +40 -0
package/package.json
CHANGED
package/src/commands/add.js
CHANGED
|
@@ -480,7 +480,8 @@ resource "aws_subnet" "db_isolated" {
|
|
|
480
480
|
|
|
481
481
|
// Idempotently appends the isolated-subnet block to network.tf content.
|
|
482
482
|
// Returns the content unchanged when the block already exists. Uses the
|
|
483
|
-
//
|
|
483
|
+
// line-anchored lookup so a `#` comment quoting the header never
|
|
484
|
+
// false-positives.
|
|
484
485
|
export function ensureIsolatedSubnets(networkTfContent) {
|
|
485
486
|
const content = String(networkTfContent ?? '');
|
|
486
487
|
if (findResourceBlock(content, 'aws_subnet', 'db_isolated')) return content;
|
package/src/commands/apply.js
CHANGED
|
@@ -5,18 +5,20 @@ import color from 'picocolors';
|
|
|
5
5
|
import { renderDryRunPreview, parseTerraformConfig, buildCostTelemetryProps } from '../utils/visualizer.js';
|
|
6
6
|
import { detectFramework } from '../utils/detector.js';
|
|
7
7
|
import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
8
|
-
import { failCommand, shouldAutoApprove, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
|
|
8
|
+
import { failCommand, isProgrammaticCall, shouldAutoApprove, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
|
|
9
9
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
10
10
|
import { spawnSync } from 'child_process';
|
|
11
11
|
import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, checkOutputsContract, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } from '../utils/terraform.js';
|
|
12
12
|
import { classifyTerraformError, countRecreateCollisions, getRunbook, ERROR_CODES } from '../utils/terraform-errors.js';
|
|
13
13
|
import { readInitManifest, recordAppliedTarget } from '../utils/backup.js';
|
|
14
|
-
import { requireManagedTree } from '../utils/terraform-metadata.js';
|
|
15
|
-
import { readTerraformComputeTarget } from '../utils/resolvers.js';
|
|
14
|
+
import { requireManagedTree, parseStateBucketBackend } from '../utils/terraform-metadata.js';
|
|
15
|
+
import { readTerraformComputeTarget, resolveRegion } from '../utils/resolvers.js';
|
|
16
16
|
import { requireAwakeEnvironment, resolveSleepTarget, guardSleepingEnv } from '../utils/sleep-state.js';
|
|
17
17
|
import { promptStateBucketRecovery, recreateStateBucket } from '../utils/recovery.js';
|
|
18
18
|
import { resolveProjectName, readResourceSuffix } from '../utils/resolvers.js';
|
|
19
19
|
import { ensureLambdaSeedImage } from '../utils/lambda-ecr.js';
|
|
20
|
+
import { checkAwsCredentials, ensureStateBucketExists, printAwsAuthGuidance } from '../utils/aws.js';
|
|
21
|
+
import { findUnreconciledFiles, isValidAccountId, PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
|
|
20
22
|
import { runWake } from './wake.js';
|
|
21
23
|
|
|
22
24
|
export function parseApplyArgs(argv = []) {
|
|
@@ -24,12 +26,106 @@ export function parseApplyArgs(argv = []) {
|
|
|
24
26
|
if (args[0] === 'apply' || args[0] === 'deploy') args.shift();
|
|
25
27
|
const { options, unknown } = parseFlags(args, {
|
|
26
28
|
boolean: ['force', 'destroy-previous-target', 'force-resume', 'allow-partial-outputs', 'headless', 'auto-approve', 'dry-run'],
|
|
27
|
-
string: ['force-unlock'],
|
|
29
|
+
string: ['force-unlock', 'account-id'],
|
|
28
30
|
});
|
|
29
31
|
if (unknown.length > 0) options.unknownFlags = unknown;
|
|
30
32
|
return { force: false, ...options };
|
|
31
33
|
}
|
|
32
34
|
|
|
35
|
+
// Offline reconcile: an `init --offline` tree carries
|
|
36
|
+
// YOUR_AWS_ACCOUNT_ID placeholders instead of an account id and has no
|
|
37
|
+
// state bucket. Resolve the account (explicit flag, else STS ground
|
|
38
|
+
// truth), confirm once, rewrite the files, and ensure the bucket —
|
|
39
|
+
// afterwards the normal flow sees a reconciled tree. Returns
|
|
40
|
+
// { proceed: true } or { proceed: false, result } carrying the
|
|
41
|
+
// refusal/failure for the caller to return.
|
|
42
|
+
export async function reconcileOfflineTree({ targetDir, options = {}, projectName }) {
|
|
43
|
+
const files = findUnreconciledFiles(targetDir);
|
|
44
|
+
let accountId;
|
|
45
|
+
let source;
|
|
46
|
+
const flag = options.accountId;
|
|
47
|
+
if (flag !== undefined && flag !== null) {
|
|
48
|
+
if (!isValidAccountId(flag)) {
|
|
49
|
+
return {
|
|
50
|
+
proceed: false,
|
|
51
|
+
result: await failCommand({
|
|
52
|
+
noExit: isProgrammaticCall(options),
|
|
53
|
+
message: `\n✖ Invalid --account-id "${flag}": ${describeAccountIdShape(flag)}.\n`,
|
|
54
|
+
event: 'infrastructure_applied',
|
|
55
|
+
telemetry: { projectName },
|
|
56
|
+
errorCode: 'INVALID_ACCOUNT_ID',
|
|
57
|
+
reason: 'invalid-account-id',
|
|
58
|
+
}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
accountId = flag;
|
|
62
|
+
source = 'flag';
|
|
63
|
+
} else {
|
|
64
|
+
try {
|
|
65
|
+
accountId = (await checkAwsCredentials(resolveRegion(options, targetDir))).accountId;
|
|
66
|
+
source = 'sts';
|
|
67
|
+
} catch {
|
|
68
|
+
printAwsAuthGuidance(options);
|
|
69
|
+
return {
|
|
70
|
+
proceed: false,
|
|
71
|
+
result: await failCommand({
|
|
72
|
+
noExit: isProgrammaticCall(options),
|
|
73
|
+
message: '\n✖ Could not resolve the AWS account: configure credentials first — apply cannot provision without them.\n',
|
|
74
|
+
event: 'infrastructure_applied',
|
|
75
|
+
telemetry: { projectName },
|
|
76
|
+
errorCode: 'AWS_CREDENTIALS_MISSING',
|
|
77
|
+
reason: 'aws-credentials-missing',
|
|
78
|
+
}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const from = source === 'flag' ? '--account-id' : 'AWS credentials';
|
|
83
|
+
log.message(`Reconciling ${files.length} offline placeholder file(s) with account ${color.cyan(accountId)} (from ${from}):`);
|
|
84
|
+
for (const file of files) log.message(` ${color.dim('-')} ${file}`);
|
|
85
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
86
|
+
message: '\n✖ apply needs approval to reconcile offline placeholders.',
|
|
87
|
+
hint: ' Re-run with --auto-approve to reconcile non-interactively.\n',
|
|
88
|
+
event: 'infrastructure_applied',
|
|
89
|
+
telemetry: { projectName },
|
|
90
|
+
errorCode: 'RECONCILE_NON_INTERACTIVE',
|
|
91
|
+
});
|
|
92
|
+
if (refused) return { proceed: false, result: refused };
|
|
93
|
+
if (!shouldAutoApprove(options)) {
|
|
94
|
+
const confirmed = await confirm({
|
|
95
|
+
message: 'Rewrite the placeholders and ensure the state bucket?',
|
|
96
|
+
initialValue: false,
|
|
97
|
+
});
|
|
98
|
+
if (confirmed !== true) {
|
|
99
|
+
cancel('Reconcile aborted.');
|
|
100
|
+
process.exit(0);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
for (const file of files) {
|
|
104
|
+
const abs = path.join(targetDir, file);
|
|
105
|
+
fs.writeFileSync(abs, fs.readFileSync(abs, 'utf8').split(PLACEHOLDER_ACCOUNT_ID).join(accountId));
|
|
106
|
+
}
|
|
107
|
+
log.message(color.green(`Rewrote ${files.length} file(s).`));
|
|
108
|
+
const backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
|
|
109
|
+
const { bucket, region: backendRegion } = parseStateBucketBackend(backend);
|
|
110
|
+
const ensured = await ensureStateBucketExists({
|
|
111
|
+
region: backendRegion ?? resolveRegion(options, targetDir),
|
|
112
|
+
bucket,
|
|
113
|
+
});
|
|
114
|
+
trackEvent('apply_reconciled', {
|
|
115
|
+
projectName,
|
|
116
|
+
account_source: source,
|
|
117
|
+
file_count: files.length,
|
|
118
|
+
bucket_created: ensured.created,
|
|
119
|
+
});
|
|
120
|
+
return { proceed: true };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function describeAccountIdShape(value) {
|
|
124
|
+
const text = String(value);
|
|
125
|
+
if (!/^\d+$/.test(text)) return 'expected exactly 12 digits, got non-digit characters';
|
|
126
|
+
return `expected exactly 12 digits, got ${text.length}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
33
129
|
// Unlock-and-retry flow for a stale Terraform state lock. Headless
|
|
34
130
|
// refuses unless `--force-unlock <id>` was passed; interactive asks once.
|
|
35
131
|
// Retries the apply exactly once, skipping the already-confirmed preview.
|
|
@@ -213,14 +309,26 @@ async function applyStackMain(input = {}) {
|
|
|
213
309
|
});
|
|
214
310
|
}
|
|
215
311
|
|
|
216
|
-
// 1a.
|
|
312
|
+
// 1a. Offline reconcile: an `init --offline` tree still carries
|
|
313
|
+
// account placeholders and has no state bucket — resolve, confirm,
|
|
314
|
+
// rewrite, and ensure it before anything reads the files. Dry runs
|
|
315
|
+
// only warn: previews change nothing.
|
|
316
|
+
const unreconciled = findUnreconciledFiles(targetDir);
|
|
317
|
+
if (unreconciled.length > 0 && !options.isDryRun) {
|
|
318
|
+
const reconciled = await reconcileOfflineTree({ targetDir, options, projectName: path.basename(targetDir) });
|
|
319
|
+
if (!reconciled.proceed) return reconciled.result;
|
|
320
|
+
} else if (unreconciled.length > 0) {
|
|
321
|
+
log.warn(color.yellow('⚠ This tree still carries offline account placeholders. Run a real apply to reconcile it.'));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// 1b. Surface an interrupted previous run. Informational only — the
|
|
217
325
|
// new run overwrites the marker when it starts.
|
|
218
326
|
const lastRun = readLastRunMarker(targetDir);
|
|
219
327
|
if (isInterruptedMarker(lastRun)) {
|
|
220
328
|
log.warn(color.yellow(`⚠ Previous ${lastRun.command || 'terraform'} run was interrupted (started ${lastRun.startedAt || 'unknown'}). If it died mid-apply, review with ${color.green('cd terraform && terraform plan')} before trusting this run.`));
|
|
221
329
|
}
|
|
222
330
|
|
|
223
|
-
//
|
|
331
|
+
// 1c. Refuse to apply against an asleep environment: apply resets
|
|
224
332
|
// the app desired count while the database stays stopped, so fresh
|
|
225
333
|
// tasks would crash-loop. Dry runs change nothing, so they keep the
|
|
226
334
|
// historical advisory warning instead of the shared gate.
|
package/src/commands/doctor.js
CHANGED
|
@@ -155,40 +155,52 @@ async function checkStateLock({ cwd, s3Client, deep }) {
|
|
|
155
155
|
const keyMatch = backend.match(/key\s*=\s*"([^"]+)"/);
|
|
156
156
|
const stateKey = keyMatch ? keyMatch[1] : 'terraform.tfstate';
|
|
157
157
|
const client = s3Client ?? new S3Client({ region: region ?? 'us-east-2' });
|
|
158
|
-
|
|
158
|
+
// Workspace states live under `env:/<name>/`, outside the default key
|
|
159
|
+
// prefix — list both so a stuck preview lock surfaces with its
|
|
160
|
+
// workspace instead of reporting a false "no lock".
|
|
161
|
+
const lockKeys = [];
|
|
159
162
|
try {
|
|
160
|
-
|
|
161
|
-
|
|
163
|
+
for (const prefix of [stateKey, 'env:/']) {
|
|
164
|
+
const resp = await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix }));
|
|
165
|
+
for (const entry of resp.Contents || []) {
|
|
166
|
+
if (typeof entry.Key === 'string' && entry.Key.endsWith('.tflock')) lockKeys.push(entry.Key);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
162
169
|
} catch (error) {
|
|
163
170
|
if (error?.name === 'NoSuchBucket') return { ok: true, note: 'state bucket absent' };
|
|
164
171
|
return { ok: true, skipped: 'state bucket unreachable' };
|
|
165
172
|
}
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
173
|
+
const uniqueLocks = [...new Set(lockKeys)];
|
|
174
|
+
if (uniqueLocks.length === 0) return { ok: true };
|
|
175
|
+
const detailLines = [];
|
|
176
|
+
for (const lockKey of uniqueLocks) {
|
|
177
|
+
detailLines.push(`Lock file ${lockKey} is present in the state bucket${workspaceSuffix(lockKey)}.`);
|
|
178
|
+
if (deep) {
|
|
179
|
+
try {
|
|
180
|
+
const obj = await client.send(new GetObjectCommand({ Bucket: bucket, Key: lockKey }));
|
|
181
|
+
const text = typeof obj.Body?.transformToString === 'function'
|
|
182
|
+
? await obj.Body.transformToString()
|
|
183
|
+
: '';
|
|
184
|
+
const info = JSON.parse(text);
|
|
185
|
+
const who = info.Who ?? info.who ?? 'unknown holder';
|
|
186
|
+
const operation = info.Operation ?? info.operation ?? 'unknown operation';
|
|
187
|
+
const created = info.Created ?? info.created ?? 'unknown time';
|
|
188
|
+
detailLines.push(`Held by ${who} (${operation}, since ${created}).`);
|
|
189
|
+
} catch {
|
|
190
|
+
// The lock itself is the finding; holder detail is best-effort.
|
|
191
|
+
}
|
|
184
192
|
}
|
|
185
193
|
}
|
|
186
194
|
return { ok: false, detailLines };
|
|
187
195
|
}
|
|
188
196
|
|
|
189
|
-
//
|
|
190
|
-
//
|
|
191
|
-
|
|
197
|
+
// `env:/pr-12/terraform.tfstate.tflock` → ` (workspace pr-12)`; the
|
|
198
|
+
// default key reports bare, as before.
|
|
199
|
+
function workspaceSuffix(lockKey) {
|
|
200
|
+
const match = /^env:\/([^/]+)\//.exec(lockKey);
|
|
201
|
+
return match ? ` (workspace ${match[1]})` : '';
|
|
202
|
+
}
|
|
203
|
+
|
|
192
204
|
// Project check: an open `repo:*` OIDC trust lets any GitHub repo's
|
|
193
205
|
// Actions assume the deploy role. Warning-grade (pre-fix trees render it
|
|
194
206
|
// by default): surfaces yellow without flipping the verdict red. List
|
|
@@ -208,6 +220,9 @@ function checkOidcTrustScope({ cwd }) {
|
|
|
208
220
|
};
|
|
209
221
|
}
|
|
210
222
|
|
|
223
|
+
// Project check: a leftover interrupted/running marker means the last
|
|
224
|
+
// Terraform run never settled. Warning-grade (apply proceeds with its own
|
|
225
|
+
// warning): surfaces yellow without flipping the verdict red.
|
|
211
226
|
function checkInterruptedRun({ cwd }) {
|
|
212
227
|
const marker = readLastRunMarker(cwd);
|
|
213
228
|
if (!isInterruptedMarker(marker)) return { ok: true };
|
package/src/commands/drift.js
CHANGED
|
@@ -209,6 +209,19 @@ async function runDriftMain(input = {}) {
|
|
|
209
209
|
encoding: 'utf8',
|
|
210
210
|
maxBuffer: 32 * 1024 * 1024,
|
|
211
211
|
});
|
|
212
|
+
if (planResult?.error?.code === 'ENOBUFS') {
|
|
213
|
+
s.stop(color.red('Terraform plan output too large.'));
|
|
214
|
+
return failCommand({
|
|
215
|
+
noExit,
|
|
216
|
+
message: '\n✖ terraform plan output exceeded the 32MB buffer.\n',
|
|
217
|
+
hint: ' Narrow the plan with -target, or run terraform plan directly for the full output.\n',
|
|
218
|
+
event: 'drift_run',
|
|
219
|
+
telemetry: { projectName, action: 'check' },
|
|
220
|
+
errorCode: 'TERRAFORM_PLAN_TOO_LARGE',
|
|
221
|
+
reason: 'terraform-plan-too-large',
|
|
222
|
+
resultExtra: { region },
|
|
223
|
+
});
|
|
224
|
+
}
|
|
212
225
|
const status = planResult?.status;
|
|
213
226
|
if (status === 0) {
|
|
214
227
|
s.stop(color.green('No drift.'));
|
package/src/commands/gc.js
CHANGED
|
@@ -3,8 +3,8 @@ import path from 'path';
|
|
|
3
3
|
import { spawnSync } from 'child_process';
|
|
4
4
|
import { ECRClient, DescribeRepositoriesCommand, DescribeImagesCommand, BatchDeleteImageCommand } from '@aws-sdk/client-ecr';
|
|
5
5
|
import { CloudWatchLogsClient, DescribeLogGroupsCommand, DeleteLogGroupCommand } from '@aws-sdk/client-cloudwatch-logs';
|
|
6
|
-
import { ECSClient, ListServicesCommand } from '@aws-sdk/client-ecs';
|
|
7
|
-
import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand } from '@aws-sdk/client-ec2';
|
|
6
|
+
import { ECSClient, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
|
|
7
|
+
import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand, DescribeSubnetsCommand } from '@aws-sdk/client-ec2';
|
|
8
8
|
import { SecretsManagerClient, ListSecretsCommand } from '@aws-sdk/client-secrets-manager';
|
|
9
9
|
import color from 'picocolors';
|
|
10
10
|
import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
|
|
@@ -230,26 +230,75 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
|
|
|
230
230
|
// predicate — exact project tag only. Foreign and untagged VPCs land in
|
|
231
231
|
// reportOnly, never in deletable, so prefix lookalikes (`myapp-evil`)
|
|
232
232
|
// and legacy resources can never enter the deletion set.
|
|
233
|
-
|
|
233
|
+
// Live VPC ids behind running (or desired) ECS services: services →
|
|
234
|
+
// awsvpc subnets → VPCs. Fail-closed like the preview-log-group
|
|
235
|
+
// liveness: any client error resolves `unknown` instead of guessing.
|
|
236
|
+
export async function discoverLiveVpcIds({ ecsClient = null, cluster = null, ec2Client = null } = {}) {
|
|
237
|
+
const vpcIds = new Set();
|
|
238
|
+
try {
|
|
239
|
+
if (!ecsClient || !cluster || !ec2Client) return { vpcIds, unknown: false };
|
|
240
|
+
let nextToken;
|
|
241
|
+
const arns = [];
|
|
242
|
+
do {
|
|
243
|
+
const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 }));
|
|
244
|
+
arns.push(...(resp.serviceArns || []));
|
|
245
|
+
nextToken = resp.nextToken;
|
|
246
|
+
} while (nextToken);
|
|
247
|
+
const subnetIds = new Set();
|
|
248
|
+
for (const batch of chunkArray(arns, 10)) {
|
|
249
|
+
const desc = await ecsClient.send(new DescribeServicesCommand({ cluster, services: batch }));
|
|
250
|
+
for (const svc of desc.services || []) {
|
|
251
|
+
// Desired counts: a crash-looping preview runs nothing
|
|
252
|
+
// yet is unambiguously live.
|
|
253
|
+
if ((svc.desiredCount ?? 0) <= 0 && (svc.runningCount ?? 0) <= 0) continue;
|
|
254
|
+
for (const id of svc.networkConfiguration?.awsvpcConfiguration?.subnets || []) subnetIds.add(id);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (subnetIds.size > 0) {
|
|
258
|
+
const subs = await ec2Client.send(new DescribeSubnetsCommand({ SubnetIds: [...subnetIds] }));
|
|
259
|
+
for (const sn of subs.Subnets || []) if (sn.VpcId) vpcIds.add(sn.VpcId);
|
|
260
|
+
}
|
|
261
|
+
} catch {
|
|
262
|
+
return { vpcIds, unknown: true };
|
|
263
|
+
}
|
|
264
|
+
return { vpcIds, unknown: false };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function discoverDeepVpcs({ ec2Client, ecsClient = null, cluster = null, projectName, resourceSuffix = '', isLambda = false }) {
|
|
234
268
|
const deletable = [];
|
|
235
269
|
const reportOnly = [];
|
|
270
|
+
// The stack's own default-workspace VPC is live by construction —
|
|
271
|
+
// asleep stacks run nothing, so task liveness alone would propose
|
|
272
|
+
// deleting the slept network. (Lambda trees create no VPCs, so the
|
|
273
|
+
// Name check is the whole liveness story there.)
|
|
274
|
+
const defaultVpcName = `${projectName}${resourceSuffix}-vpc`;
|
|
275
|
+
const live = isLambda
|
|
276
|
+
? { vpcIds: new Set(), unknown: false }
|
|
277
|
+
: await discoverLiveVpcIds({ ecsClient, cluster, ec2Client });
|
|
236
278
|
let nextToken;
|
|
237
279
|
do {
|
|
238
280
|
const resp = await ec2Client.send(new DescribeVpcsCommand({ NextToken: nextToken }));
|
|
239
281
|
for (const vpc of resp.Vpcs || []) {
|
|
240
282
|
const entry = { kind: 'vpc', id: vpc.VpcId };
|
|
241
|
-
if (hasExactProjectTag(vpc.Tags, projectName)) {
|
|
242
|
-
deletable.push(entry);
|
|
243
|
-
} else {
|
|
283
|
+
if (!hasExactProjectTag(vpc.Tags, projectName)) {
|
|
244
284
|
reportOnly.push({
|
|
245
285
|
...entry,
|
|
246
286
|
reason: Array.isArray(vpc.Tags) && vpc.Tags.length > 0 ? 'foreign-project' : 'unscoped',
|
|
247
287
|
});
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
const name = (vpc.Tags || []).find((tag) => tag?.Key === 'Name')?.Value;
|
|
291
|
+
if (name === defaultVpcName || live.vpcIds.has(vpc.VpcId)) {
|
|
292
|
+
reportOnly.push({ ...entry, reason: 'live-excluded' });
|
|
293
|
+
} else if (live.unknown) {
|
|
294
|
+
reportOnly.push({ ...entry, reason: 'liveness-unknown' });
|
|
295
|
+
} else {
|
|
296
|
+
deletable.push(entry);
|
|
248
297
|
}
|
|
249
298
|
}
|
|
250
299
|
nextToken = resp.NextToken;
|
|
251
300
|
} while (nextToken);
|
|
252
|
-
return { deletable, reportOnly };
|
|
301
|
+
return { deletable, reportOnly, unknown: live.unknown };
|
|
253
302
|
}
|
|
254
303
|
|
|
255
304
|
// Deep target discovery: secrets are report-only, never deletable —
|
|
@@ -348,12 +397,14 @@ export async function discoverOrphanedResources(ctx) {
|
|
|
348
397
|
export async function discoverDeepOrphans(ctx) {
|
|
349
398
|
const deletable = [];
|
|
350
399
|
const reportOnly = [];
|
|
400
|
+
let unknown = false;
|
|
351
401
|
for (const target of GC_TARGETS.filter((entry) => entry.scope === 'deep')) {
|
|
352
402
|
const found = await target.discover(ctx);
|
|
353
403
|
deletable.push(...(found.deletable || []));
|
|
354
404
|
reportOnly.push(...(found.reportOnly || []));
|
|
405
|
+
if (found.unknown === true) unknown = true;
|
|
355
406
|
}
|
|
356
|
-
return { deletable, reportOnly };
|
|
407
|
+
return { deletable, reportOnly, unknown };
|
|
357
408
|
}
|
|
358
409
|
|
|
359
410
|
export const ECR_BATCH_DELETE_LIMIT = 100;
|
|
@@ -441,7 +492,11 @@ function printDeepReport(deep, projectName) {
|
|
|
441
492
|
? 'owned — secrets are never auto-deleted'
|
|
442
493
|
: entry.reason === 'prefix-report-only'
|
|
443
494
|
? 'name-prefix match — review before acting'
|
|
444
|
-
:
|
|
495
|
+
: entry.reason === 'live-excluded'
|
|
496
|
+
? 'live — excluded'
|
|
497
|
+
: entry.reason === 'liveness-unknown'
|
|
498
|
+
? 'liveness unverifiable — review before acting'
|
|
499
|
+
: 'never deleted by gc';
|
|
445
500
|
console.log(` ${color.dim('-')} ${entry.kind}/${entry.id} ${color.dim(`(${why})`)}`);
|
|
446
501
|
}
|
|
447
502
|
console.log('');
|
|
@@ -536,16 +591,24 @@ async function runGcMain(input = {}) {
|
|
|
536
591
|
console.log(color.dim(`Total orphaned resources: ${discovered.totalCount}`));
|
|
537
592
|
|
|
538
593
|
// Deep scan (opt-in): report-only audit of tag-keyed orphans (VPCs,
|
|
539
|
-
// secrets, state bucket). Never prompts, never deletes —
|
|
540
|
-
//
|
|
541
|
-
//
|
|
542
|
-
// any future deletion acts on them.
|
|
594
|
+
// secrets, state bucket). Never prompts, never deletes — VPC
|
|
595
|
+
// candidates additionally pass ECS liveness plus the stack-VPC name
|
|
596
|
+
// check, so live networks land in report-only, never deletable.
|
|
543
597
|
if (deep) {
|
|
544
598
|
const ds = spinner();
|
|
545
599
|
ds.start('Deep scanning tag-keyed orphans...');
|
|
546
600
|
let deepResult;
|
|
547
601
|
try {
|
|
548
|
-
deepResult = await discoverDeepOrphans({
|
|
602
|
+
deepResult = await discoverDeepOrphans({
|
|
603
|
+
ec2Client,
|
|
604
|
+
secretsClient,
|
|
605
|
+
cwd,
|
|
606
|
+
projectName,
|
|
607
|
+
ecsClient,
|
|
608
|
+
cluster: resolveCluster(options, cwd),
|
|
609
|
+
resourceSuffix: readResourceSuffix(cwd),
|
|
610
|
+
isLambda: isComputeTarget(cwd, 'lambda'),
|
|
611
|
+
});
|
|
549
612
|
} catch (error) {
|
|
550
613
|
ds.stop(color.red('❌ Deep discovery failed.'));
|
|
551
614
|
await trackFailure('gc_run', { projectName, deep: true, error_message: error?.message });
|
|
@@ -557,10 +620,14 @@ async function runGcMain(input = {}) {
|
|
|
557
620
|
});
|
|
558
621
|
}
|
|
559
622
|
ds.stop('Deep discovery complete.');
|
|
623
|
+
if (deepResult.unknown === true) {
|
|
624
|
+
console.log(color.yellow('⚠ VPC liveness could not be verified — no VPCs will be proposed. Check credentials (ECS/EC2) and retry.'));
|
|
625
|
+
}
|
|
560
626
|
printDeepReport(deepResult, projectName);
|
|
561
627
|
const deepCounts = {
|
|
562
628
|
vpc_deletable: deepResult.deletable.filter((entry) => entry.kind === 'vpc').length,
|
|
563
629
|
vpc_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'vpc').length,
|
|
630
|
+
vpc_liveness_unknown: deepResult.unknown === true,
|
|
564
631
|
secret_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'secret').length,
|
|
565
632
|
state_bucket_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'state-bucket').length,
|
|
566
633
|
};
|
package/src/commands/init.js
CHANGED
|
@@ -41,11 +41,13 @@ import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-ru
|
|
|
41
41
|
import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust } from '../utils/resolvers.js';
|
|
42
42
|
import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
|
|
43
43
|
import { parseDomainTf } from '../utils/domains.js';
|
|
44
|
+
import { PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
|
|
44
45
|
|
|
45
46
|
// Greppable, invalid-as-real placeholder stamped into backend.tf and
|
|
46
47
|
// workflow role ARNs by `init --offline`. Uppercase by design: S3 rejects
|
|
47
|
-
// it, so an unreconciled tree fails loud at `terraform init`.
|
|
48
|
-
|
|
48
|
+
// it, so an unreconciled tree fails loud at `terraform init`. Single
|
|
49
|
+
// source lives in reconcile.js; this alias keeps the init-facing name.
|
|
50
|
+
export const OFFLINE_ACCOUNT_PLACEHOLDER = PLACEHOLDER_ACCOUNT_ID;
|
|
49
51
|
|
|
50
52
|
// Reconciliation checklist for offline scaffolds. console.log (not clack)
|
|
51
53
|
// so it lands in CI logs as well as terminals. Mirrors every call
|
package/src/core/parser.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { normalizeArgv } from '../utils/args.js';
|
|
2
2
|
|
|
3
|
+
// The only meaningful --no-telemetry spellings (bare, =true, =false —
|
|
4
|
+
// the getBoolFlag convention). Anything else (=garbage, or a flag-like
|
|
5
|
+
// *value* such as --cmd "--no-telemetry=x") is not a global: it flows
|
|
6
|
+
// through to per-command parsing, where the unknown-flag gate rejects
|
|
7
|
+
// it loudly instead of this layer silently eating a command value.
|
|
8
|
+
const GLOBAL_ONLY_FLAGS = new Set(['--no-telemetry', '--no-telemetry=true', '--no-telemetry=false']);
|
|
9
|
+
|
|
3
10
|
export function parseCliArgs(processArgs) {
|
|
4
11
|
const argv = normalizeArgv(processArgs);
|
|
5
12
|
// 1. Extract telemetry flag safely
|
|
6
|
-
const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' ||
|
|
13
|
+
const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' || arg === '--no-telemetry=true');
|
|
7
14
|
|
|
8
15
|
// 2. Filter out telemetry flag
|
|
9
|
-
const args = argv.filter(arg =>
|
|
16
|
+
const args = argv.filter(arg => !GLOBAL_ONLY_FLAGS.has(arg));
|
|
10
17
|
|
|
11
18
|
// 3. Flag readers. Every value flag supports both `--flag=value` and
|
|
12
19
|
// `--flag value` spellings; space-form values are recorded in
|
|
@@ -159,9 +166,9 @@ export function parseCliArgs(processArgs) {
|
|
|
159
166
|
// Args for per-command parsers: --no-telemetry is honored globally via
|
|
160
167
|
// DO_NOT_TRACK (see parseCliArgs), so it must not reach parseFlags —
|
|
161
168
|
// otherwise the unknown-flag gate would reject a documented global
|
|
162
|
-
// option on every command.
|
|
169
|
+
// option on every command. Only meaningful spellings are stripped; a
|
|
170
|
+
// flag-like value (e.g. --cmd "--no-telemetry=x") passes through to the
|
|
171
|
+
// command untouched.
|
|
163
172
|
export function stripGlobalOnlyFlags(processArgs) {
|
|
164
|
-
return normalizeArgv(processArgs).filter(
|
|
165
|
-
(arg) => arg !== '--no-telemetry' && !(typeof arg === 'string' && arg.startsWith('--no-telemetry='))
|
|
166
|
-
);
|
|
173
|
+
return normalizeArgv(processArgs).filter((arg) => !GLOBAL_ONLY_FLAGS.has(arg));
|
|
167
174
|
}
|
package/src/utils/aws.js
CHANGED
|
@@ -132,9 +132,10 @@ export async function provisionStateBucket(region, projectName) {
|
|
|
132
132
|
// 2. Format Bucket Name
|
|
133
133
|
const stateBucketName = formatStateBucketName(projectName, awsAccountId);
|
|
134
134
|
|
|
135
|
-
// 3. Create S3 Bucket & Enable Versioning
|
|
135
|
+
// 3. Create S3 Bucket & Enable Versioning (shared helper, so init,
|
|
136
|
+
// recovery, and apply reconcile create identical buckets).
|
|
136
137
|
const s3Client = new S3Client({ region });
|
|
137
|
-
await
|
|
138
|
+
await ensureStateBucketExists({ region, bucket: stateBucketName, s3Client });
|
|
138
139
|
|
|
139
140
|
return { awsAccountId, stateBucketName, s3Client };
|
|
140
141
|
}
|
|
@@ -142,14 +143,16 @@ export async function provisionStateBucket(region, projectName) {
|
|
|
142
143
|
// Creates (or re-creates) one explicitly named state bucket with the same
|
|
143
144
|
// tagging + versioning provisionStateBucket applies. Recovery reads the
|
|
144
145
|
// bucket from backend.tf and lands here instead of re-deriving the name,
|
|
145
|
-
// which would miss on suffixed trees.
|
|
146
|
-
|
|
146
|
+
// which would miss on suffixed trees. `created` reports whether this
|
|
147
|
+
// call made the bucket (vs finding it already owned) so callers can
|
|
148
|
+
// tell creation from adoption without an extra HeadBucket round trip.
|
|
149
|
+
export async function ensureStateBucketExists({ region, bucket, s3Client = null }) {
|
|
147
150
|
if (process.env.CI_MOCK_AWS === 'true') {
|
|
148
|
-
return { bucket, mocked: true };
|
|
151
|
+
return { bucket, mocked: true, created: false };
|
|
149
152
|
}
|
|
150
|
-
const
|
|
151
|
-
await createVersionedBucket(
|
|
152
|
-
return { bucket };
|
|
153
|
+
const client = s3Client ?? new S3Client({ region });
|
|
154
|
+
const { created } = await createVersionedBucket(client, bucket, region);
|
|
155
|
+
return { bucket, created };
|
|
153
156
|
}
|
|
154
157
|
|
|
155
158
|
async function createVersionedBucket(s3Client, bucket, region) {
|
|
@@ -158,26 +161,28 @@ async function createVersionedBucket(s3Client, bucket, region) {
|
|
|
158
161
|
Bucket: bucket,
|
|
159
162
|
CreateBucketConfiguration: region === 'us-east-1' ? undefined : { LocationConstraint: region }
|
|
160
163
|
}));
|
|
161
|
-
|
|
162
|
-
await s3Client.send(new PutBucketTaggingCommand({
|
|
163
|
-
Bucket: bucket,
|
|
164
|
-
Tagging: {
|
|
165
|
-
TagSet: [
|
|
166
|
-
{ Key: "ManagedBy", Value: "grada" }
|
|
167
|
-
]
|
|
168
|
-
}
|
|
169
|
-
}));
|
|
170
|
-
|
|
171
|
-
await s3Client.send(new PutBucketVersioningCommand({
|
|
172
|
-
Bucket: bucket,
|
|
173
|
-
VersioningConfiguration: { Status: 'Enabled' }
|
|
174
|
-
}));
|
|
175
164
|
} catch (error) {
|
|
176
165
|
// Ignore if the bucket already exists and is owned by the user
|
|
177
166
|
if (error.name !== 'BucketAlreadyOwnedByYou') {
|
|
178
167
|
throw error;
|
|
179
168
|
}
|
|
169
|
+
return { created: false };
|
|
180
170
|
}
|
|
171
|
+
|
|
172
|
+
await s3Client.send(new PutBucketTaggingCommand({
|
|
173
|
+
Bucket: bucket,
|
|
174
|
+
Tagging: {
|
|
175
|
+
TagSet: [
|
|
176
|
+
{ Key: "ManagedBy", Value: "grada" }
|
|
177
|
+
]
|
|
178
|
+
}
|
|
179
|
+
}));
|
|
180
|
+
|
|
181
|
+
await s3Client.send(new PutBucketVersioningCommand({
|
|
182
|
+
Bucket: bucket,
|
|
183
|
+
VersioningConfiguration: { Status: 'Enabled' }
|
|
184
|
+
}));
|
|
185
|
+
return { created: true };
|
|
181
186
|
}
|
|
182
187
|
|
|
183
188
|
export async function teardownStateBucket(region, bucketName, options = {}) {
|
package/src/utils/file-lock.js
CHANGED
|
@@ -127,25 +127,3 @@ export async function withProjectLock(cwd, fn, options = {}) {
|
|
|
127
127
|
releaseLock(lockDir);
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
-
|
|
131
|
-
// Synchronous single-attempt variant for sync-only call sites (domain
|
|
132
|
-
// provider injection). Never waits: takes over stale locks, otherwise
|
|
133
|
-
// throws FILE_LOCK_TIMEOUT immediately.
|
|
134
|
-
export function withProjectLockSync(cwd, fn, options = {}) {
|
|
135
|
-
const { scope = 'project', staleMs = DEFAULT_LOCK_STALE_MS } = options || {};
|
|
136
|
-
const lockDir = lockDirFor(cwd, scope);
|
|
137
|
-
fs.mkdirSync(path.dirname(lockDir), { recursive: true });
|
|
138
|
-
if (!tryAcquire(lockDir)) {
|
|
139
|
-
if (lockAgeMs(lockDir) > staleMs) {
|
|
140
|
-
releaseLock(lockDir);
|
|
141
|
-
if (!tryAcquire(lockDir)) throw timeoutError(scope, 0);
|
|
142
|
-
} else {
|
|
143
|
-
throw timeoutError(scope, 0);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
try {
|
|
147
|
-
return fn();
|
|
148
|
-
} finally {
|
|
149
|
-
releaseLock(lockDir);
|
|
150
|
-
}
|
|
151
|
-
}
|
package/src/utils/hcl.js
CHANGED
|
@@ -92,11 +92,14 @@ function escapeRegExp(raw) {
|
|
|
92
92
|
|
|
93
93
|
// Locates `resource "<type>" "<name>" { ... }`. Returns
|
|
94
94
|
// `{ headerIdx, openIdx, closeIdx }` or null when the resource or its
|
|
95
|
-
// braces cannot be found.
|
|
95
|
+
// braces cannot be found. The header anchors to a line start (resource
|
|
96
|
+
// blocks are top-level), so a `#` comment quoting the header never
|
|
97
|
+
// false-positives.
|
|
96
98
|
export function findResourceBlock(content, resourceType, resourceName) {
|
|
97
99
|
const text = String(content ?? '');
|
|
98
100
|
const pattern = new RegExp(
|
|
99
|
-
|
|
101
|
+
`^\\s*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
|
|
102
|
+
'm'
|
|
100
103
|
);
|
|
101
104
|
const match = pattern.exec(text);
|
|
102
105
|
if (!match) return null;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
// Token offline scaffolds (`init --offline`) leave where the AWS account
|
|
5
|
+
// ID belongs: the bucket name in terraform/backend.tf plus every
|
|
6
|
+
// role-to-assume ARN in .github/workflows/*.yml. Detection only —
|
|
7
|
+
// rewriting lives in apply's reconcile pre-step.
|
|
8
|
+
export const PLACEHOLDER_ACCOUNT_ID = 'YOUR_AWS_ACCOUNT_ID';
|
|
9
|
+
|
|
10
|
+
// Repo-relative paths still containing the placeholder (`[]` when the
|
|
11
|
+
// tree is reconciled). Missing files are skipped, never an error; the
|
|
12
|
+
// workflows directory is globbed (not filename-hardcoded) so future
|
|
13
|
+
// workflows are covered.
|
|
14
|
+
export function findUnreconciledFiles(targetDir) {
|
|
15
|
+
const found = [];
|
|
16
|
+
const check = (repoPath) => {
|
|
17
|
+
let content;
|
|
18
|
+
try {
|
|
19
|
+
content = fs.readFileSync(path.join(targetDir, repoPath), 'utf8');
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (content.includes(PLACEHOLDER_ACCOUNT_ID)) found.push(repoPath);
|
|
24
|
+
};
|
|
25
|
+
check(path.join('terraform', 'backend.tf'));
|
|
26
|
+
let entries = [];
|
|
27
|
+
try {
|
|
28
|
+
entries = fs.readdirSync(path.join(targetDir, '.github', 'workflows'));
|
|
29
|
+
} catch {
|
|
30
|
+
entries = [];
|
|
31
|
+
}
|
|
32
|
+
for (const entry of entries.filter((name) => /\.ya?ml$/.test(name)).sort()) {
|
|
33
|
+
check(path.join('.github', 'workflows', entry));
|
|
34
|
+
}
|
|
35
|
+
return found.sort();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isValidAccountId(value) {
|
|
39
|
+
return typeof value === 'string' && /^\d{12}$/.test(value);
|
|
40
|
+
}
|