grada-run 0.45.0 → 0.47.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/README.md +4 -2
- package/bin/cli.js +4 -0
- package/package.json +1 -1
- package/src/commands/db/enable-vector.js +2 -3
- package/src/commands/db/migrate.js +35 -197
- package/src/commands/drift.js +8 -12
- package/src/commands/init.js +31 -0
- package/src/commands/run.js +232 -0
- package/src/core/parser.js +1 -0
- package/src/utils/backup.js +3 -3
- package/src/utils/ci-workflows.js +38 -0
- package/src/utils/ecs-runner.js +233 -1
- package/templates/github/plan.yml +153 -0
package/README.md
CHANGED
|
@@ -102,6 +102,7 @@ The interactive wizard will analyze your codebase, detect your framework, estima
|
|
|
102
102
|
| [`status`](./apps/docs/src/content/docs/cli/status.md) | Health dashboard with live Golden Signals, auto-`diagnose` on degradation, `--json` for scripts, and `--watch` for live repaint. |
|
|
103
103
|
| [`rollback`](./apps/docs/src/content/docs/cli/rollback.md) | Returns the live service to a previous task revision, with live progress (ECS only). |
|
|
104
104
|
| [`exec`](./apps/docs/src/content/docs/cli/exec.md) | Opens a shell in a running container via Session Manager (ECS only). |
|
|
105
|
+
| [`run`](./apps/docs/src/content/docs/cli/run.md) | Runs a one-off command in a fresh, disposable container inside the VPC — backfills, seeders, admin scripts — with live logs (ECS only). |
|
|
105
106
|
| [`db connect`](./apps/docs/src/content/docs/cli/db.md) | Opens a `localhost` tunnel to your private database (PostgreSQL, MySQL, or Aurora). |
|
|
106
107
|
| [`db migrate`](./apps/docs/src/content/docs/cli/db.md) | Runs migrations inside the VPC (auto-detected) or installs the CI pre-deploy gate. |
|
|
107
108
|
| [`db enable-vector`](./apps/docs/src/content/docs/cli/db.md) | Enables `pgvector` for AI embeddings with a one-off VPC task. |
|
|
@@ -115,7 +116,7 @@ The interactive wizard will analyze your codebase, detect your framework, estima
|
|
|
115
116
|
| [`domain`](./apps/docs/src/content/docs/cli/domain.md) | Attaches a custom domain with automated ACM TLS (Route 53 or external DNS). |
|
|
116
117
|
| [`destroy`](./apps/docs/src/content/docs/cli/destroy.md) | Tears down AWS resources to stop billing (state bucket optionally retained). |
|
|
117
118
|
| [`eject`](./apps/docs/src/content/docs/cli/eject.md) | Strips `grada` metadata, leaving pure Terraform and Actions files. |
|
|
118
|
-
| [`--headless`](./apps/docs/src/content/docs/guides/headless.md) | Fully programmatic runs for CI/CD (`--target`, `--with`, `--db-engine`, `--setup-ci-migrate`, `--setup-ci-drift`, `--offline`). |
|
|
119
|
+
| [`--headless`](./apps/docs/src/content/docs/guides/headless.md) | Fully programmatic runs for CI/CD (`--target`, `--with`, `--db-engine`, `--setup-ci-migrate`, `--setup-ci-drift`, `--setup-ci-plan`, `--offline`). |
|
|
119
120
|
| [`sync-ai`](./apps/docs/src/content/docs/cli/sync-ai.md) | Generates IDE assistant rules for your stack (Cursor, Copilot, Windsurf, Claude). |
|
|
120
121
|
| [`mcp`](./apps/docs/src/content/docs/cli/mcp.md) | Serves the MCP server for AI agents (STDIO/HTTP) or installs editor config (`--install`). |
|
|
121
122
|
|
|
@@ -133,7 +134,8 @@ your-project/
|
|
|
133
134
|
├── .github/
|
|
134
135
|
│ └── workflows/
|
|
135
136
|
│ ├── deploy.yml # Keyless OIDC CI/CD deployment pipeline
|
|
136
|
-
│
|
|
137
|
+
│ ├── drift.yml # Scheduled IaC drift detection (opt-in via `--setup-ci-drift` or `drift --setup`)
|
|
138
|
+
│ └── plan.yml # Terraform plan comments on PRs (via `--setup-ci-plan`, on by default interactively)
|
|
137
139
|
└── terraform/
|
|
138
140
|
├── main.tf # ECR repository + compute (ECS Cluster/Fargate Task, Lambda + API Gateway with `--target lambda`, or S3 + CloudFront with `--target static`)
|
|
139
141
|
├── network.tf # VPC, Public Subnets, ALB, and Security Groups
|
package/bin/cli.js
CHANGED
|
@@ -12,6 +12,7 @@ import { syncAi } from '../src/commands/sync-ai.js';
|
|
|
12
12
|
import { runLogs, parseLogsArgs } from '../src/commands/logs.js';
|
|
13
13
|
import { runStatus, parseStatusArgs } from '../src/commands/status.js';
|
|
14
14
|
import { runExec, parseExecArgs } from '../src/commands/exec.js';
|
|
15
|
+
import { runRun, parseRunArgs } from '../src/commands/run.js';
|
|
15
16
|
import { runDb } from '../src/commands/db.js';
|
|
16
17
|
import { runRollback, parseRollbackArgs } from '../src/commands/rollback.js';
|
|
17
18
|
import { runGc, parseGcArgs } from '../src/commands/gc.js';
|
|
@@ -42,6 +43,7 @@ const HELP_TEXT = [
|
|
|
42
43
|
' status Service health dashboard (--region, --json, --watch, --workspace)',
|
|
43
44
|
' rollback [rev] Roll back ECS service to a previous task revision (ECS only — Lambda uses image tags)',
|
|
44
45
|
' exec Open an interactive shell in a running container (--cluster, --service, --container, --command, --region, --workspace)',
|
|
46
|
+
' run Run a one-off command in an ephemeral ECS task (--cmd, --task-def, --timeout, --workspace)',
|
|
45
47
|
' db connect Open a secure local tunnel to your database (--port, --show-credentials, --workspace, --region)',
|
|
46
48
|
' db enable-vector Enable the pgvector extension via a one-off ECS task (--task-def, --timeout)',
|
|
47
49
|
' db import Import a SQL dump into your database (--file, --from, --yes)',
|
|
@@ -172,6 +174,8 @@ if (wantsVersion) {
|
|
|
172
174
|
runCommand(runRollback({ ...parseRollbackArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
|
|
173
175
|
} else if (positionalArgs[0] === 'exec') {
|
|
174
176
|
runCommand(runExec({ ...parseExecArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
|
|
177
|
+
} else if (positionalArgs[0] === 'run') {
|
|
178
|
+
runCommand(runRun({ ...parseRunArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
|
|
175
179
|
} else if (positionalArgs[0] === 'db') {
|
|
176
180
|
runCommand(runDb(commandArgs, { ...(isHeadless ? { isHeadless: true } : {}) }));
|
|
177
181
|
} else if (positionalArgs[0] === 'gc') {
|
package/package.json
CHANGED
|
@@ -16,9 +16,8 @@ import {
|
|
|
16
16
|
resolveCwd,
|
|
17
17
|
} from '../../utils/resolvers.js';
|
|
18
18
|
import { resolveContainer } from '../../utils/ecs.js';
|
|
19
|
-
import { runEphemeralEcsTask } from '../../utils/ecs-runner.js';
|
|
19
|
+
import { runEphemeralEcsTask, buildRunnerCommand } from '../../utils/ecs-runner.js';
|
|
20
20
|
import { parseTimeoutSeconds } from '../../utils/system.js';
|
|
21
|
-
import { buildMigrationCommand } from './migrate.js';
|
|
22
21
|
import fsSync from 'fs';
|
|
23
22
|
import path from 'path';
|
|
24
23
|
|
|
@@ -235,7 +234,7 @@ async function runDbEnableVectorMain(input = {}) {
|
|
|
235
234
|
service,
|
|
236
235
|
containerName,
|
|
237
236
|
taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
|
|
238
|
-
command: (containerDef) =>
|
|
237
|
+
command: (containerDef) => buildRunnerCommand(vectorScript, containerDef),
|
|
239
238
|
startedBy: 'grada-db-enable-vector',
|
|
240
239
|
logGroupName,
|
|
241
240
|
timeoutMs,
|
|
@@ -2,8 +2,8 @@ import { ECSClient } from '@aws-sdk/client-ecs';
|
|
|
2
2
|
import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
|
|
3
3
|
import color from 'picocolors';
|
|
4
4
|
import { intro, outro, spinner, text, isCancel } from '@clack/prompts';
|
|
5
|
-
import {
|
|
6
|
-
import { failCommand, failAwsError,
|
|
5
|
+
import { trackSuccess, setActiveCommandName, resetActiveCommandName, getCliVersion } from '../../core/telemetry.js';
|
|
6
|
+
import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
|
|
7
7
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../../utils/args.js';
|
|
8
8
|
import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/aws.js';
|
|
9
9
|
import {
|
|
@@ -15,13 +15,11 @@ import {
|
|
|
15
15
|
resolveAppName,
|
|
16
16
|
resolveHeadless,
|
|
17
17
|
resolveCwd,
|
|
18
|
-
readFileSafe,
|
|
19
18
|
readTerraformComputeTarget,
|
|
20
19
|
} from '../../utils/resolvers.js';
|
|
21
|
-
import { detectMigrationCommand
|
|
20
|
+
import { detectMigrationCommand } from '../../utils/detector.js';
|
|
22
21
|
import { resolveContainer } from '../../utils/ecs.js';
|
|
23
|
-
import { runEphemeralEcsTask } from '../../utils/ecs-runner.js';
|
|
24
|
-
import { parseTimeoutSeconds } from '../../utils/system.js';
|
|
22
|
+
import { runEphemeralEcsTask, buildRunnerCommand, parseRunnerTimeout, guardNpmStrippedRunner, reportRunnerOutcome } from '../../utils/ecs-runner.js';
|
|
25
23
|
import { atomicWriteFile } from '../../utils/atomic-write.js';
|
|
26
24
|
import { pinnedActionUse } from '../../data/action-pins.js';
|
|
27
25
|
import fsSync from 'fs';
|
|
@@ -181,69 +179,9 @@ export function injectPreviewMigrationGate(workflowContent, { cmd, cliVersion }
|
|
|
181
179
|
});
|
|
182
180
|
}
|
|
183
181
|
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
|
|
187
|
-
// instead (BUG-171). Indeterminate stays postgresql (back-compat).
|
|
188
|
-
function sniffMigrationScheme(entries, values) {
|
|
189
|
-
const engine = values.get('DB_ENGINE');
|
|
190
|
-
if (typeof engine === 'string' && engine !== '') {
|
|
191
|
-
return /mysql|maria/i.test(engine) ? 'mysql' : 'postgresql';
|
|
192
|
-
}
|
|
193
|
-
const port = values.get('DB_PORT');
|
|
194
|
-
if (typeof port === 'string' && port !== '') {
|
|
195
|
-
return port === '3306' ? 'mysql' : 'postgresql';
|
|
196
|
-
}
|
|
197
|
-
const refs = entries.map((entry) => entry?.valueFrom).filter((ref) => typeof ref === 'string').join('\n');
|
|
198
|
-
if (/mysql|maria|3306/i.test(refs)) return 'mysql';
|
|
199
|
-
return 'postgresql';
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Runtime userinfo encoder for the synthesized URL (BUG-139): node sees
|
|
203
|
-
// only shell references, never the values, so the encoding ladder ships
|
|
204
|
-
// inside the script — node (encodeURIComponent) → sed (the URL-breaking
|
|
205
|
-
// subset: %, ?, #, @, :, /) → warned raw. Quoting alone cannot save a
|
|
206
|
-
// `?` or `#` in the password: the URL parser (not the shell) is what
|
|
207
|
-
// breaks, so the shell refs must be encoded, not quoted.
|
|
208
|
-
function buildEncodedUrlExport({ scheme, defaultPort, defaultName }) {
|
|
209
|
-
const nodeEncode = `node -e 'var s="${scheme}",a=process.argv.slice(1);console.log(s+"://"+encodeURIComponent(a[0])+":"+encodeURIComponent(a[1])+"@"+a[2]+":"+a[3]+"/"+a[4])' "$_u" "$_p" "$_h" "$_o" "$_n"`;
|
|
210
|
-
const sedEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$(_grada_enc "$_u")" "$(_grada_enc "$_p")" "$_h" "$_o" "$_n"`;
|
|
211
|
-
const rawEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$_u" "$_p" "$_h" "$_o" "$_n"`;
|
|
212
|
-
return `_grada_db_url() { _u="\${DB_USER}"; _p="\${DB_PASSWORD}"; _h="\${DB_HOST}"; _o="\${DB_PORT:-${defaultPort}}"; _n="\${DB_NAME:-${defaultName}}"; `
|
|
213
|
-
+ `if command -v node >/dev/null 2>&1; then ${nodeEncode}; `
|
|
214
|
-
+ `elif command -v sed >/dev/null 2>&1; then _grada_enc() { printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/?/%3F/g' -e 's/#/%23/g' -e 's/@/%40/g' -e 's/:/%3A/g' -e 's|/|%2F|g'; }; ${sedEncode}; `
|
|
215
|
-
+ `else echo "grada: warning: DATABASE_URL built without userinfo encoding (no node or sed in image)" >&2; ${rawEncode}; fi; }; `
|
|
216
|
-
+ `if [ -z "\${DATABASE_URL:-}" ]; then export DATABASE_URL="$(_grada_db_url)"; fi`;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// Builds the container override command for the migration task. When the
|
|
220
|
-
// task definition provides discrete `DB_*` credentials but no
|
|
221
|
-
// `DATABASE_URL`, the command exports a runtime-synthesized URL (from the
|
|
222
|
-
// container's own environment, so secrets never cross the RunTask API
|
|
223
|
-
// call) before running the user's migration command. Pure and unit-tested.
|
|
224
|
-
export function buildMigrationCommand(resolvedCmd, containerDef) {
|
|
225
|
-
const cmd = String(resolvedCmd ?? '');
|
|
226
|
-
const environment = Array.isArray(containerDef?.environment) ? containerDef.environment : [];
|
|
227
|
-
const secrets = Array.isArray(containerDef?.secrets) ? containerDef.secrets : [];
|
|
228
|
-
const entries = [...environment, ...secrets];
|
|
229
|
-
const names = new Set(entries.map((entry) => entry?.name));
|
|
230
|
-
if (names.has('DATABASE_URL')) return ['sh', '-c', cmd];
|
|
231
|
-
if (!names.has('DB_HOST') || !names.has('DB_USER') || !names.has('DB_PASSWORD')) {
|
|
232
|
-
return ['sh', '-c', cmd];
|
|
233
|
-
}
|
|
234
|
-
const values = new Map(entries.map((entry) => [entry?.name, entry?.value]));
|
|
235
|
-
const scheme = sniffMigrationScheme(entries, values);
|
|
236
|
-
// RDS/Aurora enforces `rds.force_ssl = 1` by default: require TLS for
|
|
237
|
-
// synthesized postgres URLs so libpq-based migrations never fail on a
|
|
238
|
-
// plaintext connection (MySQL clients ignore PGSSLMODE; leave them alone).
|
|
239
|
-
const tlsPrefix = scheme === 'postgresql' ? 'export PGSSLMODE="${PGSSLMODE:-require}"; ' : '';
|
|
240
|
-
const urlExport = buildEncodedUrlExport({
|
|
241
|
-
scheme,
|
|
242
|
-
defaultPort: scheme === 'mysql' ? '3306' : '5432',
|
|
243
|
-
defaultName: scheme === 'mysql' ? 'mysql' : 'postgres',
|
|
244
|
-
});
|
|
245
|
-
return ['sh', '-c', `${tlsPrefix}${urlExport}; ${cmd}`];
|
|
246
|
-
}
|
|
182
|
+
// Back-compat alias: the synthesis logic now lives in ecs-runner.js as
|
|
183
|
+
// buildRunnerCommand (shared by migrate, enable-vector, and run).
|
|
184
|
+
export { buildRunnerCommand as buildMigrationCommand };
|
|
247
185
|
|
|
248
186
|
// Programmatic entry wrapper: stamps cli_command for telemetry on every
|
|
249
187
|
// invocation path, including direct imports that bypass bin/cli.js and MCP.
|
|
@@ -297,17 +235,13 @@ async function runDbMigrateMain(input = {}) {
|
|
|
297
235
|
});
|
|
298
236
|
}
|
|
299
237
|
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
reason: 'invalid-timeout',
|
|
308
|
-
resultExtra: { cluster, service, region },
|
|
309
|
-
});
|
|
310
|
-
}
|
|
238
|
+
const parsedTimeout = await parseRunnerTimeout(options.timeout, DEFAULT_MIGRATE_TIMEOUT_SECONDS, {
|
|
239
|
+
event: 'db_migrate_run',
|
|
240
|
+
telemetry: { projectName },
|
|
241
|
+
resultExtra: { cluster, service, region },
|
|
242
|
+
});
|
|
243
|
+
if (typeof parsedTimeout !== 'number') return parsedTimeout;
|
|
244
|
+
const timeoutSeconds = parsedTimeout;
|
|
311
245
|
|
|
312
246
|
// 1. Resolve the migration command (shared by live runs and --setup-ci).
|
|
313
247
|
let resolvedCmd = null;
|
|
@@ -345,27 +279,14 @@ async function runDbMigrateMain(input = {}) {
|
|
|
345
279
|
}
|
|
346
280
|
}
|
|
347
281
|
|
|
348
|
-
// 1b. Stripped-runner guard
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
return failCommand({
|
|
357
|
-
message: `\n✖ Refusing to run "${resolvedCmd}": your Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" inside the task.\n`,
|
|
358
|
-
hint: ` Bundle a framework-compiled runner instead and re-run with an explicit node-based command, e.g. --cmd "node ./dist/migrate.cjs". Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
|
|
359
|
-
event: 'db_migrate_run',
|
|
360
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: setupCi, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
|
|
361
|
-
errorCode: 'NPM_CMD_STRIPPED_RUNNER',
|
|
362
|
-
reason: 'npm-cmd-stripped-runner',
|
|
363
|
-
resultExtra: { cluster, service, region },
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
console.log(color.yellow(`⚠️ "${resolvedCmd}" starts with npm/npx but your Dockerfile strips those binaries from the runner image — this will fail with "command not found" unless you switch to a node-based command (e.g. "node ./dist/migrate.cjs"). Ensure your Dockerfile builds the bundle and copies it into the runner image.${ormHint}`));
|
|
367
|
-
trackEvent('npm_cmd_stripped_runner', { projectName, cmd_source: cmdSource, ci_setup: setupCi });
|
|
368
|
-
}
|
|
282
|
+
// 1b. Stripped-runner guard (shared with `run`).
|
|
283
|
+
const strippedRefusal = await guardNpmStrippedRunner({
|
|
284
|
+
resolvedCmd, cwd, headless,
|
|
285
|
+
event: 'db_migrate_run',
|
|
286
|
+
telemetry: { projectName, cmd_source: cmdSource, ci_setup: setupCi },
|
|
287
|
+
resultExtra: { cluster, service, region },
|
|
288
|
+
});
|
|
289
|
+
if (strippedRefusal) return strippedRefusal;
|
|
369
290
|
|
|
370
291
|
// 2. --setup-ci: patch the workflow file, no AWS calls.
|
|
371
292
|
if (setupCi) {
|
|
@@ -456,7 +377,7 @@ async function runDbMigrateMain(input = {}) {
|
|
|
456
377
|
service,
|
|
457
378
|
containerName,
|
|
458
379
|
taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
|
|
459
|
-
command: (containerDef) =>
|
|
380
|
+
command: (containerDef) => buildRunnerCommand(resolvedCmd, containerDef),
|
|
460
381
|
startedBy: 'grada-db-migrate',
|
|
461
382
|
logGroupName,
|
|
462
383
|
timeoutMs,
|
|
@@ -468,103 +389,20 @@ async function runDbMigrateMain(input = {}) {
|
|
|
468
389
|
taskNoun: 'migration',
|
|
469
390
|
});
|
|
470
391
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
print: () => {
|
|
475
|
-
console.log(`\n The ECS service ${color.cyan(service)} does not exist or is inactive.`);
|
|
476
|
-
console.log(` Run ${color.green('npx grada-run apply')} to provision your infrastructure.\n`);
|
|
477
|
-
},
|
|
478
|
-
event: 'db_migrate_run',
|
|
479
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
480
|
-
errorCode: 'ECS_SERVICE_NOT_FOUND',
|
|
481
|
-
reason: 'ecs-service-not-found',
|
|
482
|
-
resultExtra: { cluster, service, region },
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
if (!outcome.ok && outcome.code === 'NO_VPC_CONFIG') {
|
|
487
|
-
s.stop(color.red('Service has no VPC configuration.'));
|
|
488
|
-
return failCommand({
|
|
489
|
-
message: `\n✖ The ECS service ${color.cyan(service)} has no VPC network configuration, so the migration task cannot be placed.\n`,
|
|
490
|
-
event: 'db_migrate_run',
|
|
491
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
492
|
-
errorCode: 'RUN_TASK_FAILED',
|
|
493
|
-
reason: 'run-task-failed',
|
|
494
|
-
resultExtra: { cluster, service, region },
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
if (!outcome.ok && outcome.code === 'CONTAINER_NOT_FOUND') {
|
|
499
|
-
s.stop(color.red('Container not found.'));
|
|
500
|
-
return failCommand({
|
|
501
|
-
message: `\n✖ Container "${containerName}" does not exist in task definition "${outcome.targetTaskDef}".\n`,
|
|
502
|
-
hint: `Override with --container <name>. Available: ${outcome.available.join(', ') || 'none'}\n`,
|
|
503
|
-
event: 'db_migrate_run',
|
|
504
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
505
|
-
errorCode: 'CONTAINER_NOT_FOUND',
|
|
506
|
-
reason: 'container-not-found',
|
|
507
|
-
resultExtra: { cluster, service, region },
|
|
508
|
-
});
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
if (!outcome.ok && outcome.code === 'RUN_TASK_FAILED') {
|
|
512
|
-
s.stop(color.red('Failed to start migration task.'));
|
|
513
|
-
return failCommand({
|
|
514
|
-
message: `\n✖ ECS could not start the migration task: ${outcome.reason}.\n`,
|
|
515
|
-
event: 'db_migrate_run',
|
|
516
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
517
|
-
errorCode: 'RUN_TASK_FAILED',
|
|
518
|
-
reason: 'run-task-failed',
|
|
519
|
-
resultExtra: { cluster, service, region },
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
|
|
523
|
-
return failNamedContainerMissing({
|
|
524
|
-
spinner: s, outcome, cluster, service, region,
|
|
525
|
-
event: 'db_migrate_run',
|
|
526
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
527
|
-
noun: 'Migration',
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
if (!outcome.ok && outcome.code === 'TIMEOUT') {
|
|
531
|
-
try { s.stop(color.yellow('Migration timed out.')); } catch { /* already stopped */ }
|
|
532
|
-
return failCommand({
|
|
533
|
-
message: `\n✖ Migration timed out after ${timeoutSeconds}s. The task was stopped (best-effort); increase --timeout and retry.\n`,
|
|
534
|
-
event: 'db_migrate_run',
|
|
535
|
-
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
536
|
-
errorCode: 'MIGRATION_TIMEOUT',
|
|
537
|
-
reason: 'migration-timeout',
|
|
538
|
-
resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
|
|
539
|
-
});
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
const exitCode = outcome.exitCode;
|
|
543
|
-
const stoppedReason = outcome.stoppedReason;
|
|
544
|
-
if (exitCode === 0) {
|
|
545
|
-
// Owner pairs its own start/stop: the runner usually stops
|
|
546
|
-
// first (idempotent no-op then), but success must never
|
|
547
|
-
// depend on a callee for the spinner lifecycle (BUG-202).
|
|
548
|
-
try { s.stop(color.green('Migration succeeded.')); } catch { /* already stopped */ }
|
|
549
|
-
console.log(color.green('\n✅ Migration succeeded.'));
|
|
550
|
-
await trackSuccess('db_migrate_run', { projectName, cmd_source: cmdSource, ci_setup: false });
|
|
551
|
-
outro(color.green('Done.'));
|
|
552
|
-
return { ok: true, success: true, exitCode: 0, taskArn: outcome.taskArn };
|
|
553
|
-
}
|
|
554
|
-
const propagated = (typeof exitCode === 'number' && exitCode > 0) ? exitCode : 1;
|
|
555
|
-
// The ECS stopped reason is the only diagnosis PostHog gets for a
|
|
556
|
-
// failed task (exit codes alone can't distinguish image-pull from
|
|
557
|
-
// command-not-found from migration errors) — stamp it.
|
|
558
|
-
const failureDetail = `Migration failed with exit code ${exitCode ?? 'unknown'}: ${stoppedReason}`;
|
|
559
|
-
return failCommand({
|
|
560
|
-
message: `\n✖ ${failureDetail}.\n`,
|
|
392
|
+
// Outcome mapping shared with `run` (labels parameterize the copy).
|
|
393
|
+
return reportRunnerOutcome({
|
|
394
|
+
outcome, spinner: s,
|
|
561
395
|
event: 'db_migrate_run',
|
|
562
396
|
telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
397
|
+
cluster, service, region,
|
|
398
|
+
containerName,
|
|
399
|
+
label: 'Migration',
|
|
400
|
+
taskPhrase: 'migration task',
|
|
401
|
+
timeoutSeconds,
|
|
402
|
+
timeoutCode: 'MIGRATION_TIMEOUT',
|
|
403
|
+
timeoutReason: 'migration-timeout',
|
|
404
|
+
taskFailedCode: 'MIGRATION_TASK_FAILED',
|
|
405
|
+
taskFailedReason: 'migration-task-failed',
|
|
568
406
|
});
|
|
569
407
|
} catch (error) {
|
|
570
408
|
if (isAuthError(error)) {
|
package/src/commands/drift.js
CHANGED
|
@@ -8,7 +8,7 @@ import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../c
|
|
|
8
8
|
import { failCommand, failAwsError, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
|
|
9
9
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
10
10
|
import { resolveRegion, resolveProjectName, resolveCwd, readFileSafe } from '../utils/resolvers.js';
|
|
11
|
-
import {
|
|
11
|
+
import { renderCiWorkflow } from '../utils/ci-workflows.js';
|
|
12
12
|
|
|
13
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
14
14
|
const __dirname = path.dirname(__filename);
|
|
@@ -44,17 +44,13 @@ export function extractRoleArn(deployYmlContent) {
|
|
|
44
44
|
// Renders `templates/github/drift.yml` into the project. Shared by
|
|
45
45
|
// `drift --setup` and `--setup-ci-drift`; never exits, never tracks.
|
|
46
46
|
export function scaffoldDriftWorkflow(cwd = process.cwd(), { region, roleArn, force = false } = {}) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
56
|
-
atomicWriteFileSync(targetPath, rendered, 'utf8');
|
|
57
|
-
return { ok: true, path: targetPath };
|
|
47
|
+
return renderCiWorkflow({
|
|
48
|
+
templatePath: DRIFT_TEMPLATE_PATH,
|
|
49
|
+
region,
|
|
50
|
+
roleArn,
|
|
51
|
+
targetPath: path.join(cwd, DRIFT_WORKFLOW_FILE),
|
|
52
|
+
force,
|
|
53
|
+
});
|
|
58
54
|
}
|
|
59
55
|
|
|
60
56
|
// Condenses `terraform plan` output to the resource-change lines plus the
|
package/src/commands/init.js
CHANGED
|
@@ -27,6 +27,7 @@ import { ADDON_REGISTRY, addonTargetDisposition, addonSupportedTargets } from '.
|
|
|
27
27
|
import { validateAddonFlags, resolveAddonOptions, scaffoldAddon, DEFAULT_BEDROCK_MODEL } from './add.js';
|
|
28
28
|
import { injectMigrationGate, injectPreviewMigrationGate } from './db/migrate.js';
|
|
29
29
|
import { scaffoldDriftWorkflow } from './drift.js';
|
|
30
|
+
import { scaffoldPlanWorkflow } from '../utils/ci-workflows.js';
|
|
30
31
|
import { trackEvent, flushTelemetry, getCliVersion, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
31
32
|
import { failCommand } from '../utils/command.js';
|
|
32
33
|
import { getFrameworkWarning } from '../utils/warnings.js';
|
|
@@ -609,6 +610,21 @@ async function mainStackMain(input = {}) {
|
|
|
609
610
|
driftEnabled = driftAnswer === true;
|
|
610
611
|
}
|
|
611
612
|
|
|
613
|
+
// Plan-on-PR: explicit flag wins, else offer. Defaults ON —
|
|
614
|
+
// reviewing infra changes before merge is the safe default.
|
|
615
|
+
const setupCiPlanFlag = initOptions.setupCiPlan === true;
|
|
616
|
+
let planEnabled = false;
|
|
617
|
+
if (setupCiPlanFlag) {
|
|
618
|
+
planEnabled = true;
|
|
619
|
+
} else if (isInteractive) {
|
|
620
|
+
const planAnswer = await confirm({
|
|
621
|
+
message: 'Post Terraform plans as PR comments (review infra changes before merge)?',
|
|
622
|
+
initialValue: true,
|
|
623
|
+
});
|
|
624
|
+
if (typeof planAnswer === 'symbol') process.exit(0);
|
|
625
|
+
planEnabled = planAnswer === true;
|
|
626
|
+
}
|
|
627
|
+
|
|
612
628
|
// Addon selection: interactive multiselect, or explicit --with.
|
|
613
629
|
let selectedAddons;
|
|
614
630
|
if (isInteractive && !isStaticSite) {
|
|
@@ -937,6 +953,20 @@ async function mainStackMain(input = {}) {
|
|
|
937
953
|
}
|
|
938
954
|
}
|
|
939
955
|
|
|
956
|
+
if (planEnabled) {
|
|
957
|
+
// plan.yml rides the manifest + backup like drift.yml (R1):
|
|
958
|
+
// re-init backs the old file up and regenerates fresh (current
|
|
959
|
+
// role ARN) instead of silently keeping a stale copy.
|
|
960
|
+
const planned = scaffoldPlanWorkflow(dirConfig.targetDir, {
|
|
961
|
+
region: config.region,
|
|
962
|
+
roleArn: `arn:aws:iam::${awsAccountId}:role/${dirConfig.actualProjectName}${resourceSuffix}-github-actions-role`,
|
|
963
|
+
force: initOptions.force,
|
|
964
|
+
});
|
|
965
|
+
if (planned.ok) {
|
|
966
|
+
console.log(color.green('✅ Scaffolded .github/workflows/plan.yml (Terraform plan on PR)'));
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
940
970
|
// 7b2. Restore preserved files over the fresh output, then record
|
|
941
971
|
// content hashes of everything generated above so a later re-run can
|
|
942
972
|
// distinguish pristine output from hand edits (F3), plus the intended
|
|
@@ -989,6 +1019,7 @@ async function mainStackMain(input = {}) {
|
|
|
989
1019
|
detected_addons: Object.keys(ADDON_REGISTRY).filter((cap) => capabilities.addons[cap]?.detected === true),
|
|
990
1020
|
migration_gate_enabled: migrationGateEnabled,
|
|
991
1021
|
drift_detection_enabled: driftEnabled,
|
|
1022
|
+
plan_on_pr_enabled: planEnabled,
|
|
992
1023
|
});
|
|
993
1024
|
|
|
994
1025
|
s.stop('Infrastructure provisioned successfully!');
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { ECSClient } from '@aws-sdk/client-ecs';
|
|
2
|
+
import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
|
|
3
|
+
import color from 'picocolors';
|
|
4
|
+
import { intro, outro, spinner, text, isCancel } from '@clack/prompts';
|
|
5
|
+
import { setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
6
|
+
import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../utils/command.js';
|
|
7
|
+
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
8
|
+
import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
|
|
9
|
+
import {
|
|
10
|
+
resolveRegion,
|
|
11
|
+
resolveProjectName,
|
|
12
|
+
resolveCluster,
|
|
13
|
+
resolveService,
|
|
14
|
+
resolveLogGroup,
|
|
15
|
+
resolveAppName,
|
|
16
|
+
resolveHeadless,
|
|
17
|
+
resolveCwd,
|
|
18
|
+
guardComputeTarget,
|
|
19
|
+
} from '../utils/resolvers.js';
|
|
20
|
+
import { resolveContainer } from '../utils/ecs.js';
|
|
21
|
+
import { runEphemeralEcsTask, buildRunnerCommand, parseRunnerTimeout, guardNpmStrippedRunner, reportRunnerOutcome } from '../utils/ecs-runner.js';
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_RUN_TIMEOUT_SECONDS = 600;
|
|
24
|
+
export const DEFAULT_POLL_INTERVAL_MS = 2000;
|
|
25
|
+
export const DEFAULT_FLUSH_MAX_POLLS = 6;
|
|
26
|
+
export const DEFAULT_FLUSH_INTERVAL_MS = 1000;
|
|
27
|
+
|
|
28
|
+
export const RUN_NODE_EXAMPLE = 'node ./dist/backfill.cjs';
|
|
29
|
+
|
|
30
|
+
const LAMBDA_TARGET_HINT = ' Ephemeral Fargate tasks need an ECS service — remote execution is not supported on Lambda targets yet.\n';
|
|
31
|
+
const STATIC_TARGET_HINT = ' Static sites provision no compute — there is no container to execute against.\n';
|
|
32
|
+
|
|
33
|
+
export function parseRunArgs(argv = []) {
|
|
34
|
+
const args = normalizeArgv(argv);
|
|
35
|
+
if (args[0] === 'run') args.shift();
|
|
36
|
+
const { options, rest, unknown } = parseFlags(args, {
|
|
37
|
+
string: [
|
|
38
|
+
{ name: 'cmd', key: 'cmd', greedy: true },
|
|
39
|
+
{ name: 'task-def', key: 'taskDef' },
|
|
40
|
+
{ name: 'timeout', key: 'timeout' },
|
|
41
|
+
{ name: 'project-name', key: 'projectName' },
|
|
42
|
+
{ name: 'region', key: 'region' },
|
|
43
|
+
{ name: 'workspace', key: 'workspace' },
|
|
44
|
+
{ name: 'cluster', key: 'cluster' },
|
|
45
|
+
{ name: 'service', key: 'service' },
|
|
46
|
+
{ name: 'container', key: 'container' },
|
|
47
|
+
],
|
|
48
|
+
boolean: ['headless'],
|
|
49
|
+
});
|
|
50
|
+
const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
|
|
51
|
+
if (positionals.length > 0) options.unexpectedPositionals = positionals;
|
|
52
|
+
if (unknown.length > 0) options.unknownFlags = unknown;
|
|
53
|
+
return options;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Programmatic entry wrapper: stamps cli_command for telemetry on every
|
|
57
|
+
// invocation path, including direct imports that bypass bin/cli.js and MCP.
|
|
58
|
+
export async function runRun(input = {}) {
|
|
59
|
+
setActiveCommandName('run');
|
|
60
|
+
try {
|
|
61
|
+
return await runRunMain(input);
|
|
62
|
+
} finally {
|
|
63
|
+
resetActiveCommandName();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function runRunMain(input = {}) {
|
|
68
|
+
const options = normalizeOptions(input);
|
|
69
|
+
const unknownRefusal = await refuseUnknownFlags(options, { command: 'run', event: 'run_run' });
|
|
70
|
+
if (unknownRefusal) return unknownRefusal;
|
|
71
|
+
let cwd;
|
|
72
|
+
let region;
|
|
73
|
+
let projectName;
|
|
74
|
+
let cluster;
|
|
75
|
+
let service;
|
|
76
|
+
let containerName;
|
|
77
|
+
let logGroupName;
|
|
78
|
+
try {
|
|
79
|
+
cwd = resolveCwd(options);
|
|
80
|
+
region = resolveRegion(options, cwd);
|
|
81
|
+
projectName = resolveProjectName(options, cwd);
|
|
82
|
+
const appName = resolveAppName(projectName, options.workspace, cwd);
|
|
83
|
+
const namespacedOptions = { ...options, projectName: appName };
|
|
84
|
+
cluster = resolveCluster(namespacedOptions, cwd);
|
|
85
|
+
service = resolveService(namespacedOptions, cwd);
|
|
86
|
+
containerName = resolveContainer(namespacedOptions, cwd);
|
|
87
|
+
logGroupName = resolveLogGroup(namespacedOptions, cwd);
|
|
88
|
+
} catch {
|
|
89
|
+
return failProjectNotInitialized({ event: 'run_run' });
|
|
90
|
+
}
|
|
91
|
+
const headless = resolveHeadless(options);
|
|
92
|
+
|
|
93
|
+
intro(color.bgCyan(color.black(' grada run 🏃 ')));
|
|
94
|
+
|
|
95
|
+
if (Array.isArray(options.unexpectedPositionals) && options.unexpectedPositionals.length > 0) {
|
|
96
|
+
return failCommand({
|
|
97
|
+
message: `\n✖ Unexpected argument "${options.unexpectedPositionals[0]}". Wrap multi-word --cmd values in quotes: --cmd "${options.unexpectedPositionals.join(' ')}".\n`,
|
|
98
|
+
event: 'run_run',
|
|
99
|
+
telemetry: { projectName },
|
|
100
|
+
errorCode: 'UNEXPECTED_POSITIONAL_ARGS',
|
|
101
|
+
reason: 'unexpected-positional-args',
|
|
102
|
+
resultExtra: { cluster, service, region },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// One-off tasks run on ECS Fargate — refuse other targets before
|
|
107
|
+
// prompting or constructing AWS clients.
|
|
108
|
+
const targetGuard = guardComputeTarget({ cwd, command: 'Remote command execution', supported: ['ecs'] });
|
|
109
|
+
if (targetGuard) {
|
|
110
|
+
return failCommand({
|
|
111
|
+
message: targetGuard.message,
|
|
112
|
+
hint: targetGuard.actual === 'lambda' ? LAMBDA_TARGET_HINT : STATIC_TARGET_HINT,
|
|
113
|
+
event: 'run_run',
|
|
114
|
+
telemetry: { projectName },
|
|
115
|
+
errorCode: targetGuard.errorCode,
|
|
116
|
+
reason: targetGuard.reason,
|
|
117
|
+
resultExtra: { cluster, service, region },
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const parsedTimeout = await parseRunnerTimeout(options.timeout, DEFAULT_RUN_TIMEOUT_SECONDS, {
|
|
122
|
+
event: 'run_run',
|
|
123
|
+
telemetry: { projectName },
|
|
124
|
+
resultExtra: { cluster, service, region },
|
|
125
|
+
});
|
|
126
|
+
if (typeof parsedTimeout !== 'number') return parsedTimeout;
|
|
127
|
+
const timeoutSeconds = parsedTimeout;
|
|
128
|
+
|
|
129
|
+
// Resolve the command: explicit --cmd, else an interactive prompt.
|
|
130
|
+
// Generic commands cannot be auto-detected like migrations, so
|
|
131
|
+
// headless runs without --cmd fail closed.
|
|
132
|
+
let resolvedCmd = null;
|
|
133
|
+
let cmdSource = null;
|
|
134
|
+
if (typeof options.cmd === 'string' && options.cmd.trim()) {
|
|
135
|
+
resolvedCmd = options.cmd.trim();
|
|
136
|
+
cmdSource = 'explicit';
|
|
137
|
+
} else if (!headless) {
|
|
138
|
+
const answer = await text({
|
|
139
|
+
message: 'Command to run inside the VPC:',
|
|
140
|
+
placeholder: 'e.g. node ./dist/backfill.cjs',
|
|
141
|
+
});
|
|
142
|
+
if (isCancel(answer) || typeof answer !== 'string' || !answer.trim()) {
|
|
143
|
+
outro(color.yellow('Run cancelled.'));
|
|
144
|
+
return { ok: false, reason: 'cancelled', cluster, service, region };
|
|
145
|
+
}
|
|
146
|
+
resolvedCmd = answer.trim();
|
|
147
|
+
cmdSource = 'prompted';
|
|
148
|
+
} else {
|
|
149
|
+
return failCommand({
|
|
150
|
+
message: '\n✖ No command to run. Pass --cmd "<command>" (e.g. --cmd "node ./dist/backfill.cjs").\n',
|
|
151
|
+
event: 'run_run',
|
|
152
|
+
telemetry: { projectName, cmd_source: 'none' },
|
|
153
|
+
errorCode: 'MISSING_RUN_CMD',
|
|
154
|
+
reason: 'missing-run-cmd',
|
|
155
|
+
resultExtra: { cluster, service, region },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Stripped-runner guard (shared with `db migrate`).
|
|
160
|
+
const strippedRefusal = await guardNpmStrippedRunner({
|
|
161
|
+
resolvedCmd, cwd, headless,
|
|
162
|
+
event: 'run_run',
|
|
163
|
+
telemetry: { projectName, cmd_source: cmdSource },
|
|
164
|
+
resultExtra: { cluster, service, region },
|
|
165
|
+
nodeExample: RUN_NODE_EXAMPLE,
|
|
166
|
+
});
|
|
167
|
+
if (strippedRefusal) return strippedRefusal;
|
|
168
|
+
|
|
169
|
+
// Live run: discover the service and launch a one-off task.
|
|
170
|
+
const ecsClient = resolveClient(options.ecsClient, ECSClient, { region });
|
|
171
|
+
const logsClient = resolveClient(options.logsClient ?? options.cloudwatchClient, CloudWatchLogsClient, { region });
|
|
172
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
173
|
+
const maxFlushPolls = options.maxFlushPolls ?? DEFAULT_FLUSH_MAX_POLLS;
|
|
174
|
+
const flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
|
|
175
|
+
const timeoutMs = options.timeoutMs ?? timeoutSeconds * 1000;
|
|
176
|
+
|
|
177
|
+
const s = spinner();
|
|
178
|
+
s.start('Starting one-off task...');
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
const outcome = await runEphemeralEcsTask({
|
|
182
|
+
ecsClient,
|
|
183
|
+
logsClient,
|
|
184
|
+
cluster,
|
|
185
|
+
service,
|
|
186
|
+
containerName,
|
|
187
|
+
taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
|
|
188
|
+
command: (containerDef) => buildRunnerCommand(resolvedCmd, containerDef),
|
|
189
|
+
startedBy: 'grada-run',
|
|
190
|
+
logGroupName,
|
|
191
|
+
timeoutMs,
|
|
192
|
+
timeoutSeconds,
|
|
193
|
+
pollIntervalMs,
|
|
194
|
+
maxFlushPolls,
|
|
195
|
+
flushIntervalMs,
|
|
196
|
+
spinner: s,
|
|
197
|
+
taskNoun: 'one-off',
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// Outcome mapping shared with `db migrate` (labels parameterize the copy).
|
|
201
|
+
return reportRunnerOutcome({
|
|
202
|
+
outcome, spinner: s,
|
|
203
|
+
event: 'run_run',
|
|
204
|
+
telemetry: { projectName, cmd_source: cmdSource },
|
|
205
|
+
cluster, service, region,
|
|
206
|
+
containerName,
|
|
207
|
+
label: 'Task',
|
|
208
|
+
taskPhrase: 'one-off task',
|
|
209
|
+
timeoutSeconds,
|
|
210
|
+
timeoutCode: 'RUN_TIMEOUT',
|
|
211
|
+
timeoutReason: 'run-timeout',
|
|
212
|
+
taskFailedCode: 'RUN_COMMAND_FAILED',
|
|
213
|
+
taskFailedReason: 'run-command-failed',
|
|
214
|
+
});
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (isAuthError(error)) {
|
|
217
|
+
await trackAwsFailure('run_run', error, { projectName, cmd_source: cmdSource });
|
|
218
|
+
handleAuthErrorBranch(error, s, options);
|
|
219
|
+
return { ok: false, reason: 'error', cluster, service, region };
|
|
220
|
+
}
|
|
221
|
+
try { s.stop(color.red('❌ Run failed.')); } catch { /* spinner already stopped */ }
|
|
222
|
+
return failAwsError({
|
|
223
|
+
event: 'run_run',
|
|
224
|
+
error,
|
|
225
|
+
telemetry: { projectName, cmd_source: cmdSource },
|
|
226
|
+
reason: 'error',
|
|
227
|
+
resultExtra: { cluster, service, region },
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export default runRun;
|
package/src/core/parser.js
CHANGED
|
@@ -141,6 +141,7 @@ export function parseCliArgs(processArgs) {
|
|
|
141
141
|
githubRepo: getValueFlag('github-repo'),
|
|
142
142
|
setupCiMigrate: getBoolOrValueFlag('setup-ci-migrate'),
|
|
143
143
|
setupCiDrift: getBoolFlag('setup-ci-drift') === true,
|
|
144
|
+
setupCiPlan: getBoolFlag('setup-ci-plan') === true,
|
|
144
145
|
};
|
|
145
146
|
|
|
146
147
|
// 5. Isolate positional commands (non-string elements are positionals;
|
package/src/utils/backup.js
CHANGED
|
@@ -33,7 +33,7 @@ function collectManifestFiles(targetDir) {
|
|
|
33
33
|
// hand edits like deploy.yml — manifest them so re-init refuses
|
|
34
34
|
// dirty trees and backs them up instead of silently overwriting or
|
|
35
35
|
// leaving them stale (BUG-158).
|
|
36
|
-
for (const rel of ['Dockerfile', 'preview.yml', 'teardown.yml', 'drift.yml'].map((name) => (
|
|
36
|
+
for (const rel of ['Dockerfile', 'preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml'].map((name) => (
|
|
37
37
|
name === 'Dockerfile' ? name : path.join('.github', 'workflows', name)
|
|
38
38
|
))) {
|
|
39
39
|
if (fs.existsSync(path.join(targetDir, rel))) relPaths.push(rel);
|
|
@@ -226,7 +226,7 @@ export async function planExistingFiles(targetDir, { isHeadless = false, force =
|
|
|
226
226
|
const tfPath = path.join(targetDir, 'terraform');
|
|
227
227
|
const dockerfilePath = path.join(targetDir, 'Dockerfile');
|
|
228
228
|
const wfPath = path.join(targetDir, '.github', 'workflows', 'deploy.yml');
|
|
229
|
-
const extraWorkflows = ['preview.yml', 'teardown.yml', 'drift.yml']
|
|
229
|
+
const extraWorkflows = ['preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml']
|
|
230
230
|
.map((workflow) => path.join('.github', 'workflows', workflow))
|
|
231
231
|
.filter((rel) => fs.existsSync(path.join(targetDir, rel)));
|
|
232
232
|
|
|
@@ -303,7 +303,7 @@ export async function executeBackup(targetDir, plan = {}) {
|
|
|
303
303
|
['terraform/', path.join(targetDir, 'terraform')],
|
|
304
304
|
['Dockerfile', path.join(targetDir, 'Dockerfile')],
|
|
305
305
|
['.github/workflows/deploy.yml', path.join(targetDir, '.github', 'workflows', 'deploy.yml')],
|
|
306
|
-
...['preview.yml', 'teardown.yml', 'drift.yml'].map((workflow) => {
|
|
306
|
+
...['preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml'].map((workflow) => {
|
|
307
307
|
const rel = path.join('.github', 'workflows', workflow);
|
|
308
308
|
return [rel, path.join(targetDir, rel)];
|
|
309
309
|
}),
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import fsSync from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import { atomicWriteFileSync } from './atomic-write.js';
|
|
5
|
+
|
|
6
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = path.dirname(__filename);
|
|
8
|
+
|
|
9
|
+
export const PLAN_TEMPLATE_PATH = path.join(__dirname, '../../templates/github/plan.yml');
|
|
10
|
+
export const PLAN_WORKFLOW_FILE = path.join('.github', 'workflows', 'plan.yml');
|
|
11
|
+
|
|
12
|
+
// Shared render-and-write core for generated CI workflows: substitutes
|
|
13
|
+
// the region + role ARN placeholders, refuses to overwrite without
|
|
14
|
+
// force, and writes atomically. Never exits, never tracks.
|
|
15
|
+
export function renderCiWorkflow({ templatePath, region, roleArn, targetPath, force = false } = {}) {
|
|
16
|
+
const template = fsSync.readFileSync(templatePath, 'utf8');
|
|
17
|
+
const rendered = template
|
|
18
|
+
.replaceAll('{{REGION}}', region)
|
|
19
|
+
.replaceAll('{{ROLE_ARN}}', roleArn);
|
|
20
|
+
if (fsSync.existsSync(targetPath) && force !== true && force !== 'true') {
|
|
21
|
+
return { ok: false, reason: 'exists', path: targetPath };
|
|
22
|
+
}
|
|
23
|
+
fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
24
|
+
atomicWriteFileSync(targetPath, rendered, 'utf8');
|
|
25
|
+
return { ok: true, path: targetPath };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Renders `templates/github/plan.yml` into the project. Used by init's
|
|
29
|
+
// `--setup-ci-plan`; never exits, never tracks.
|
|
30
|
+
export function scaffoldPlanWorkflow(cwd = process.cwd(), { region, roleArn, force = false } = {}) {
|
|
31
|
+
return renderCiWorkflow({
|
|
32
|
+
templatePath: PLAN_TEMPLATE_PATH,
|
|
33
|
+
region,
|
|
34
|
+
roleArn,
|
|
35
|
+
targetPath: path.join(cwd, PLAN_WORKFLOW_FILE),
|
|
36
|
+
force,
|
|
37
|
+
});
|
|
38
|
+
}
|
package/src/utils/ecs-runner.js
CHANGED
|
@@ -6,10 +6,16 @@ import {
|
|
|
6
6
|
} from '@aws-sdk/client-ecs';
|
|
7
7
|
import { FilterLogEventsCommand, GetLogEventsCommand } from '@aws-sdk/client-cloudwatch-logs';
|
|
8
8
|
import color from 'picocolors';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { outro } from '@clack/prompts';
|
|
9
11
|
import { fetchActiveService, pickRuntimeContainer } from './ecs.js';
|
|
10
|
-
import { sleep, pollUntil } from './system.js';
|
|
12
|
+
import { sleep, pollUntil, parseTimeoutSeconds } from './system.js';
|
|
11
13
|
import { truncateSpinnerText } from './spinner-text.js';
|
|
12
14
|
import { isNotFoundError, buildLogStreamName } from '../commands/logs.js';
|
|
15
|
+
import { failCommand, failNamedContainerMissing } from './command.js';
|
|
16
|
+
import { trackEvent, trackSuccess } from '../core/telemetry.js';
|
|
17
|
+
import { readFileSafe } from './resolvers.js';
|
|
18
|
+
import { isNpmShimCommand, dockerfileStripsNpmShims, ormMappedHintSegment } from './detector.js';
|
|
13
19
|
|
|
14
20
|
export const DEFAULT_RUNNER_POLL_INTERVAL_MS = 2000;
|
|
15
21
|
export const DEFAULT_RUNNER_FLUSH_MAX_POLLS = 6;
|
|
@@ -301,3 +307,229 @@ export async function runEphemeralEcsTask({
|
|
|
301
307
|
const stoppedReason = match.reason || finalTask?.stoppedReason || 'unknown';
|
|
302
308
|
return { ok: true, taskArn, exitCode, stoppedReason };
|
|
303
309
|
}
|
|
310
|
+
|
|
311
|
+
// Sniffs the URL scheme from discrete credentials. Explicit values win;
|
|
312
|
+
// when DB_ENGINE/DB_PORT are secrets-sourced (valueFrom, values unknown
|
|
313
|
+
// to the CLI) the reference text is sniffed for engine/port hints
|
|
314
|
+
// instead (BUG-171). Indeterminate stays postgresql (back-compat).
|
|
315
|
+
function sniffRunnerScheme(entries, values) {
|
|
316
|
+
const engine = values.get('DB_ENGINE');
|
|
317
|
+
if (typeof engine === 'string' && engine !== '') {
|
|
318
|
+
return /mysql|maria/i.test(engine) ? 'mysql' : 'postgresql';
|
|
319
|
+
}
|
|
320
|
+
const port = values.get('DB_PORT');
|
|
321
|
+
if (typeof port === 'string' && port !== '') {
|
|
322
|
+
return port === '3306' ? 'mysql' : 'postgresql';
|
|
323
|
+
}
|
|
324
|
+
const refs = entries.map((entry) => entry?.valueFrom).filter((ref) => typeof ref === 'string').join('\n');
|
|
325
|
+
if (/mysql|maria|3306/i.test(refs)) return 'mysql';
|
|
326
|
+
return 'postgresql';
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Runtime userinfo encoder for the synthesized URL (BUG-139): node sees
|
|
330
|
+
// only shell references, never the values, so the encoding ladder ships
|
|
331
|
+
// inside the script — node (encodeURIComponent) → sed (the URL-breaking
|
|
332
|
+
// subset: %, ?, #, @, :, /) → warned raw. Quoting alone cannot save a
|
|
333
|
+
// `?` or `#` in the password: the URL parser (not the shell) is what
|
|
334
|
+
// breaks, so the shell refs must be encoded, not quoted.
|
|
335
|
+
function buildEncodedUrlExport({ scheme, defaultPort, defaultName }) {
|
|
336
|
+
const nodeEncode = `node -e 'var s="${scheme}",a=process.argv.slice(1);console.log(s+"://"+encodeURIComponent(a[0])+":"+encodeURIComponent(a[1])+"@"+a[2]+":"+a[3]+"/"+a[4])' "$_u" "$_p" "$_h" "$_o" "$_n"`;
|
|
337
|
+
const sedEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$(_grada_enc "$_u")" "$(_grada_enc "$_p")" "$_h" "$_o" "$_n"`;
|
|
338
|
+
const rawEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$_u" "$_p" "$_h" "$_o" "$_n"`;
|
|
339
|
+
return `_grada_db_url() { _u="\${DB_USER}"; _p="\${DB_PASSWORD}"; _h="\${DB_HOST}"; _o="\${DB_PORT:-${defaultPort}}"; _n="\${DB_NAME:-${defaultName}}"; `
|
|
340
|
+
+ `if command -v node >/dev/null 2>&1; then ${nodeEncode}; `
|
|
341
|
+
+ `elif command -v sed >/dev/null 2>&1; then _grada_enc() { printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/?/%3F/g' -e 's/#/%23/g' -e 's/@/%40/g' -e 's/:/%3A/g' -e 's|/|%2F|g'; }; ${sedEncode}; `
|
|
342
|
+
+ `else echo "grada: warning: DATABASE_URL built without userinfo encoding (no node or sed in image)" >&2; ${rawEncode}; fi; }; `
|
|
343
|
+
+ `if [ -z "\${DATABASE_URL:-}" ]; then export DATABASE_URL="$(_grada_db_url)"; fi`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Builds the container override command for an ephemeral runner task. When
|
|
347
|
+
// the task definition provides discrete `DB_*` credentials but no
|
|
348
|
+
// `DATABASE_URL`, the command exports a runtime-synthesized URL (from the
|
|
349
|
+
// container's own environment, so secrets never cross the RunTask API
|
|
350
|
+
// call) before running the user's command. Pure and unit-tested.
|
|
351
|
+
export function buildRunnerCommand(resolvedCmd, containerDef) {
|
|
352
|
+
const cmd = String(resolvedCmd ?? '');
|
|
353
|
+
const environment = Array.isArray(containerDef?.environment) ? containerDef.environment : [];
|
|
354
|
+
const secrets = Array.isArray(containerDef?.secrets) ? containerDef.secrets : [];
|
|
355
|
+
const entries = [...environment, ...secrets];
|
|
356
|
+
const names = new Set(entries.map((entry) => entry?.name));
|
|
357
|
+
if (names.has('DATABASE_URL')) return ['sh', '-c', cmd];
|
|
358
|
+
if (!names.has('DB_HOST') || !names.has('DB_USER') || !names.has('DB_PASSWORD')) {
|
|
359
|
+
return ['sh', '-c', cmd];
|
|
360
|
+
}
|
|
361
|
+
const values = new Map(entries.map((entry) => [entry?.name, entry?.value]));
|
|
362
|
+
const scheme = sniffRunnerScheme(entries, values);
|
|
363
|
+
// RDS/Aurora enforces `rds.force_ssl = 1` by default: require TLS for
|
|
364
|
+
// synthesized postgres URLs so libpq-based migrations never fail on a
|
|
365
|
+
// plaintext connection (MySQL clients ignore PGSSLMODE; leave them alone).
|
|
366
|
+
const tlsPrefix = scheme === 'postgresql' ? 'export PGSSLMODE="${PGSSLMODE:-require}"; ' : '';
|
|
367
|
+
const urlExport = buildEncodedUrlExport({
|
|
368
|
+
scheme,
|
|
369
|
+
defaultPort: scheme === 'mysql' ? '3306' : '5432',
|
|
370
|
+
defaultName: scheme === 'mysql' ? 'mysql' : 'postgres',
|
|
371
|
+
});
|
|
372
|
+
return ['sh', '-c', `${tlsPrefix}${urlExport}; ${cmd}`];
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Validates `--timeout` for ephemeral-runner commands (`db migrate`,
|
|
376
|
+
// `run`): returns the seconds on success, or the failCommand result
|
|
377
|
+
// (printed, tracked, and exited) when invalid. Callers branch on
|
|
378
|
+
// `typeof result !== 'number'`.
|
|
379
|
+
export async function parseRunnerTimeout(timeoutRaw, defaultSeconds, { event, telemetry = {}, resultExtra = {} } = {}) {
|
|
380
|
+
const timeoutSeconds = parseTimeoutSeconds(timeoutRaw, defaultSeconds);
|
|
381
|
+
if (timeoutSeconds !== null) return timeoutSeconds;
|
|
382
|
+
return failCommand({
|
|
383
|
+
message: `\n✖ Invalid --timeout "${timeoutRaw}". Use a positive number of seconds (default ${defaultSeconds}).\n`,
|
|
384
|
+
event,
|
|
385
|
+
telemetry,
|
|
386
|
+
errorCode: 'INVALID_TIMEOUT',
|
|
387
|
+
reason: 'invalid-timeout',
|
|
388
|
+
resultExtra,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Stripped-runner guard for ephemeral-runner commands: Grada's
|
|
393
|
+
// node-family images remove npm/npx/yarn from the runner stage, so an
|
|
394
|
+
// npm-shim command is a guaranteed `command not found` inside the task.
|
|
395
|
+
// Fail fast headless; warn loudly (and proceed) interactively. Fail-open
|
|
396
|
+
// when no Dockerfile is present — nothing to prove breakage against.
|
|
397
|
+
// Returns null to proceed, or the failCommand result when refusing.
|
|
398
|
+
export async function guardNpmStrippedRunner({
|
|
399
|
+
resolvedCmd, cwd, headless, event, telemetry = {}, resultExtra = {},
|
|
400
|
+
nodeExample = 'node ./dist/migrate.cjs',
|
|
401
|
+
}) {
|
|
402
|
+
if (!isNpmShimCommand(resolvedCmd) || !dockerfileStripsNpmShims(readFileSafe(path.join(cwd, 'Dockerfile')))) {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
const ormHint = ormMappedHintSegment(cwd, '--cmd ');
|
|
406
|
+
if (headless) {
|
|
407
|
+
return failCommand({
|
|
408
|
+
message: `\n✖ Refusing to run "${resolvedCmd}": your Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" inside the task.\n`,
|
|
409
|
+
hint: ` Bundle a framework-compiled runner instead and re-run with an explicit node-based command, e.g. --cmd "${nodeExample}". Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
|
|
410
|
+
event,
|
|
411
|
+
telemetry: { ...telemetry, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
|
|
412
|
+
errorCode: 'NPM_CMD_STRIPPED_RUNNER',
|
|
413
|
+
reason: 'npm-cmd-stripped-runner',
|
|
414
|
+
resultExtra,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
console.log(color.yellow(`⚠️ "${resolvedCmd}" starts with npm/npx but your Dockerfile strips those binaries from the runner image — this will fail with "command not found" unless you switch to a node-based command (e.g. "${nodeExample}"). Ensure your Dockerfile builds the bundle and copies it into the runner image.${ormHint}`));
|
|
418
|
+
trackEvent('npm_cmd_stripped_runner', { ...telemetry });
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Maps a runEphemeralEcsTask outcome to the caller's terminal result:
|
|
423
|
+
// stops the spinner with command-specific wording, prints, tracks, and
|
|
424
|
+
// exits via failCommand — or records success and returns the success
|
|
425
|
+
// object. `label` names the finished unit ("Migration succeeded."),
|
|
426
|
+
// `taskPhrase` names the placed unit ("the migration task cannot be
|
|
427
|
+
// placed"). Callers return this result directly.
|
|
428
|
+
export async function reportRunnerOutcome({
|
|
429
|
+
outcome, spinner: s, event, telemetry = {},
|
|
430
|
+
cluster, service, region,
|
|
431
|
+
containerName, label, taskPhrase,
|
|
432
|
+
timeoutSeconds, timeoutCode, timeoutReason,
|
|
433
|
+
taskFailedCode, taskFailedReason,
|
|
434
|
+
}) {
|
|
435
|
+
const resultExtra = { cluster, service, region };
|
|
436
|
+
|
|
437
|
+
if (!outcome.ok && outcome.code === 'ECS_SERVICE_NOT_FOUND') {
|
|
438
|
+
s.stop(color.yellow('Service not found.'));
|
|
439
|
+
return failCommand({
|
|
440
|
+
print: () => {
|
|
441
|
+
console.log(`\n The ECS service ${color.cyan(service)} does not exist or is inactive.`);
|
|
442
|
+
console.log(` Run ${color.green('npx grada-run apply')} to provision your infrastructure.\n`);
|
|
443
|
+
},
|
|
444
|
+
event,
|
|
445
|
+
telemetry,
|
|
446
|
+
errorCode: 'ECS_SERVICE_NOT_FOUND',
|
|
447
|
+
reason: 'ecs-service-not-found',
|
|
448
|
+
resultExtra,
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (!outcome.ok && outcome.code === 'NO_VPC_CONFIG') {
|
|
453
|
+
s.stop(color.red('Service has no VPC configuration.'));
|
|
454
|
+
return failCommand({
|
|
455
|
+
message: `\n✖ The ECS service ${color.cyan(service)} has no VPC network configuration, so the ${taskPhrase} cannot be placed.\n`,
|
|
456
|
+
event,
|
|
457
|
+
telemetry,
|
|
458
|
+
errorCode: 'RUN_TASK_FAILED',
|
|
459
|
+
reason: 'run-task-failed',
|
|
460
|
+
resultExtra,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (!outcome.ok && outcome.code === 'CONTAINER_NOT_FOUND') {
|
|
465
|
+
s.stop(color.red('Container not found.'));
|
|
466
|
+
return failCommand({
|
|
467
|
+
message: `\n✖ Container "${containerName}" does not exist in task definition "${outcome.targetTaskDef}".\n`,
|
|
468
|
+
hint: `Override with --container <name>. Available: ${outcome.available.join(', ') || 'none'}\n`,
|
|
469
|
+
event,
|
|
470
|
+
telemetry,
|
|
471
|
+
errorCode: 'CONTAINER_NOT_FOUND',
|
|
472
|
+
reason: 'container-not-found',
|
|
473
|
+
resultExtra,
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (!outcome.ok && outcome.code === 'RUN_TASK_FAILED') {
|
|
478
|
+
s.stop(color.red(`Failed to start ${taskPhrase}.`));
|
|
479
|
+
return failCommand({
|
|
480
|
+
message: `\n✖ ECS could not start the ${taskPhrase}: ${outcome.reason}.\n`,
|
|
481
|
+
event,
|
|
482
|
+
telemetry,
|
|
483
|
+
errorCode: 'RUN_TASK_FAILED',
|
|
484
|
+
reason: 'run-task-failed',
|
|
485
|
+
resultExtra,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
|
|
489
|
+
return failNamedContainerMissing({
|
|
490
|
+
spinner: s, outcome, cluster, service, region,
|
|
491
|
+
event,
|
|
492
|
+
telemetry,
|
|
493
|
+
noun: label,
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
if (!outcome.ok && outcome.code === 'TIMEOUT') {
|
|
497
|
+
try { s.stop(color.yellow(`${label} timed out.`)); } catch { /* already stopped */ }
|
|
498
|
+
return failCommand({
|
|
499
|
+
message: `\n✖ ${label} timed out after ${timeoutSeconds}s. The task was stopped (best-effort); increase --timeout and retry.\n`,
|
|
500
|
+
event,
|
|
501
|
+
telemetry,
|
|
502
|
+
errorCode: timeoutCode,
|
|
503
|
+
reason: timeoutReason,
|
|
504
|
+
resultExtra: { ...resultExtra, taskArn: outcome.taskArn },
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const exitCode = outcome.exitCode;
|
|
509
|
+
const stoppedReason = outcome.stoppedReason;
|
|
510
|
+
if (exitCode === 0) {
|
|
511
|
+
// Owner pairs its own start/stop: the runner usually stops
|
|
512
|
+
// first (idempotent no-op then), but success must never
|
|
513
|
+
// depend on a callee for the spinner lifecycle (BUG-202).
|
|
514
|
+
try { s.stop(color.green(`${label} succeeded.`)); } catch { /* already stopped */ }
|
|
515
|
+
console.log(color.green(`\n✅ ${label} succeeded.`));
|
|
516
|
+
await trackSuccess(event, { ...telemetry });
|
|
517
|
+
outro(color.green('Done.'));
|
|
518
|
+
return { ok: true, success: true, exitCode: 0, taskArn: outcome.taskArn };
|
|
519
|
+
}
|
|
520
|
+
const propagated = (typeof exitCode === 'number' && exitCode > 0) ? exitCode : 1;
|
|
521
|
+
// The ECS stopped reason is the only diagnosis PostHog gets for a
|
|
522
|
+
// failed task (exit codes alone can't distinguish image-pull from
|
|
523
|
+
// command-not-found from task errors) — stamp it.
|
|
524
|
+
const failureDetail = `${label} failed with exit code ${exitCode ?? 'unknown'}: ${stoppedReason}`;
|
|
525
|
+
return failCommand({
|
|
526
|
+
message: `\n✖ ${failureDetail}.\n`,
|
|
527
|
+
event,
|
|
528
|
+
telemetry,
|
|
529
|
+
errorCode: taskFailedCode,
|
|
530
|
+
extra: { exit_code: exitCode ?? -1, error_message: failureDetail },
|
|
531
|
+
reason: taskFailedReason,
|
|
532
|
+
resultExtra: { ...resultExtra, taskArn: outcome.taskArn },
|
|
533
|
+
exitCode: propagated,
|
|
534
|
+
});
|
|
535
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
name: Terraform Plan on PR
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
# pull_request_target (not pull_request): this file comes from the base
|
|
5
|
+
# branch, so a fork PR cannot delete the same-repo guard below to reach
|
|
6
|
+
# the admin CI role (BUG-140). The PR head is checked out explicitly by
|
|
7
|
+
# SHA in the guarded step instead.
|
|
8
|
+
pull_request_target:
|
|
9
|
+
types: [opened, synchronize, reopened]
|
|
10
|
+
paths:
|
|
11
|
+
- 'terraform/**'
|
|
12
|
+
|
|
13
|
+
# One runner per PR: rapid pushes cancel superseded plans instead of
|
|
14
|
+
# overlapping runs on the same state.
|
|
15
|
+
concurrency:
|
|
16
|
+
group: plan-${{ github.event.pull_request.number }}
|
|
17
|
+
cancel-in-progress: true
|
|
18
|
+
|
|
19
|
+
env:
|
|
20
|
+
AWS_REGION: {{REGION}}
|
|
21
|
+
|
|
22
|
+
permissions:
|
|
23
|
+
id-token: write
|
|
24
|
+
contents: read
|
|
25
|
+
pull-requests: write # Required to post the plan comment
|
|
26
|
+
|
|
27
|
+
jobs:
|
|
28
|
+
terraform-plan:
|
|
29
|
+
name: Terraform Plan
|
|
30
|
+
# Same-repo PRs only: fork code must never execute with the admin CI
|
|
31
|
+
# role. Trustworthy because this file comes from base (see trigger
|
|
32
|
+
# above). Public repos needing fork plans should gate this job
|
|
33
|
+
# behind an environment with required reviewers instead of deleting
|
|
34
|
+
# the guard.
|
|
35
|
+
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
36
|
+
runs-on: ubuntu-latest
|
|
37
|
+
timeout-minutes: 30
|
|
38
|
+
|
|
39
|
+
steps:
|
|
40
|
+
- name: Checkout PR head
|
|
41
|
+
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
42
|
+
with:
|
|
43
|
+
# Pinned SHA (not a ref name): the exact head this event fired
|
|
44
|
+
# for, immune to ref moves between event and checkout.
|
|
45
|
+
ref: ${{ github.event.pull_request.head.sha }}
|
|
46
|
+
|
|
47
|
+
- name: Configure AWS credentials
|
|
48
|
+
id: aws-creds
|
|
49
|
+
uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
|
|
50
|
+
continue-on-error: true
|
|
51
|
+
with:
|
|
52
|
+
role-to-assume: {{ROLE_ARN}}
|
|
53
|
+
aws-region: ${{ env.AWS_REGION }}
|
|
54
|
+
|
|
55
|
+
# Plan-on-PR is a merge signal: a failed assume fails the run with
|
|
56
|
+
# the bootstrap pointer (deploy shape, BUG-138) — never green-silent.
|
|
57
|
+
- name: Interpret credential failure
|
|
58
|
+
if: steps.aws-creds.outcome == 'failure'
|
|
59
|
+
run: |
|
|
60
|
+
echo "::error::AWS credential assumption failed — if the stack was never provisioned, bootstrap it first (npx grada-run apply); otherwise check terraform/oidc.tf trust."
|
|
61
|
+
exit 1
|
|
62
|
+
|
|
63
|
+
- name: Setup Terraform
|
|
64
|
+
uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
|
|
65
|
+
with:
|
|
66
|
+
# The wrapper mangles -detailed-exitcode; raw codes (0/1/2) are the signal.
|
|
67
|
+
terraform_wrapper: false
|
|
68
|
+
|
|
69
|
+
- name: Terraform Init
|
|
70
|
+
working-directory: ./terraform
|
|
71
|
+
run: terraform init -input=false
|
|
72
|
+
|
|
73
|
+
# -detailed-exitcode: 0 = no changes, 1 = error, 2 = changes present.
|
|
74
|
+
# Exit 2 posts the plan and stays green — the comment is the signal.
|
|
75
|
+
# Exit 1 (plan ERROR) fails the job after the comment posts below.
|
|
76
|
+
- name: Terraform Plan
|
|
77
|
+
id: plan
|
|
78
|
+
working-directory: ./terraform
|
|
79
|
+
run: |
|
|
80
|
+
set +e
|
|
81
|
+
terraform plan -input=false -lock-timeout=5m -detailed-exitcode -no-color -out=tfplan > plan-full.txt 2>&1
|
|
82
|
+
EXITCODE=$?
|
|
83
|
+
echo "exitcode=$EXITCODE" >> "$GITHUB_OUTPUT"
|
|
84
|
+
if [ "$EXITCODE" != "1" ]; then
|
|
85
|
+
terraform show -no-color tfplan > plan.txt
|
|
86
|
+
else
|
|
87
|
+
cp plan-full.txt plan.txt
|
|
88
|
+
fi
|
|
89
|
+
# Exit 1 fails the job; the comment step still posts via its
|
|
90
|
+
# always() gate so the error lands on the PR, not just the log.
|
|
91
|
+
if [ "$EXITCODE" = "1" ]; then exit 1; fi
|
|
92
|
+
|
|
93
|
+
- name: Comment plan on PR
|
|
94
|
+
if: always() && steps.plan.outputs.exitcode != ''
|
|
95
|
+
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
|
96
|
+
with:
|
|
97
|
+
script: |
|
|
98
|
+
const fs = require('fs');
|
|
99
|
+
const { owner, repo } = context.repo;
|
|
100
|
+
const marker = '<!-- grada-plan -->';
|
|
101
|
+
const exitcode = '${{ steps.plan.outputs.exitcode }}';
|
|
102
|
+
const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${context.runId}`;
|
|
103
|
+
let plan = '';
|
|
104
|
+
try {
|
|
105
|
+
plan = fs.readFileSync('terraform/plan.txt', 'utf8');
|
|
106
|
+
} catch (error) {
|
|
107
|
+
plan = '(plan output unavailable)';
|
|
108
|
+
}
|
|
109
|
+
if (plan.length > 30000) {
|
|
110
|
+
plan = `${plan.slice(0, 30000)}\n... (truncated, see ${runUrl})`;
|
|
111
|
+
}
|
|
112
|
+
let summary = '';
|
|
113
|
+
if (exitcode === '2') {
|
|
114
|
+
const match = /^Plan:.*$/m.exec(plan);
|
|
115
|
+
summary = match ? match[0] : 'Plan: changes present';
|
|
116
|
+
} else if (exitcode === '1') {
|
|
117
|
+
summary = 'Plan: errored';
|
|
118
|
+
} else {
|
|
119
|
+
summary = 'No changes';
|
|
120
|
+
}
|
|
121
|
+
const heading = exitcode === '1' ? '## ❌ Terraform Plan Failed' : '## Terraform Plan';
|
|
122
|
+
const body = `${marker}\n${heading}\n\n**${summary}** ([workflow run](${runUrl})).\n\n<details><summary>Show Plan</summary>\n\n\`\`\`diff\n${plan}\n\`\`\`\n\n</details>`;
|
|
123
|
+
const { data: comments } = await github.rest.issues.listComments({
|
|
124
|
+
issue_number: context.issue.number,
|
|
125
|
+
owner: context.repo.owner,
|
|
126
|
+
repo: context.repo.repo,
|
|
127
|
+
});
|
|
128
|
+
const existing = comments.find((comment) => comment.body?.includes(marker));
|
|
129
|
+
if (existing) {
|
|
130
|
+
await github.rest.issues.updateComment({
|
|
131
|
+
owner: context.repo.owner,
|
|
132
|
+
repo: context.repo.repo,
|
|
133
|
+
comment_id: existing.id,
|
|
134
|
+
body,
|
|
135
|
+
});
|
|
136
|
+
} else {
|
|
137
|
+
await github.rest.issues.createComment({
|
|
138
|
+
issue_number: context.issue.number,
|
|
139
|
+
owner: context.repo.owner,
|
|
140
|
+
repo: context.repo.repo,
|
|
141
|
+
body,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
# Fork PRs skip the privileged job above loudly instead of silently:
|
|
146
|
+
# no credentials are issued and no plan is posted.
|
|
147
|
+
fork-notice:
|
|
148
|
+
name: Fork PR notice
|
|
149
|
+
if: github.event.pull_request.head.repo.full_name != github.repository
|
|
150
|
+
runs-on: ubuntu-latest
|
|
151
|
+
timeout-minutes: 5
|
|
152
|
+
steps:
|
|
153
|
+
- run: echo "Terraform plan runs for same-repo pull requests only — fork PR #${{ github.event.pull_request.number }} skipped (no AWS credentials issued)."
|