grada-run 0.40.14 → 0.40.16

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 CHANGED
@@ -128,11 +128,11 @@ if (wantsVersion) {
128
128
  } else if (positionalArgs[0] === 'secrets' && positionalArgs[1] === 'push') {
129
129
  const envFile = positionalArgs[2] || '.env';
130
130
  const projectName = path.basename(process.cwd());
131
- runCommand(pushSecrets(envFile, projectName, { isHeadless, region: parseRegionFlag(rawArgs) }));
131
+ runCommand(pushSecrets(envFile, projectName, { ...(isHeadless ? { isHeadless: true } : {}), region: parseRegionFlag(rawArgs) }));
132
132
  } else if (positionalArgs[0] === 'secrets' && positionalArgs[1] === 'pull') {
133
133
  const envFile = positionalArgs[2] || '.env';
134
134
  const projectName = path.basename(process.cwd());
135
- runCommand(pullSecrets(envFile, projectName, { isHeadless, region: parseRegionFlag(rawArgs) }));
135
+ runCommand(pullSecrets(envFile, projectName, { ...(isHeadless ? { isHeadless: true } : {}), region: parseRegionFlag(rawArgs) }));
136
136
  } else if (positionalArgs[0] === 'secrets' && positionalArgs[1] === 'audit') {
137
137
  const envFile = positionalArgs[2] || '.env';
138
138
  const projectName = path.basename(process.cwd());
@@ -178,7 +178,7 @@ if (wantsVersion) {
178
178
  } else if (positionalArgs[0] === 'telemetry') {
179
179
  runCommand(runTelemetry({ subcommand: positionalArgs[1], ...(isHeadless ? { isHeadless: true } : {}) }));
180
180
  } else if (positionalArgs[0] === undefined || positionalArgs[0] === 'init') {
181
- runCommand(mainStack({ isHeadless, isPreconfigured, headlessOptions, initOptions }));
181
+ runCommand(mainStack({ ...(isHeadless ? { isHeadless: true } : {}), isPreconfigured, headlessOptions, initOptions }));
182
182
  } else {
183
183
  // Unknown input must never scaffold: a typo is not an init request.
184
184
  console.error(`\n✖ Unknown command "${positionalArgs[0]}".`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.40.14",
3
+ "version": "0.40.16",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -460,6 +460,45 @@ export const LAMBDA_VPC_CONFIG_BLOCK = ` vpc_config {
460
460
  security_group_ids = [aws_security_group.ecs_tasks.id]
461
461
  }`;
462
462
 
463
+ // Isolated subnets shared by every data-plane subnet group (RDS,
464
+ // ElastiCache). network.tf carries this block on new trees; `add` backfills
465
+ // it for trees generated before it moved out of database.tf (which only
466
+ // existed alongside a database).
467
+ export const ISOLATED_SUBNETS_BLOCK = `# Isolated Subnets (No Internet Gateway routing). Shared by every
468
+ # data-plane subnet group (RDS, ElastiCache).
469
+ resource "aws_subnet" "db_isolated" {
470
+ count = 2
471
+ vpc_id = aws_vpc.main.id
472
+ cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index + 10)
473
+ availability_zone = data.aws_availability_zones.available.names[count.index]
474
+
475
+ tags = {
476
+ Name = "\${local.app_name}-db-isolated-\${count.index}"
477
+ }
478
+ }`;
479
+
480
+ // Idempotently appends the isolated-subnet block to network.tf content.
481
+ // Returns the content unchanged when the block already exists.
482
+ export function ensureIsolatedSubnets(networkTfContent) {
483
+ const content = String(networkTfContent ?? '');
484
+ if (content.includes('resource "aws_subnet" "db_isolated"')) return content;
485
+ const prefix = content.endsWith('\n') ? content : `${content}\n`;
486
+ return `${prefix}\n${ISOLATED_SUBNETS_BLOCK}\n`;
487
+ }
488
+
489
+ // Backfills the isolated-subnet block into a tree whose network.tf predates
490
+ // it. No-op when network.tf is missing (static) or already has the block.
491
+ // Returns true when the file was written.
492
+ async function backfillIsolatedSubnets(projectDir) {
493
+ const networkTfPath = path.join(projectDir, 'terraform', 'network.tf');
494
+ if (!fsSync.existsSync(networkTfPath)) return false;
495
+ const before = await fs.readFile(networkTfPath, 'utf-8');
496
+ const after = ensureIsolatedSubnets(before);
497
+ if (after === before) return false;
498
+ await atomicWriteFile(networkTfPath, normalizeBlankLines(after));
499
+ return true;
500
+ }
501
+
463
502
  // Idempotently attaches `vpc_config` to `aws_lambda_function."app"` (used
464
503
  // when `add db:redis` runs on a Lambda project generated without a
465
504
  // database). Returns the content unchanged for ECS projects or when the
@@ -1469,6 +1508,9 @@ async function scaffoldDatabaseInner(engine, projectDir, refs) {
1469
1508
  } else {
1470
1509
  await atomicWriteFile(databaseTfPath, normalizeBlankLines(rendered));
1471
1510
  }
1511
+ // Engine templates reference the shared isolated subnets: backfill the
1512
+ // block on trees generated before it moved to network.tf.
1513
+ const subnetsBackfilled = await backfillIsolatedSubnets(projectDir);
1472
1514
 
1473
1515
  let randomInjected = false;
1474
1516
  if (isLambda) {
@@ -1518,6 +1560,7 @@ async function scaffoldDatabaseInner(engine, projectDir, refs) {
1518
1560
  workerEnvInjected,
1519
1561
  vpcInjected,
1520
1562
  randomInjected,
1563
+ subnetsBackfilled,
1521
1564
  ejected,
1522
1565
  };
1523
1566
  }
@@ -1659,6 +1702,13 @@ async function scaffoldAddonInner(capability, resolvedOpts, { cwd, region } = {}
1659
1702
  await atomicWriteFile(targetPath, normalizeBlankLines(rendered));
1660
1703
  }
1661
1704
 
1705
+ // Addons referencing the shared isolated subnets (db:redis) backfill the
1706
+ // block on trees generated before it moved to network.tf.
1707
+ let subnetsBackfilled = false;
1708
+ if (rendered.includes('aws_subnet.db_isolated')) {
1709
+ subnetsBackfilled = await backfillIsolatedSubnets(projectDir);
1710
+ }
1711
+
1662
1712
  const envVars = Array.isArray(opts.envVars) ? opts.envVars : [];
1663
1713
  const upsertKeys = Array.isArray(opts.upsertKeys) ? opts.upsertKeys : [];
1664
1714
  const injectOptions = upsertKeys.length > 0 ? { upsertKeys } : {};
@@ -1697,6 +1747,7 @@ async function scaffoldAddonInner(capability, resolvedOpts, { cwd, region } = {}
1697
1747
  envInjected,
1698
1748
  workerEnvInjected,
1699
1749
  vpcInjected,
1750
+ subnetsBackfilled,
1700
1751
  ejected,
1701
1752
  };
1702
1753
  }
@@ -2,7 +2,7 @@ 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 { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../../core/telemetry.js';
5
+ import { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName, getCliVersion } from '../../core/telemetry.js';
6
6
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized } from '../../utils/command.js';
7
7
  import { parseFlags, normalizeOptions, normalizeArgv } from '../../utils/args.js';
8
8
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/aws.js';
@@ -113,45 +113,50 @@ function stripPreviousGateBlock(content) {
113
113
  return content.slice(0, lineStart) + content.slice(lineEnd === -1 ? content.length : lineEnd + 1);
114
114
  }
115
115
 
116
+ // Builds the CI invocation of this CLI for injected gate blocks: pinned to
117
+ // the installing version so pipelines stay reproducible across releases.
118
+ // Falls back to the unpinned runner when the version is unknowable
119
+ // (source checkouts report 'unknown').
120
+ export function buildRunnerInvocation(cliVersion) {
121
+ const ver = typeof cliVersion === 'string' ? cliVersion.trim() : '';
122
+ if (ver === '' || ver === 'unknown') return 'npx grada-run';
123
+ return `npx --yes @grada-run/grada@${ver}`;
124
+ }
125
+
126
+ // Shared injection core: strips any previous gate, renders the block, and
127
+ // splices it before the anchor step. Returns null without the anchor.
128
+ function injectGateBlock(content, { runLine, stepName, anchor }) {
129
+ const base = stripPreviousGateBlock(String(content ?? ''));
130
+ const includeSetupNode = !base.includes('actions/setup-node');
131
+ const block = renderGateBlock({ includeSetupNode, stepName, runLine });
132
+ const anchorIdx = base.indexOf(anchor);
133
+ if (anchorIdx === -1) return null;
134
+ const insertAt = base.lastIndexOf('\n', anchorIdx) + 1;
135
+ return `${base.slice(0, insertAt)}${block}${base.slice(insertAt)}`;
136
+ }
137
+
116
138
  // Idempotently injects (or refreshes) the migration gate block into a
117
139
  // deploy.yml document. Returns the updated content, or null when neither
118
140
  // anchor step is present. Pure and unit-tested.
119
- export function injectMigrationGate(workflowContent, { cmd }) {
120
- const content = String(workflowContent ?? '');
141
+ export function injectMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
121
142
  const taskDefRef = '${{ steps.register-task-def.outputs.task-arn }}';
122
-
123
- const base = stripPreviousGateBlock(content);
124
- const includeSetupNode = !base.includes('actions/setup-node');
125
- const block = renderGateBlock({
126
- includeSetupNode,
143
+ return injectGateBlock(workflowContent, {
127
144
  stepName: 'Pre-Deploy Database Migration',
128
- runLine: `npx grada-run db migrate --cmd ${quoteShellArg(cmd)} --task-def "${taskDefRef}" --headless`,
145
+ runLine: `${buildRunnerInvocation(cliVersion)} db migrate --cmd ${quoteShellArg(cmd)} --task-def "${taskDefRef}" --headless`,
146
+ anchor: '- name: Force ECS deployment',
129
147
  });
130
-
131
- const forceIdx = base.indexOf('- name: Force ECS deployment');
132
- if (forceIdx === -1) return null;
133
- const insertAt = base.lastIndexOf('\n', forceIdx) + 1;
134
- return `${base.slice(0, insertAt)}${block}${base.slice(insertAt)}`;
135
148
  }
136
149
 
137
150
  // Idempotently injects (or refreshes) the migration gate block into a
138
151
  // preview.yml document (ECS only — Lambda has no migrate-gate story yet).
139
152
  // Previews have no register step, so `db migrate` resolves the workspace
140
153
  // service itself via --workspace. Returns null without the anchor.
141
- export function injectPreviewMigrationGate(workflowContent, { cmd }) {
142
- const content = String(workflowContent ?? '');
143
- const base = stripPreviousGateBlock(content);
144
- const includeSetupNode = !base.includes('actions/setup-node');
145
- const block = renderGateBlock({
146
- includeSetupNode,
154
+ export function injectPreviewMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
155
+ return injectGateBlock(workflowContent, {
147
156
  stepName: 'Preview Database Migration',
148
- runLine: `npx grada-run db migrate --cmd ${quoteShellArg(cmd)} --workspace "\${{ env.WORKSPACE }}" --headless`,
157
+ runLine: `${buildRunnerInvocation(cliVersion)} db migrate --cmd ${quoteShellArg(cmd)} --workspace "\${{ env.WORKSPACE }}" --headless`,
158
+ anchor: '- name: Comment PR',
149
159
  });
150
-
151
- const commentIdx = base.indexOf('- name: Comment PR');
152
- if (commentIdx === -1) return null;
153
- const insertAt = base.lastIndexOf('\n', commentIdx) + 1;
154
- return `${base.slice(0, insertAt)}${block}${base.slice(insertAt)}`;
155
160
  }
156
161
 
157
162
  // Builds the container override command for the migration task. When the
@@ -380,7 +385,7 @@ async function runDbMigrateMain(input = {}) {
380
385
  resultExtra: { cluster, service, region },
381
386
  });
382
387
  }
383
- const updated = injectMigrationGate(workflowContent, { cmd: resolvedCmd });
388
+ const updated = injectMigrationGate(workflowContent, { cmd: resolvedCmd, cliVersion: getCliVersion() });
384
389
  if (updated === null) {
385
390
  return failCommand({
386
391
  message: '\n✖ Could not find the task-definition registration or ECS deployment step in .github/workflows/deploy.yml to anchor the migration gate.\n',
@@ -403,7 +408,7 @@ async function runDbMigrateMain(input = {}) {
403
408
  previewContent = null;
404
409
  }
405
410
  if (previewContent !== null) {
406
- const previewUpdated = injectPreviewMigrationGate(previewContent, { cmd: resolvedCmd });
411
+ const previewUpdated = injectPreviewMigrationGate(previewContent, { cmd: resolvedCmd, cliVersion: getCliVersion() });
407
412
  if (previewUpdated !== null) {
408
413
  fsSync.writeFileSync(previewFile, previewUpdated, 'utf8');
409
414
  console.log(color.green('✅ Preview migration gate installed in .github/workflows/preview.yml.'));
@@ -809,7 +809,7 @@ async function mainStackMain(input = {}) {
809
809
  if (migrationGateEnabled && migrationCmd) {
810
810
  const deployYmlPath = path.join(dirConfig.targetDir, '.github', 'workflows', 'deploy.yml');
811
811
  const workflowContent = readFileSafe(deployYmlPath);
812
- const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd }) : null;
812
+ const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION }) : null;
813
813
  if (gated) {
814
814
  atomicWriteFileSync(deployYmlPath, gated);
815
815
  console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml'));
@@ -820,7 +820,7 @@ async function mainStackMain(input = {}) {
820
820
  const previewYmlPath = path.join(dirConfig.targetDir, '.github', 'workflows', 'preview.yml');
821
821
  const previewContent = readFileSafe(previewYmlPath);
822
822
  if (previewContent) {
823
- const previewGated = injectPreviewMigrationGate(previewContent, { cmd: migrationCmd });
823
+ const previewGated = injectPreviewMigrationGate(previewContent, { cmd: migrationCmd, cliVersion: CLI_VERSION });
824
824
  if (previewGated) {
825
825
  atomicWriteFileSync(previewYmlPath, previewGated);
826
826
  console.log(color.green('✅ Wired the preview database migration gate into .github/workflows/preview.yml'));
@@ -862,6 +862,7 @@ async function mainStackMain(input = {}) {
862
862
  trackEvent('project_provisioned', {
863
863
  // 1. Core & Context
864
864
  projectName: dirConfig.actualProjectName,
865
+ success: true, // funnel outcome: failures emit success:false via failCommand
865
866
  cli_version: CLI_VERSION,
866
867
  is_headless: isHeadless,
867
868
  setup_mode: config.setupType,
@@ -236,7 +236,7 @@ export async function runLambdaStatus(input = {}) {
236
236
 
237
237
  if (!health.healthy) {
238
238
  console.log(color.yellow(DEGRADED_MESSAGE));
239
- await trackFailure('status_run', { projectName, healthy: false, degraded: true });
239
+ await trackFailure('status_run', { projectName, healthy: false, degraded: true, reason: 'degraded' });
240
240
  if (options.watchMode) return { ...payload, watchMode: true };
241
241
  const diagnosis = await runDiagnose({ cwd, region });
242
242
  await failCommand({ exitCode: 1, noExit });
@@ -352,7 +352,7 @@ export async function runStaticStatus(input = {}) {
352
352
 
353
353
  if (!healthy) {
354
354
  console.log(color.yellow(` Distribution is ${distribution.Status} — CloudFront changes propagate in a few minutes.\n`));
355
- await trackFailure('status_run', { projectName, healthy: false, degraded: true });
355
+ await trackFailure('status_run', { projectName, healthy: false, degraded: true, reason: 'degraded' });
356
356
  if (options.watchMode) return { ...payload, watchMode: true };
357
357
  await failCommand({ exitCode: 1, noExit });
358
358
  return payload;
@@ -543,7 +543,7 @@ async function runStatusMain(input = {}) {
543
543
 
544
544
  if (!health.healthy) {
545
545
  console.log(color.yellow(DEGRADED_MESSAGE));
546
- await trackFailure('status_run', { projectName, healthy: false, degraded: true });
546
+ await trackFailure('status_run', { projectName, healthy: false, degraded: true, reason: 'degraded' });
547
547
  if (options.watchMode) return { ...payload, watchMode: true };
548
548
  const diagnosis = await runDiagnose({ cluster, region, logGroup });
549
549
  await failCommand({ exitCode: 1, noExit });
@@ -5,6 +5,13 @@ on:
5
5
  branches:
6
6
  - {{DEPLOY_BRANCH}}
7
7
 
8
+ # Overlapping deploys race: each run publishes its own image and calls
9
+ # update-function-code, so a stale run finishing last would silently
10
+ # regress production. Superseded runs cancel instead — newest always wins.
11
+ concurrency:
12
+ group: deploy-${{ github.ref }}
13
+ cancel-in-progress: true
14
+
8
15
  env:
9
16
  AWS_REGION: {{REGION}}
10
17
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
@@ -5,6 +5,13 @@ on:
5
5
  branches:
6
6
  - {{DEPLOY_BRANCH}}
7
7
 
8
+ # Overlapping deploys race: each run syncs its own build with --delete, so
9
+ # interleaved runs would publish a mixed old/new file set. Superseded runs
10
+ # cancel instead — newest always wins.
11
+ concurrency:
12
+ group: deploy-${{ github.ref }}
13
+ cancel-in-progress: true
14
+
8
15
  env:
9
16
  AWS_REGION: {{REGION}}
10
17
  S3_BUCKET: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-site-{{AWS_ACCOUNT_ID}}
@@ -5,6 +5,13 @@ on:
5
5
  branches:
6
6
  - {{DEPLOY_BRANCH}}
7
7
 
8
+ # Overlapping deploys race: each run registers its own revision and force-
9
+ # deploys, so a stale run finishing last would silently regress production.
10
+ # Superseded runs cancel instead — newest always wins.
11
+ concurrency:
12
+ group: deploy-${{ github.ref }}
13
+ cancel-in-progress: true
14
+
8
15
  env:
9
16
  AWS_REGION: {{REGION}}
10
17
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
@@ -99,10 +99,13 @@ jobs:
99
99
  }
100
100
 
101
101
  - name: Notify Slack
102
- if: steps.plan.outputs.exitcode == '2' && secrets.SLACK_WEBHOOK_URL != ''
102
+ if: steps.plan.outputs.exitcode == '2'
103
103
  env:
104
104
  SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
105
105
  run: |
106
+ # GitHub rejects the secrets context in step-level if: expressions,
107
+ # so the absent-secret skip lives here instead of the condition.
108
+ if [ -z "$SLACK_WEBHOOK_URL" ]; then exit 0; fi
106
109
  SUMMARY=$(head -c 1500 terraform/plan.txt)
107
110
  jq -n \
108
111
  --arg repo "$GITHUB_REPOSITORY" \
@@ -4,6 +4,13 @@ on:
4
4
  pull_request:
5
5
  types: [opened, synchronize, reopened]
6
6
 
7
+ # One runner per PR: rapid pushes cancel superseded previews instead of
8
+ # overlapping applies on the same workspace. Shares its group with
9
+ # teardown.yml, which queues (never cancels) behind an in-flight deploy.
10
+ concurrency:
11
+ group: preview-${{ github.event.pull_request.number }}
12
+ cancel-in-progress: true
13
+
7
14
  env:
8
15
  AWS_REGION: {{REGION}}
9
16
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
@@ -48,7 +55,7 @@ jobs:
48
55
  id: tf-apply
49
56
  working-directory: ./terraform
50
57
  run: |
51
- terraform init
58
+ terraform init -input=false
52
59
  # Create or select the workspace specific to this PR
53
60
  terraform workspace select -or-create ${{ env.WORKSPACE }}
54
61
  terraform apply -auto-approve
@@ -4,6 +4,13 @@ on:
4
4
  pull_request:
5
5
  types: [opened, synchronize, reopened]
6
6
 
7
+ # One runner per PR: rapid pushes cancel superseded previews instead of
8
+ # overlapping applies on the same workspace. Shares its group with
9
+ # teardown.yml, which queues (never cancels) behind an in-flight deploy.
10
+ concurrency:
11
+ group: preview-${{ github.event.pull_request.number }}
12
+ cancel-in-progress: true
13
+
7
14
  env:
8
15
  AWS_REGION: {{REGION}}
9
16
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
@@ -48,7 +55,7 @@ jobs:
48
55
  id: tf-apply
49
56
  working-directory: ./terraform
50
57
  run: |
51
- terraform init
58
+ terraform init -input=false
52
59
  # Create or select the workspace specific to this PR
53
60
  terraform workspace select -or-create ${{ env.WORKSPACE }}
54
61
  terraform apply -auto-approve
@@ -4,6 +4,12 @@ on:
4
4
  pull_request:
5
5
  types: [closed]
6
6
 
7
+ # Shared with the preview workflow: teardown queues behind an in-flight
8
+ # deploy instead of racing it on the state lock. No cancel-in-progress —
9
+ # a teardown must run to completion, never be skipped.
10
+ concurrency:
11
+ group: preview-${{ github.event.pull_request.number }}
12
+
7
13
  env:
8
14
  AWS_REGION: {{REGION}}
9
15
  WORKSPACE: pr-${{ github.event.pull_request.number }}
@@ -33,7 +39,13 @@ jobs:
33
39
  - name: Terraform Init & Destroy
34
40
  working-directory: ./terraform
35
41
  run: |
36
- terraform init
42
+ terraform init -input=false
43
+ # PRs that never got a preview (early failure, pre-previews PR)
44
+ # have no workspace — exit green instead of failing the run.
45
+ if ! terraform workspace list 2>/dev/null | sed 's/^[* ]*//' | grep -qx "${{ env.WORKSPACE }}"; then
46
+ echo "No preview workspace ${{ env.WORKSPACE }} — nothing to tear down."
47
+ exit 0
48
+ fi
37
49
  # Select the PR workspace
38
50
  terraform workspace select ${{ env.WORKSPACE }}
39
51
  # Destroy all resources in this workspace safely
@@ -5,10 +5,10 @@
5
5
  # Billing: fixed ~$9.49/mo baseline (cache.t4g.micro Valkey 8.0 at $0.013/hr
6
6
  # in us-east-2); $0 intra-AZ VPC data transfer.
7
7
 
8
- # --- ElastiCache Subnet Group ---
8
+ # --- ElastiCache Subnet Group (isolated subnets, shared with RDS) ---
9
9
  resource "aws_elasticache_subnet_group" "redis" {
10
10
  name = "${local.app_name}-redis-subnets"
11
- subnet_ids = aws_subnet.public[*].id
11
+ subnet_ids = aws_subnet.db_isolated[*].id
12
12
  }
13
13
 
14
14
  # --- Redis Security Group (ECS tasks only) ---
@@ -1,15 +1,5 @@
1
- # 1. Isolated Subnets (No Internet Gateway routing)
2
- resource "aws_subnet" "db_isolated" {
3
- count = 2
4
- vpc_id = aws_vpc.main.id
5
- cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index + 10)
6
- availability_zone = data.aws_availability_zones.available.names[count.index]
7
-
8
- tags = {
9
- Name = "${local.app_name}-db-isolated-${count.index}"
10
- }
11
- }
12
-
1
+ # 1. Database Subnet Group (isolated subnets live in network.tf, shared
2
+ # with ElastiCache so every data-plane group stays off public subnets)
13
3
  resource "aws_db_subnet_group" "main" {
14
4
  name = "${local.app_name}-db-subnet-group"
15
5
  subnet_ids = aws_subnet.db_isolated[*].id
@@ -1,15 +1,5 @@
1
- # 1. Isolated Subnets (No Internet Gateway routing)
2
- resource "aws_subnet" "db_isolated" {
3
- count = 2
4
- vpc_id = aws_vpc.main.id
5
- cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index + 10)
6
- availability_zone = data.aws_availability_zones.available.names[count.index]
7
-
8
- tags = {
9
- Name = "${local.app_name}-db-isolated-${count.index}"
10
- }
11
- }
12
-
1
+ # 1. Database Subnet Group (isolated subnets live in network.tf, shared
2
+ # with ElastiCache so every data-plane group stays off public subnets)
13
3
  resource "aws_db_subnet_group" "main" {
14
4
  name = "${local.app_name}-db-subnet-group"
15
5
  subnet_ids = aws_subnet.db_isolated[*].id
@@ -1,15 +1,5 @@
1
- # 1. Isolated Subnets (No Internet Gateway routing)
2
- resource "aws_subnet" "db_isolated" {
3
- count = 2
4
- vpc_id = aws_vpc.main.id
5
- cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index + 10)
6
- availability_zone = data.aws_availability_zones.available.names[count.index]
7
-
8
- tags = {
9
- Name = "${local.app_name}-db-isolated-${count.index}"
10
- }
11
- }
12
-
1
+ # 1. Database Subnet Group (isolated subnets live in network.tf, shared
2
+ # with ElastiCache so every data-plane group stays off public subnets)
13
3
  resource "aws_db_subnet_group" "main" {
14
4
  name = "${local.app_name}-db-subnet-group"
15
5
  subnet_ids = aws_subnet.db_isolated[*].id
@@ -280,7 +280,7 @@ resource "aws_iam_role_policy" "secrets_policy" {
280
280
 
281
281
  # --- Outputs ---
282
282
  output "alb_direct_url" {
283
- description = "Direct Load Balancer URL (Bypasses CloudFront/CDN)"
283
+ description = "Load Balancer origin URL (accepts CloudFront edge traffic only; direct browser access needs a temporary SG rule)"
284
284
  value = "http://${aws_lb.main.dns_name}"
285
285
  }
286
286
 
@@ -47,18 +47,42 @@ resource "aws_route_table_association" "public" {
47
47
  route_table_id = aws_route_table.public.id
48
48
  }
49
49
 
50
+ # Isolated Subnets (No Internet Gateway routing). Shared by every data-plane
51
+ # subnet group (RDS, ElastiCache) so caches never need public subnets. The
52
+ # historical db_isolated address is kept deliberately: renaming would force
53
+ # subnet replacement on existing trees.
54
+ resource "aws_subnet" "db_isolated" {
55
+ count = 2
56
+ vpc_id = aws_vpc.main.id
57
+ cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index + 10)
58
+ availability_zone = data.aws_availability_zones.available.names[count.index]
59
+
60
+ tags = {
61
+ Name = "${local.app_name}-db-isolated-${count.index}"
62
+ }
63
+ }
64
+
50
65
  # --- Security Groups ---
51
- # ALB SG: Allow public internet access on HTTP
66
+
67
+ # Origin-facing CloudFront edge IPs: the only callers the ALB accepts.
68
+ data "aws_ec2_managed_prefix_list" "cloudfront" {
69
+ name = "com.amazonaws.global.cloudfront.origin-facing"
70
+ }
71
+
72
+ # ALB SG: Allow HTTP from CloudFront edges only (no direct internet access)
52
73
  resource "aws_security_group" "alb" {
53
74
  name = "${local.app_name}-alb-sg"
54
- description = "Allow inbound HTTP to ALB"
75
+ description = "Allow inbound HTTP to ALB from CloudFront only"
55
76
  vpc_id = aws_vpc.main.id
56
77
 
57
78
  ingress {
58
- from_port = 80
59
- to_port = 80
60
- protocol = "tcp"
61
- cidr_blocks = ["0.0.0.0/0"]
79
+ from_port = 80
80
+ to_port = 80
81
+ protocol = "tcp"
82
+ # CloudFront-only: the origin speaks plaintext HTTP, so direct browser
83
+ # access would bypass the CDN (and TLS on domained trees). Debugging
84
+ # via the direct URL needs a temporary personal-IP rule.
85
+ prefix_list_ids = [data.aws_ec2_managed_prefix_list.cloudfront.id]
62
86
  }
63
87
 
64
88
  egress {