@grada-run/grada 0.41.0 → 0.41.1
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/bin/cli.js +1 -0
- package/package.json +1 -1
- package/src/commands/add.js +1 -1
- package/src/commands/apply.js +94 -17
- package/src/commands/db/migrate.js +1 -1
- package/src/commands/exec.js +1 -1
- package/src/commands/gc.js +75 -35
- package/src/utils/args.js +17 -2
- package/src/utils/command.js +3 -1
- package/src/utils/hcl.js +1 -1
- package/src/utils/terraform-errors.js +2 -2
- package/src/utils/terraform-metadata.js +36 -0
- package/src/utils/terraform.js +22 -7
- package/templates/README-static.md +2 -5
- package/templates/README.md +2 -5
package/bin/cli.js
CHANGED
|
@@ -73,6 +73,7 @@ const HELP_TEXT = [
|
|
|
73
73
|
'Global options:',
|
|
74
74
|
' --version, -v Print the CLI version and exit',
|
|
75
75
|
' --no-telemetry Disable telemetry for this run only (persistent: grada telemetry off; every run: DO_NOT_TRACK=1)',
|
|
76
|
+
' --flag=value Use the = form when a flag value itself starts with a dash (e.g. --cmd=--dry-run)',
|
|
76
77
|
];
|
|
77
78
|
|
|
78
79
|
const rawArgs = process.argv.slice(2);
|
package/package.json
CHANGED
package/src/commands/add.js
CHANGED
|
@@ -77,7 +77,7 @@ export function parseAddArgs(argv = []) {
|
|
|
77
77
|
const args = normalizeArgv(argv);
|
|
78
78
|
if (args[0] === 'add') args.shift();
|
|
79
79
|
const { options: parsed, rest, unknown } = parseFlags(args, {
|
|
80
|
-
string: ['region', 'project-name', 'partition-key', 'model', 'domain', 'from-email', 'zone-id', 'schedule', { name: 'cmd', key: 'cronCommand' }, { name: 'cron-command', key: 'cronCommand' }, 'name', 'timezone'],
|
|
80
|
+
string: ['region', 'project-name', 'partition-key', 'model', 'domain', 'from-email', 'zone-id', 'schedule', { name: 'cmd', key: 'cronCommand', greedy: true }, { name: 'cron-command', key: 'cronCommand', greedy: true }, 'name', 'timezone'],
|
|
81
81
|
boolean: ['force', { name: 'headless', key: 'isHeadless' }],
|
|
82
82
|
bareBoolean: ['list-models', 'refresh'],
|
|
83
83
|
});
|
package/src/commands/apply.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from 'path';
|
|
2
2
|
import fs from 'fs';
|
|
3
|
-
import { intro, outro, spinner, log, cancel, confirm } from '@clack/prompts';
|
|
3
|
+
import { intro, outro, spinner, log, cancel, confirm, isCancel } from '@clack/prompts';
|
|
4
4
|
import color from 'picocolors';
|
|
5
5
|
import { renderDryRunPreview, parseTerraformConfig, buildCostTelemetryProps } from '../utils/visualizer.js';
|
|
6
6
|
import { detectFramework } from '../utils/detector.js';
|
|
@@ -11,13 +11,13 @@ 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, parseStateBucketBackend } from '../utils/terraform-metadata.js';
|
|
14
|
+
import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
|
|
15
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';
|
|
20
|
+
import { checkAwsCredentials, ensureStateBucketExists, isAuthError, printAwsAuthGuidance } from '../utils/aws.js';
|
|
21
21
|
import { findUnreconciledFiles, isValidAccountId, PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
|
|
22
22
|
import { runWake } from './wake.js';
|
|
23
23
|
|
|
@@ -58,6 +58,19 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
|
|
|
58
58
|
}),
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
|
+
// Ping first: the flag resolves the account, but reconciling and
|
|
62
|
+
// provisioning both need live credentials — fail guided with
|
|
63
|
+
// nothing written rather than stamping files and crashing.
|
|
64
|
+
try {
|
|
65
|
+
await checkAwsCredentials(resolveRegion(options, targetDir));
|
|
66
|
+
} catch {
|
|
67
|
+
return {
|
|
68
|
+
proceed: false,
|
|
69
|
+
result: await failCredentialsMissing(options, projectName, {
|
|
70
|
+
message: '\n✖ Could not verify AWS credentials: configure them first — apply cannot reconcile or provision without them.\n',
|
|
71
|
+
}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
61
74
|
accountId = flag;
|
|
62
75
|
source = 'flag';
|
|
63
76
|
} else {
|
|
@@ -65,16 +78,10 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
|
|
|
65
78
|
accountId = (await checkAwsCredentials(resolveRegion(options, targetDir))).accountId;
|
|
66
79
|
source = 'sts';
|
|
67
80
|
} catch {
|
|
68
|
-
printAwsAuthGuidance(options);
|
|
69
81
|
return {
|
|
70
82
|
proceed: false,
|
|
71
|
-
result: await
|
|
72
|
-
noExit: isProgrammaticCall(options),
|
|
83
|
+
result: await failCredentialsMissing(options, projectName, {
|
|
73
84
|
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
85
|
}),
|
|
79
86
|
};
|
|
80
87
|
}
|
|
@@ -107,10 +114,34 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
|
|
|
107
114
|
log.message(color.green(`Rewrote ${files.length} file(s).`));
|
|
108
115
|
const backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
|
|
109
116
|
const { bucket, region: backendRegion } = parseStateBucketBackend(backend);
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
117
|
+
let ensured;
|
|
118
|
+
try {
|
|
119
|
+
ensured = await ensureStateBucketExists({
|
|
120
|
+
region: backendRegion ?? resolveRegion(options, targetDir),
|
|
121
|
+
bucket,
|
|
122
|
+
});
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (isAuthError(error) || error?.name === 'CredentialsProviderError') {
|
|
125
|
+
return {
|
|
126
|
+
proceed: false,
|
|
127
|
+
result: await failCredentialsMissing(options, projectName, {
|
|
128
|
+
message: '\n✖ AWS credentials expired during reconciliation.\n',
|
|
129
|
+
hint: ' Placeholders are already rewritten; fix credentials and re-run apply to converge.\n',
|
|
130
|
+
}),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
proceed: false,
|
|
135
|
+
result: await failCommand({
|
|
136
|
+
noExit: isProgrammaticCall(options),
|
|
137
|
+
message: `\n✖ Could not ensure the state bucket "${bucket}": ${error?.message ?? error}.\n`,
|
|
138
|
+
event: 'infrastructure_applied',
|
|
139
|
+
telemetry: { projectName },
|
|
140
|
+
errorCode: 'RECONCILE_BUCKET_FAILED',
|
|
141
|
+
reason: 'reconcile-bucket-failed',
|
|
142
|
+
}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
114
145
|
trackEvent('apply_reconciled', {
|
|
115
146
|
projectName,
|
|
116
147
|
account_source: source,
|
|
@@ -126,6 +157,22 @@ function describeAccountIdShape(value) {
|
|
|
126
157
|
return `expected exactly 12 digits, got ${text.length}`;
|
|
127
158
|
}
|
|
128
159
|
|
|
160
|
+
// Shared credential-failure exit for every reconcile path: the recovery
|
|
161
|
+
// guidance plus a named code, so the shape can't drift between the
|
|
162
|
+
// resolution ping, the STS fallback, and the bucket ensure.
|
|
163
|
+
async function failCredentialsMissing(options, projectName, { message, hint = null }) {
|
|
164
|
+
printAwsAuthGuidance(options);
|
|
165
|
+
return failCommand({
|
|
166
|
+
noExit: isProgrammaticCall(options),
|
|
167
|
+
message,
|
|
168
|
+
...(hint === null ? {} : { hint }),
|
|
169
|
+
event: 'infrastructure_applied',
|
|
170
|
+
telemetry: { projectName },
|
|
171
|
+
errorCode: 'AWS_CREDENTIALS_MISSING',
|
|
172
|
+
reason: 'aws-credentials-missing',
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
129
176
|
// Unlock-and-retry flow for a stale Terraform state lock. Headless
|
|
130
177
|
// refuses unless `--force-unlock <id>` was passed; interactive asks once.
|
|
131
178
|
// Retries the apply exactly once, skipping the already-confirmed preview.
|
|
@@ -620,14 +667,44 @@ async function applyStackMain(input = {}) {
|
|
|
620
667
|
});
|
|
621
668
|
}
|
|
622
669
|
|
|
670
|
+
if (code === 'OIDC_PROVIDER_CONFLICT' && options._oidcAdopted !== true) {
|
|
671
|
+
// Adopt the shared provider instead of hand-editing: the
|
|
672
|
+
// GitHub provider URL is account-singleton, so the existing
|
|
673
|
+
// provider IS the match — flip the var and retry.
|
|
674
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
675
|
+
message: '\n✖ apply needs approval to adopt the existing GitHub OIDC provider.',
|
|
676
|
+
hint: ' Re-run with --auto-approve to adopt non-interactively.\n',
|
|
677
|
+
event: 'infrastructure_applied',
|
|
678
|
+
telemetry: { projectName: actualProjectName },
|
|
679
|
+
errorCode: 'OIDC_ADOPT_NON_INTERACTIVE',
|
|
680
|
+
});
|
|
681
|
+
if (refused) return refused;
|
|
682
|
+
let adopt = shouldAutoApprove(options);
|
|
683
|
+
if (!adopt) {
|
|
684
|
+
const confirmed = await confirm({
|
|
685
|
+
message: 'Adopt the existing GitHub OIDC provider (writes create_oidc_provider = false) and retry?',
|
|
686
|
+
initialValue: true,
|
|
687
|
+
});
|
|
688
|
+
adopt = !isCancel(confirmed) && confirmed === true;
|
|
689
|
+
}
|
|
690
|
+
if (adopt) {
|
|
691
|
+
upsertAutoTfvar(tfDir, 'create_oidc_provider', false);
|
|
692
|
+
trackEvent('oidc_provider_adopted', { projectName: actualProjectName });
|
|
693
|
+
log.message(color.cyan('Adopted the existing OIDC provider — retrying apply...'));
|
|
694
|
+
return applyStack({ ...options, _skipPreview: true, _oidcAdopted: true });
|
|
695
|
+
}
|
|
696
|
+
// Declined: fall through to the manual guidance below.
|
|
697
|
+
}
|
|
698
|
+
|
|
623
699
|
if (code === 'OIDC_PROVIDER_CONFLICT') {
|
|
700
|
+
// The override lives in grada.auto.tfvars (machine-owned,
|
|
701
|
+
// survives regeneration) — never in the oidc.tf default.
|
|
624
702
|
log.error(color.red('GitHub OIDC Provider Conflict Detected'));
|
|
625
703
|
log.message('AWS only allows one GitHub Actions provider per account, and you already have one configured.');
|
|
626
704
|
log.message('');
|
|
627
705
|
log.message(`${color.bold('How to fix this:')}`);
|
|
628
|
-
log.message(`1.
|
|
629
|
-
log.message(`2.
|
|
630
|
-
log.message(`3. Run ${color.cyan('npx grada-run apply')} again.`);
|
|
706
|
+
log.message(`1. Adopt the shared provider: ${color.cyan(`echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`)}`);
|
|
707
|
+
log.message(`2. Run ${color.cyan('npx grada-run apply')} again.`);
|
|
631
708
|
} else if (code === 'BACKEND_RECONFIGURE_REQUIRED' || code === 'CLOUDFRONT_IN_PROGRESS' || code === 'DELETION_PROTECTION_ACTIVE') {
|
|
632
709
|
// Named but flow-neutral: runbook guidance with a coded
|
|
633
710
|
// failure. (RECREATE_COLLISION has its dedicated branch
|
|
@@ -60,7 +60,7 @@ export function parseDbMigrateArgs(argv = []) {
|
|
|
60
60
|
if (args[0] === 'migrate') args.shift();
|
|
61
61
|
const { options, rest, unknown } = parseFlags(args, {
|
|
62
62
|
string: [
|
|
63
|
-
{ name: 'cmd', key: 'cmd' },
|
|
63
|
+
{ name: 'cmd', key: 'cmd', greedy: true },
|
|
64
64
|
{ name: 'task-def', key: 'taskDef' },
|
|
65
65
|
{ name: 'timeout', key: 'timeout' },
|
|
66
66
|
{ name: 'project-name', key: 'projectName' },
|
package/src/commands/exec.js
CHANGED
|
@@ -35,7 +35,7 @@ export function parseExecArgs(argv = []) {
|
|
|
35
35
|
const args = normalizeArgv(argv);
|
|
36
36
|
if (args[0] === 'exec') args.shift();
|
|
37
37
|
const { options, rest, unknown } = parseFlags(args, {
|
|
38
|
-
string: ['cluster', 'service', 'container', 'command', 'region'],
|
|
38
|
+
string: ['cluster', 'service', 'container', { name: 'command', greedy: true }, 'region'],
|
|
39
39
|
boolean: ['headless'],
|
|
40
40
|
});
|
|
41
41
|
const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
|
package/src/commands/gc.js
CHANGED
|
@@ -3,14 +3,14 @@ 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, DescribeServicesCommand } from '@aws-sdk/client-ecs';
|
|
6
|
+
import { ECSClient, ListClustersCommand, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
|
|
7
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';
|
|
11
11
|
import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
12
12
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
13
|
-
import { resolveRegion, resolveProjectName,
|
|
13
|
+
import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
|
|
14
14
|
import { resolveClient } from '../utils/aws.js';
|
|
15
15
|
import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
|
|
16
16
|
import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
|
|
@@ -138,15 +138,51 @@ function defaultListLambdaFunctionNames({ region, spawnSyncImpl } = {}) {
|
|
|
138
138
|
// trees, Lambda functions for serverless ones. Never throws — any scan
|
|
139
139
|
// failure resolves to `unknown` so discovery fails closed instead of
|
|
140
140
|
// proposing live-preview groups.
|
|
141
|
+
// One enumeration feeding every ECS liveness consumer: each workspace
|
|
142
|
+
// provisions its own `<app>-cluster`, so liveness must scan the
|
|
143
|
+
// default cluster AND every preview cluster — never just one.
|
|
144
|
+
// Returns service ARNs per project cluster; any client error resolves
|
|
145
|
+
// `unknown` (fail closed) instead of a partial set.
|
|
146
|
+
export async function listProjectClusterServices({ ecsClient = null, projectName, resourceSuffix = '' } = {}) {
|
|
147
|
+
const byCluster = new Map();
|
|
148
|
+
try {
|
|
149
|
+
if (!ecsClient) return { byCluster, unknown: false };
|
|
150
|
+
const clusterPattern = new RegExp(`^${escapeRegExp(projectName)}(-pr-\\d+)?${escapeRegExp(resourceSuffix)}-cluster$`);
|
|
151
|
+
let nextToken;
|
|
152
|
+
const clusters = [];
|
|
153
|
+
do {
|
|
154
|
+
const resp = await ecsClient.send(new ListClustersCommand({ nextToken, maxResults: 100 }));
|
|
155
|
+
for (const arn of resp.clusterArns || []) {
|
|
156
|
+
const name = String(arn).split('/').pop();
|
|
157
|
+
if (clusterPattern.test(name)) clusters.push(name);
|
|
158
|
+
}
|
|
159
|
+
nextToken = resp.nextToken;
|
|
160
|
+
} while (nextToken);
|
|
161
|
+
for (const cluster of clusters) {
|
|
162
|
+
let svcToken;
|
|
163
|
+
const arns = [];
|
|
164
|
+
do {
|
|
165
|
+
const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken: svcToken, maxResults: 100 }));
|
|
166
|
+
arns.push(...(resp.serviceArns || []));
|
|
167
|
+
svcToken = resp.nextToken;
|
|
168
|
+
} while (svcToken);
|
|
169
|
+
byCluster.set(cluster, arns);
|
|
170
|
+
}
|
|
171
|
+
} catch {
|
|
172
|
+
return { byCluster, unknown: true };
|
|
173
|
+
}
|
|
174
|
+
return { byCluster, unknown: false };
|
|
175
|
+
}
|
|
176
|
+
|
|
141
177
|
export async function discoverLivePreviewLogGroups({
|
|
142
178
|
ecsClient = null,
|
|
143
|
-
cluster = null,
|
|
144
179
|
projectName,
|
|
145
180
|
resourceSuffix = '',
|
|
146
181
|
isLambda = false,
|
|
147
182
|
listFunctionsImpl = defaultListLambdaFunctionNames,
|
|
148
183
|
spawnSyncImpl = null,
|
|
149
184
|
region = null,
|
|
185
|
+
clusterServices = null,
|
|
150
186
|
} = {}) {
|
|
151
187
|
const live = new Set();
|
|
152
188
|
try {
|
|
@@ -158,17 +194,15 @@ export async function discoverLivePreviewLogGroups({
|
|
|
158
194
|
if (typeof name === 'string' && fnPattern.test(name)) live.add(`/aws/lambda/${name}`);
|
|
159
195
|
}
|
|
160
196
|
} else {
|
|
161
|
-
|
|
197
|
+
const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
|
|
198
|
+
if (enumeration.unknown) return { groups: live, unknown: true };
|
|
162
199
|
const servicePattern = new RegExp(`^${base}-service$`);
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 }));
|
|
166
|
-
for (const arn of resp.serviceArns || []) {
|
|
200
|
+
for (const arns of enumeration.byCluster.values()) {
|
|
201
|
+
for (const arn of arns || []) {
|
|
167
202
|
const name = String(arn).split('/').pop();
|
|
168
203
|
if (servicePattern.test(name)) live.add(`/ecs/${name.slice(0, -'-service'.length)}`);
|
|
169
204
|
}
|
|
170
|
-
|
|
171
|
-
} while (nextToken);
|
|
205
|
+
}
|
|
172
206
|
}
|
|
173
207
|
} catch {
|
|
174
208
|
return { groups: live, unknown: true };
|
|
@@ -227,31 +261,31 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
|
|
|
227
261
|
}
|
|
228
262
|
|
|
229
263
|
// Deep target discovery: VPCs partitioned by the STRICT deletion
|
|
230
|
-
// predicate — exact project tag only. Foreign and
|
|
231
|
-
// reportOnly, never in deletable, so prefix
|
|
232
|
-
// and legacy resources can never enter the
|
|
264
|
+
// predicate — exact project tag only, minus live networks. Foreign and
|
|
265
|
+
// untagged VPCs land in reportOnly, never in deletable, so prefix
|
|
266
|
+
// lookalikes (`myapp-evil`) and legacy resources can never enter the
|
|
267
|
+
// deletion set.
|
|
233
268
|
// Live VPC ids behind running (or desired) ECS services: services →
|
|
234
|
-
// awsvpc subnets → VPCs
|
|
235
|
-
//
|
|
236
|
-
|
|
269
|
+
// awsvpc subnets → VPCs, across every project cluster (each preview
|
|
270
|
+
// workspace runs its own cluster in its own VPC). Fail-closed like the
|
|
271
|
+
// preview-log-group liveness: any client error resolves `unknown`
|
|
272
|
+
// instead of guessing.
|
|
273
|
+
export async function discoverLiveVpcIds({ ecsClient = null, ec2Client = null, projectName, resourceSuffix = '', clusterServices = null } = {}) {
|
|
237
274
|
const vpcIds = new Set();
|
|
238
275
|
try {
|
|
239
|
-
if (!ecsClient || !
|
|
240
|
-
|
|
241
|
-
|
|
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);
|
|
276
|
+
if (!ecsClient || !ec2Client) return { vpcIds, unknown: false };
|
|
277
|
+
const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
|
|
278
|
+
if (enumeration.unknown) return { vpcIds, unknown: true };
|
|
247
279
|
const subnetIds = new Set();
|
|
248
|
-
for (const
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
280
|
+
for (const [cluster, arns] of enumeration.byCluster.entries()) {
|
|
281
|
+
for (const batch of chunkArray(arns, 10)) {
|
|
282
|
+
const desc = await ecsClient.send(new DescribeServicesCommand({ cluster, services: batch }));
|
|
283
|
+
for (const svc of desc.services || []) {
|
|
284
|
+
// Desired counts: a crash-looping preview runs nothing
|
|
285
|
+
// yet is unambiguously live.
|
|
286
|
+
if ((svc.desiredCount ?? 0) <= 0 && (svc.runningCount ?? 0) <= 0) continue;
|
|
287
|
+
for (const id of svc.networkConfiguration?.awsvpcConfiguration?.subnets || []) subnetIds.add(id);
|
|
288
|
+
}
|
|
255
289
|
}
|
|
256
290
|
}
|
|
257
291
|
if (subnetIds.size > 0) {
|
|
@@ -264,7 +298,7 @@ export async function discoverLiveVpcIds({ ecsClient = null, cluster = null, ec2
|
|
|
264
298
|
return { vpcIds, unknown: false };
|
|
265
299
|
}
|
|
266
300
|
|
|
267
|
-
async function discoverDeepVpcs({ ec2Client, ecsClient = null,
|
|
301
|
+
async function discoverDeepVpcs({ ec2Client, ecsClient = null, projectName, resourceSuffix = '', isLambda = false, clusterServices = null }) {
|
|
268
302
|
const deletable = [];
|
|
269
303
|
const reportOnly = [];
|
|
270
304
|
// The stack's own default-workspace VPC is live by construction —
|
|
@@ -274,7 +308,7 @@ async function discoverDeepVpcs({ ec2Client, ecsClient = null, cluster = null, p
|
|
|
274
308
|
const defaultVpcName = `${projectName}${resourceSuffix}-vpc`;
|
|
275
309
|
const live = isLambda
|
|
276
310
|
? { vpcIds: new Set(), unknown: false }
|
|
277
|
-
: await discoverLiveVpcIds({ ecsClient,
|
|
311
|
+
: await discoverLiveVpcIds({ ecsClient, ec2Client, projectName, resourceSuffix, clusterServices });
|
|
278
312
|
let nextToken;
|
|
279
313
|
do {
|
|
280
314
|
const resp = await ec2Client.send(new DescribeVpcsCommand({ NextToken: nextToken }));
|
|
@@ -542,17 +576,23 @@ async function runGcMain(input = {}) {
|
|
|
542
576
|
|
|
543
577
|
let discovered;
|
|
544
578
|
let previewLivenessUnknown = false;
|
|
579
|
+
let previewClusterServices = null;
|
|
545
580
|
try {
|
|
546
581
|
const isLambda = isComputeTarget(cwd, 'lambda');
|
|
547
582
|
const suffix = readResourceSuffix(cwd);
|
|
583
|
+
// One cluster-service enumeration shared by the log-group and
|
|
584
|
+
// (deep) VPC liveness consumers — fetched once, not per scan.
|
|
585
|
+
previewClusterServices = isLambda
|
|
586
|
+
? null
|
|
587
|
+
: await listProjectClusterServices({ ecsClient, projectName, resourceSuffix: suffix });
|
|
548
588
|
const liveness = await discoverLivePreviewLogGroups({
|
|
549
589
|
ecsClient,
|
|
550
|
-
cluster: resolveCluster(options, cwd),
|
|
551
590
|
projectName,
|
|
552
591
|
resourceSuffix: suffix,
|
|
553
592
|
isLambda,
|
|
554
593
|
spawnSyncImpl: options.spawnSyncImpl,
|
|
555
594
|
region,
|
|
595
|
+
clusterServices: previewClusterServices,
|
|
556
596
|
});
|
|
557
597
|
previewLivenessUnknown = liveness.unknown;
|
|
558
598
|
discovered = await discoverOrphanedResources({
|
|
@@ -605,9 +645,9 @@ async function runGcMain(input = {}) {
|
|
|
605
645
|
cwd,
|
|
606
646
|
projectName,
|
|
607
647
|
ecsClient,
|
|
608
|
-
cluster: resolveCluster(options, cwd),
|
|
609
648
|
resourceSuffix: readResourceSuffix(cwd),
|
|
610
649
|
isLambda: isComputeTarget(cwd, 'lambda'),
|
|
650
|
+
clusterServices: previewClusterServices,
|
|
611
651
|
});
|
|
612
652
|
} catch (error) {
|
|
613
653
|
ds.stop(color.red('❌ Deep discovery failed.'));
|
package/src/utils/args.js
CHANGED
|
@@ -19,6 +19,19 @@ function normalizeEntries(entries) {
|
|
|
19
19
|
return map;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
// String entries marked `{ name, greedy: true }` consume the next token
|
|
23
|
+
// even when it starts with `--`: flags taking arbitrary shell text
|
|
24
|
+
// (`--cmd`, `--command`) must accept values like `--dry-run`.
|
|
25
|
+
function greedyEntries(entries) {
|
|
26
|
+
const set = new Set();
|
|
27
|
+
for (const entry of entries || []) {
|
|
28
|
+
if (entry && typeof entry === 'object' && typeof entry.name === 'string' && entry.greedy === true) {
|
|
29
|
+
set.add(entry.name);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return set;
|
|
33
|
+
}
|
|
34
|
+
|
|
22
35
|
// Guards module entry points against non-object options (direct programmatic
|
|
23
36
|
// misuse or automated fuzzing): anything that is not an object behaves like
|
|
24
37
|
// `{}`, so callers always reach structured validation instead of TypeErrors.
|
|
@@ -43,7 +56,8 @@ export function normalizeArgv(argv) {
|
|
|
43
56
|
// the bare long flag).
|
|
44
57
|
//
|
|
45
58
|
// Space-form values never consume a `--like` token (a following flag stays
|
|
46
|
-
// a flag)
|
|
59
|
+
// a flag) — except `greedy` string entries, which take arbitrary shell
|
|
60
|
+
// text. Unknown `--flags` are collected in `unknown` (never silently
|
|
47
61
|
// dropped) so commands can reject them loud; everything else is returned
|
|
48
62
|
// in `rest` so each command can apply its own positional rules.
|
|
49
63
|
export function parseFlags(args, { string = [], number = [], boolean = [], bareBoolean = [], alias = {} } = {}) {
|
|
@@ -51,6 +65,7 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
|
|
|
51
65
|
const rest = [];
|
|
52
66
|
const unknown = [];
|
|
53
67
|
const strings = normalizeEntries(string);
|
|
68
|
+
const greedyStrings = greedyEntries(string);
|
|
54
69
|
const numbers = normalizeEntries(number);
|
|
55
70
|
const booleans = normalizeEntries(boolean);
|
|
56
71
|
const bares = normalizeEntries(bareBoolean);
|
|
@@ -73,7 +88,7 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
|
|
|
73
88
|
const value = eq === -1 ? undefined : arg.slice(eq + 1);
|
|
74
89
|
if (strings.has(name)) {
|
|
75
90
|
if (value !== undefined) options[strings.get(name)] = value;
|
|
76
|
-
else if (i + 1 < list.length && !String(list[i + 1]).startsWith('--')) options[strings.get(name)] = list[++i];
|
|
91
|
+
else if (i + 1 < list.length && (greedyStrings.has(name) || !String(list[i + 1]).startsWith('--'))) options[strings.get(name)] = list[++i];
|
|
77
92
|
continue;
|
|
78
93
|
}
|
|
79
94
|
if (numbers.has(name)) {
|
package/src/utils/command.js
CHANGED
|
@@ -63,7 +63,9 @@ export async function refuseUnknownFlags(options = {}, spec = {}) {
|
|
|
63
63
|
return failCommand({
|
|
64
64
|
noExit: isProgrammaticCall(opts),
|
|
65
65
|
message: `\n✖ Unknown flag "${unknown[0]}" for ${command}.\n`,
|
|
66
|
-
hint:
|
|
66
|
+
hint: unknown[0] === '--'
|
|
67
|
+
? ' Bare "--" end-of-flags is not supported; use --flag=value when the value itself starts with a dash.\n'
|
|
68
|
+
: ' Check the spelling or run "grada --help" for usage.\n',
|
|
67
69
|
event,
|
|
68
70
|
telemetry,
|
|
69
71
|
errorCode: 'UNKNOWN_FLAG',
|
package/src/utils/hcl.js
CHANGED
|
@@ -98,7 +98,7 @@ function escapeRegExp(raw) {
|
|
|
98
98
|
export function findResourceBlock(content, resourceType, resourceName) {
|
|
99
99
|
const text = String(content ?? '');
|
|
100
100
|
const pattern = new RegExp(
|
|
101
|
-
|
|
101
|
+
`^[ \t]*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
|
|
102
102
|
'm'
|
|
103
103
|
);
|
|
104
104
|
const match = pattern.exec(text);
|
|
@@ -99,8 +99,8 @@ const RUNBOOKS = {
|
|
|
99
99
|
},
|
|
100
100
|
OIDC_PROVIDER_CONFLICT: {
|
|
101
101
|
message: 'GitHub OIDC provider already exists in this account.',
|
|
102
|
-
headless: '
|
|
103
|
-
interactive: '
|
|
102
|
+
headless: 'Re-run with --auto-approve to adopt it, or set create_oidc_provider = false in terraform/grada.auto.tfvars.',
|
|
103
|
+
interactive: 'Adopt it when prompted, or set create_oidc_provider = false in terraform/grada.auto.tfvars.',
|
|
104
104
|
},
|
|
105
105
|
CLOUDFRONT_IN_PROGRESS: {
|
|
106
106
|
message: 'CloudFront is still converging a previous change.',
|
|
@@ -133,6 +133,42 @@ export function parseStateBucketBackend(content) {
|
|
|
133
133
|
};
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
+
// Machine-owned variable overrides live in terraform/grada.auto.tfvars
|
|
137
|
+
// (auto-loaded by Terraform, gitignored, never regenerated) — never in
|
|
138
|
+
// generated .tf defaults, which regeneration would wipe.
|
|
139
|
+
export const GRADA_AUTO_TFVARS_FILENAME = 'grada.auto.tfvars';
|
|
140
|
+
|
|
141
|
+
// Idempotently sets one `key = value` override in grada.auto.tfvars,
|
|
142
|
+
// creating the file with a managed header when absent. Values are
|
|
143
|
+
// booleans only (the file holds machine flags, not secrets). Returns
|
|
144
|
+
// `{ path, created, changed }`.
|
|
145
|
+
export function upsertAutoTfvar(tfDir, key, value) {
|
|
146
|
+
if (typeof value !== 'boolean') throw new Error(`upsertAutoTfvar only supports booleans (got ${typeof value} for ${key})`);
|
|
147
|
+
if (!/^\w+$/.test(key)) throw new Error(`upsertAutoTfvar rejects non-identifier keys (got ${JSON.stringify(key)})`);
|
|
148
|
+
const filePath = path.join(tfDir, GRADA_AUTO_TFVARS_FILENAME);
|
|
149
|
+
let content = '';
|
|
150
|
+
try {
|
|
151
|
+
content = fs.readFileSync(filePath, 'utf8');
|
|
152
|
+
} catch {
|
|
153
|
+
content = '';
|
|
154
|
+
}
|
|
155
|
+
const created = content === '';
|
|
156
|
+
const line = `${key} = ${value ? 'true' : 'false'}`;
|
|
157
|
+
const pattern = new RegExp(`^${key}\\s*=.*$`, 'm');
|
|
158
|
+
let changed;
|
|
159
|
+
if (pattern.test(content)) {
|
|
160
|
+
const next = content.replace(pattern, line);
|
|
161
|
+
changed = next !== content;
|
|
162
|
+
content = next;
|
|
163
|
+
} else {
|
|
164
|
+
const header = '# Managed by grada: machine-written variable overrides. Safe to delete an entry to restore its default.\n';
|
|
165
|
+
content = `${created ? header : content.replace(/\n*$/, '\n')}${line}\n`;
|
|
166
|
+
changed = true;
|
|
167
|
+
}
|
|
168
|
+
atomicWriteFileSync(filePath, content);
|
|
169
|
+
return { path: filePath, created, changed };
|
|
170
|
+
}
|
|
171
|
+
|
|
136
172
|
// Central managed-tree gate: mutating commands refuse on ejected trees
|
|
137
173
|
// unless --force (headless fails, interactive confirms once);
|
|
138
174
|
// read-only callers pass `mode: 'warn'` to warn and proceed. Returns
|
package/src/utils/terraform.js
CHANGED
|
@@ -53,10 +53,6 @@ export function isInterruptedMarker(marker) {
|
|
|
53
53
|
// output would otherwise replace them.
|
|
54
54
|
const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)/;
|
|
55
55
|
|
|
56
|
-
function notify(spin, text) {
|
|
57
|
-
if (spin && typeof spin.message === 'function') spin.message(text);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
56
|
// Runs a terraform command while piping the latest stdout line into a
|
|
61
57
|
// @clack spinner. Resolves on exit 0; rejects with a structured error
|
|
62
58
|
// (`{ code, stderr, lockId? }` classified via terraform-errors.js)
|
|
@@ -68,8 +64,27 @@ function notify(spin, text) {
|
|
|
68
64
|
// last-run marker records running/completed/failed/interrupted for the
|
|
69
65
|
// next command to report. `onStdoutLine` observes raw lines (used by
|
|
70
66
|
// getTerraformOutputs); listeners and timers are always released.
|
|
67
|
+
//
|
|
68
|
+
// Progress display: a live terminal rewrites one spinner line, but the
|
|
69
|
+
// spinner re-renders every ~80ms — wherever cursor movement isn't
|
|
70
|
+
// honored (piped output, log viewers) each tick becomes a line and
|
|
71
|
+
// quiet stretches repeat the same message dozens of times. Non-TTY
|
|
72
|
+
// runs therefore get deduped plain lines instead, and the caller's
|
|
73
|
+
// spinner is cleared so its tick doesn't spam behind them (the
|
|
74
|
+
// caller's later stop then becomes a silent no-op). `isTTY` overrides
|
|
75
|
+
// the terminal sniff for tests.
|
|
71
76
|
export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}) {
|
|
72
|
-
const { markerDir = null, timeoutMs = 0, onStdoutLine = null } = options || {};
|
|
77
|
+
const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY } = options || {};
|
|
78
|
+
const wantsProgress = spin && typeof spin.message === 'function';
|
|
79
|
+
const live = isTTY === true && wantsProgress;
|
|
80
|
+
let lastEmitted;
|
|
81
|
+
const emit = (text) => {
|
|
82
|
+
if (lastEmitted === text) return;
|
|
83
|
+
lastEmitted = text;
|
|
84
|
+
if (live) spin.message(text);
|
|
85
|
+
else if (wantsProgress) console.log(text);
|
|
86
|
+
};
|
|
87
|
+
if (wantsProgress && !live && typeof spin.clear === 'function') spin.clear();
|
|
73
88
|
return new Promise((resolve, reject) => {
|
|
74
89
|
const child = spawn('terraform', args, { cwd });
|
|
75
90
|
let errorOutput = '';
|
|
@@ -191,13 +206,13 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
|
|
|
191
206
|
for (const line of lines) {
|
|
192
207
|
const trimmed = line.trim();
|
|
193
208
|
if (SUMMARY_LINE_RE.test(trimmed)) {
|
|
194
|
-
|
|
209
|
+
emit(`${loadingPrefix} - ${color.dim(trimmed)}`);
|
|
195
210
|
}
|
|
196
211
|
}
|
|
197
212
|
if (lines.length > 0) {
|
|
198
213
|
const latestLine = lines[lines.length - 1].trim();
|
|
199
214
|
const display = latestLine.length > 120 ? latestLine.substring(0, 117) + '...' : latestLine;
|
|
200
|
-
|
|
215
|
+
emit(`${loadingPrefix} - ${color.dim(display)}`);
|
|
201
216
|
}
|
|
202
217
|
});
|
|
203
218
|
|
|
@@ -41,12 +41,9 @@ Once live, manage the stack without opening the AWS console:
|
|
|
41
41
|
* `npx grada-run destroy --yes` — tear down the bucket and distribution
|
|
42
42
|
|
|
43
43
|
### ⚠️ Troubleshooting: OIDC Provider Already Exists
|
|
44
|
-
If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account).
|
|
44
|
+
If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). `npx grada-run apply` offers to adopt it (one confirm, zero hand-edits); to do it manually instead, add one line to `terraform/grada.auto.tfvars`:
|
|
45
45
|
```hcl
|
|
46
|
-
|
|
47
|
-
type = bool
|
|
48
|
-
default = false # <--- Change this from true to false
|
|
49
|
-
}
|
|
46
|
+
create_oidc_provider = false
|
|
50
47
|
```
|
|
51
48
|
Re-run `npx grada-run apply` to link directly to your existing provider.
|
|
52
49
|
|
package/templates/README.md
CHANGED
|
@@ -49,12 +49,9 @@ Once live, manage the stack without opening the AWS console:
|
|
|
49
49
|
* `npx grada-run add <capability>` — attach S3, DynamoDB, Valkey, SQS, or Bedrock later (`--list-models` shows available AI models)
|
|
50
50
|
|
|
51
51
|
### ⚠️ Troubleshooting: OIDC Provider Already Exists
|
|
52
|
-
If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account).
|
|
52
|
+
If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). `npx grada-run apply` offers to adopt it (one confirm, zero hand-edits); to do it manually instead, add one line to `terraform/grada.auto.tfvars`:
|
|
53
53
|
```hcl
|
|
54
|
-
|
|
55
|
-
type = bool
|
|
56
|
-
default = false # <--- Change this from true to false
|
|
57
|
-
}
|
|
54
|
+
create_oidc_provider = false
|
|
58
55
|
```
|
|
59
56
|
Re-run `npx grada-run apply` to link directly to your existing provider.
|
|
60
57
|
|