import fsSync from 'fs'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import color from 'picocolors'; import { COST_ESTIMATE_MARKER, LEGACY_COST_ESTIMATE_MARKER } from './visualizer.js'; import { findResourceBlock, replaceBlock, normalizeBlankLines, realignAssignmentRuns } from './hcl.js'; import { atomicWriteFile } from './atomic-write.js'; import { selectComposeWebService, partitionComposeEnv } from './dockerCompose.js'; import { frameworkDefaultPort, toHclStringArray } from './detector.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Fallback deployment-doc filename used only when README.md and // DEPLOYMENT.md both exist and neither was generated by us. The legacy // name stays a writable candidate so pre-rebrand docs keep updating. export const MANAGED_DOC_FALLBACK = 'GRADA.md'; export const LEGACY_MANAGED_DOC_FALLBACK = 'DEPLOY-STACK.md'; // Greppable, boot-failing Rails master-key seed: Rails cannot // boot on it, so a tree that never pushes the real key fails closed. export const RAILS_MASTER_KEY_PLACEHOLDER = 'REPLACE_ME_PUSH_REAL_RAILS_MASTER_KEY'; // A doc is ours when it carries our cost-estimate marker (current or legacy). export function isManagedDoc(content) { const text = String(content ?? ''); return text.includes(COST_ESTIMATE_MARKER) || text.includes(LEGACY_COST_ESTIMATE_MARKER); } export function buildReadmeNotice(docFile, target = 'ecs') { const what = target === 'static' ? 'Static site infrastructure (S3 + CloudFront) is managed' : target === 'lambda' ? 'AWS Lambda infrastructure is managed' : 'AWS Fargate infrastructure is managed'; return `\n## 🚀 Deployment\n${what} via [grada](./${docFile}).\n`; } // Target file sets: which templates each compute target renders. Adding a // target means adding one entry here — never another target ternary. export function targetFileSets(finalFramework) { const shared = [ { src: 'terraform/oidc.tf', dest: 'terraform/oidc.tf' }, { src: 'terraform/backend.tf', dest: 'terraform/backend.tf' }, { src: 'terraform/variables.tf', dest: 'terraform/variables.tf' }, ]; return { ecs: { files: [ { src: 'terraform/main.tf', dest: 'terraform/main.tf' }, { src: 'terraform/network.tf', dest: 'terraform/network.tf' }, { src: 'terraform/secrets.tf', dest: 'terraform/secrets.tf' }, ...shared, { src: 'terraform/cloudfront.tf', dest: 'terraform/cloudfront.tf' }, { src: `docker/${finalFramework}.Dockerfile`, dest: 'Dockerfile' }, { src: 'github/deploy.yml', dest: '.github/workflows/deploy.yml' }, ], doc: 'README.md', }, lambda: { files: [ { src: 'terraform/main-lambda.tf', dest: 'terraform/main.tf' }, { src: 'terraform/network.tf', dest: 'terraform/network.tf' }, { src: 'terraform/secrets.tf', dest: 'terraform/secrets.tf' }, ...shared, { src: 'terraform/cloudfront-lambda.tf', dest: 'terraform/cloudfront.tf' }, { src: `docker/${finalFramework}.Dockerfile`, dest: 'Dockerfile' }, { src: 'github/deploy-lambda.yml', dest: '.github/workflows/deploy.yml' }, ], doc: 'README.md', }, // Zero-compute: private S3 + CloudFront + OAC. No VPC, no secrets, // no Dockerfile — deploys sync the build output instead of images. static: { files: [ { src: 'terraform/static/main.tf', dest: 'terraform/main.tf' }, ...shared, { src: 'github/deploy-static.yml', dest: '.github/workflows/deploy.yml' }, ], doc: 'README-static.md', }, }; } // Picks the file that should receive the rendered deployment doc without ever // overwriting user-owned content. Returns null when every candidate exists // and none is managed (caller then skips doc generation with a warning). export function resolveDocDest(targetDir) { const inspect = (name) => { const filePath = path.join(targetDir, name); if (!fsSync.existsSync(filePath)) return { exists: false, managed: false }; return { exists: true, managed: isManagedDoc(fsSync.readFileSync(filePath, 'utf-8')) }; }; const readme = inspect('README.md'); if (!readme.exists || readme.managed) return 'README.md'; const deploy = inspect('DEPLOYMENT.md'); if (!deploy.exists || deploy.managed) return 'DEPLOYMENT.md'; const fallback = inspect(MANAGED_DOC_FALLBACK); if (!fallback.exists || fallback.managed) return MANAGED_DOC_FALLBACK; const legacy = inspect(LEGACY_MANAGED_DOC_FALLBACK); if (!legacy.exists || legacy.managed) return LEGACY_MANAGED_DOC_FALLBACK; return null; } export const LAMBDA_ADAPTER_IMAGE = 'public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1'; // Injects the AWS Lambda Web Adapter layer into a rendered Dockerfile so // standard HTTP servers handle API Gateway events with zero code changes. // Inserted right after the LAST `FROM` (the final stage, still running as // root) so the copy into /opt/extensions never hits a later `USER` switch. // `ENV PORT` lines already present in the runner stage are not duplicated. export function injectLambdaAdapter(dockerContent, port) { const content = String(dockerContent ?? ''); const lines = content.split('\n'); let lastFromIdx = -1; for (let i = 0; i < lines.length; i++) { if (/^\s*FROM\s+/i.test(lines[i])) lastFromIdx = i; } if (lastFromIdx === -1) return content; // Builder-stage ENV lines do not propagate to the runner, so duplicate // detection only inspects the post-last-FROM segment. const runnerStage = lines.slice(lastFromIdx + 1).join('\n'); const hasPort = /^\s*ENV\s+PORT[=\s]/im.test(runnerStage); const hasLwaPort = /^\s*ENV\s+AWS_LWA_PORT[=\s]/im.test(runnerStage); const injected = [ '', '# AWS Lambda Web Adapter (grada --target lambda)', `COPY --from=${LAMBDA_ADAPTER_IMAGE} /lambda-adapter /opt/extensions/lambda-adapter`, ...(hasLwaPort ? [] : [`ENV AWS_LWA_PORT=${port}`]), ...(hasPort ? [] : [`ENV PORT=${port}`]), ]; lines.splice(lastFromIdx + 1, 0, ...injected); return lines.join('\n'); } // Converts a Lambda-target database.tf from AWS-managed master passwords to // an explicit Terraform-managed password: VPC-attached functions cannot reach // Secrets Manager without a paid VPC endpoint, so the password flows into the // function's DB_PASSWORD environment variable instead. Removes the now-invalid // master-secret IAM policy (indexing an empty `master_user_secret` tuple fails // planning) and appends the `random_password` resource. No-op for ECS content // or content that was already converted. export function convertDatabaseTfForLambda(databaseTfContent) { let content = String(databaseTfContent ?? ''); if (!content.includes('manage_master_user_password = true')) return content; // aws_rds_cluster (Aurora) names the argument `master_password` while // aws_db_instance (RDS Postgres/MySQL) names it `password`. const passwordAttr = content.includes('resource "aws_rds_cluster"') ? 'master_password' : 'password'; content = content.replace( ' # AWS automatically creates and manages the secret in Secrets Manager!\n manage_master_user_password = true', ` # Lambda targets use an explicit Terraform-managed password (see\n # random_password.db_password below) so the value can flow into the\n # function's DB_PASSWORD environment variable without a Secrets Manager\n # VPC endpoint.\n ${passwordAttr} = random_password.db_password.result` ); content = content.replace('# 4. IAM Permission for RDS Master Password Secret\n', ''); const resource = findResourceBlock(content, 'aws_iam_role_policy', 'rds_secret_access'); if (resource) { const lineStart = content.lastIndexOf('\n', resource.headerIdx - 1) + 1; content = replaceBlock(content, { startIdx: lineStart, openIdx: resource.openIdx, closeIdx: resource.closeIdx, }, '').trimEnd(); content += '\n'; } // RDS passwords disallow / " @ and spaces; the override excludes them. if (!content.endsWith('\n')) content += '\n'; content += ` resource "random_password" "db_password" { length = 24 special = true override_special = "!#$%&*()-_=+[]{}<>:?" } `; return content.replace(/\n{3,}/g, '\n\n'); } // Shared engine reference table for relational databases, used by both // init-time generation and post-init `add db:*` so the two can never // diverge on template choice, resource addresses, ports, or attribute // names. Unknown engines fall back to postgres (mirrors init). export function resolveDbEngineRefs(engine) { const normalized = engine === 'mysql' || engine === 'aurora-postgresql' ? engine : 'postgres'; const isCluster = normalized === 'aurora-postgresql'; return { engine: normalized, isCluster, dbRef: isCluster ? 'aws_rds_cluster.postgres' : 'aws_db_instance.postgres', dbHostAttr: isCluster ? 'endpoint' : 'address', dbNameAttr: isCluster ? 'database_name' : 'db_name', dbPort: normalized === 'mysql' ? '3306' : '5432', template: normalized === 'postgres' ? 'terraform/database.tf' : `terraform/database-${normalized}.tf`, }; } // Container/Lambda environment + secret entries for `engine`. Env // entries use inject*EnvVars value encoding (a lone "${...}" renders // as a bare HCL reference, anything else stays quoted); secrets carry // literal HCL `valueFrom` fragments. Lambda carries the DB user and // password as plain variables (no Secrets Manager VPC endpoint). export function buildDbEntries(engine, target = 'ecs') { const refs = resolveDbEngineRefs(engine); const env = [ { name: 'DB_HOST', value: `\${${refs.dbRef}.${refs.dbHostAttr}}` }, { name: 'DB_PORT', value: refs.dbPort }, { name: 'DB_NAME', value: `\${${refs.dbRef}.${refs.dbNameAttr}}` }, ]; if (refs.engine !== 'postgres') env.push({ name: 'DB_ENGINE', value: refs.engine }); if (target === 'lambda') { env.push({ name: 'DB_USER', value: 'dbadmin' }); env.push({ name: 'DB_PASSWORD', value: '${random_password.db_password.result}' }); return { env, secrets: [] }; } return { env, secrets: [ { name: 'DB_USER', valueFrom: `\${${refs.dbRef}.master_user_secret[0].secret_arn}:username::` }, { name: 'DB_PASSWORD', valueFrom: `\${${refs.dbRef}.master_user_secret[0].secret_arn}:password::` }, ], }; } // Whether a target's rendered backend.tf needs the `random` provider: // always on ECS (the ALB origin secret), on Lambda only with a database // (`random_password.db_password`), never on static. export function backendNeedsRandomProvider(target, needsDatabase = false) { if (target === 'static') return false; if (target === 'lambda') return needsDatabase === true; return true; } // Adds the `random` provider to a rendered backend.tf (see // backendNeedsRandomProvider for which trees need it). No-op when present. // Resolves the compose service to merge for a render config. init // pre-selects through DOCKER_COMPOSE_WEB (a service name, or null when // init already warned and declined the merge); direct callers run the // full selector with its warnings here. Returns the service or null. export function resolveComposeWebService(config) { const services = config.DOCKER_COMPOSE; if (config.DOCKER_COMPOSE_WEB === null) return null; if (typeof config.DOCKER_COMPOSE_WEB === 'string') { const named = services.find((s) => s && s.name === config.DOCKER_COMPOSE_WEB); if (named) return named; } const { service, skipped, datastoreImage } = selectComposeWebService(services, { frameworkPort: frameworkDefaultPort(config.finalFramework), }); if (!service) { console.log(color.yellow(`⚠️ No app service detected in your compose file (${skipped === 'all-datastores' ? 'every service looks like a datastore' : 'no services found'}) — skipping the compose merge. Give your app service a \`build:\` key to merge it.`)); return null; } if (datastoreImage) { console.log(color.yellow(`⚠️ Compose service "${service.name}" looks like a datastore but was selected as the web service — verify the merged port and env vars before applying.`)); } return service; } // One loud line per filtered block: names what was withheld and where // the values belong instead. export function warnComposeSecretsFiltered(skipped) { console.log(color.yellow(`⚠️ Skipped ${skipped.length} secret-like compose env var(s) (${skipped.join(', ')}): values are never inlined into generated files — use \`grada secrets push\` instead.`)); } export function addRandomProvider(backendTfContent) { const content = String(backendTfContent ?? ''); if (/source\s*=\s*"hashicorp\/random"/.test(content)) return content; const tlsBlock = ' tls = {\n source = "hashicorp/tls"\n version = "~> 4.0"\n }'; if (!content.includes(tlsBlock)) return content; return content.replace( tlsBlock, `${tlsBlock}\n random = {\n source = "hashicorp/random"\n version = "~> 3.0"\n }` ); } export async function generateTemplates(targetDir, config) { // Collision suffix defaults to empty (pre-suffix callers and fixtures // render byte-identical names); init always passes the real value. if (config.RESOURCE_SUFFIX === undefined || config.RESOURCE_SUFFIX === null) config.RESOURCE_SUFFIX = ''; const target = config.TARGET === 'lambda' ? 'lambda' : config.TARGET === 'static' ? 'static' : 'ecs'; const isLambda = target === 'lambda'; const isStatic = target === 'static'; // 1. Create directories await fs.mkdir(targetDir, { recursive: true }); await fs.mkdir(path.join(targetDir, 'terraform'), { recursive: true }); await fs.mkdir(path.join(targetDir, '.github', 'workflows'), { recursive: true }); // 2. Define paths (never overwrite user-owned docs — see resolveDocDest) const templatesDir = path.join(__dirname, '../../templates'); const readmeDest = resolveDocDest(targetDir); const targetSet = targetFileSets(config.finalFramework)[target]; const filesToProcess = [...targetSet.files]; if (readmeDest) { filesToProcess.push({ src: targetSet.doc, dest: readmeDest }); } else { console.log(color.yellow('⚠️ README.md, DEPLOYMENT.md, GRADA.md, and DEPLOY-STACK.md all exist and none was generated by grada. Skipping deployment-doc generation to protect your files.')); } // 2.1 Point user-owned READMEs at the generated doc (append once only). const readmePath = path.join(targetDir, 'README.md'); if (readmeDest && readmeDest !== 'README.md' && fsSync.existsSync(readmePath)) { const notice = buildReadmeNotice(readmeDest, target); const current = fsSync.readFileSync(readmePath, 'utf-8'); if (!current.includes(notice.trim())) { fsSync.appendFileSync(readmePath, notice); } } // 2.1 Add Ephemeral PR workflows only if opted in (teardown.yml is // Terraform-only, so both container targets share it). Static targets // skip previews: the preview workflow builds container images. if (config.ENABLE_PR_PREVIEWS) { if (isStatic) { console.log(color.yellow('⚠️ Skipping ephemeral PR previews: the preview workflow builds container images, which static targets don\'t produce.')); } else { filesToProcess.push({ src: isLambda ? 'github/preview-lambda.yml' : 'github/preview.yml', dest: '.github/workflows/preview.yml' }); filesToProcess.push({ src: 'github/teardown.yml', dest: '.github/workflows/teardown.yml' }); } } // 3. Configure Compute Commands & Environment Variables let secretsArray = []; // Exact container env + static-secret names for the managed_env_names // collision-guard list (union over rendered task definitions). Each // section below appends what IT renders, so the list tracks the // environment by construction instead of parallel knowledge. const managedEnvNames = ['PORT']; // 3.1. Format the ECS Task Command (Heroku Procfile Support) // If a Procfile exists and has a 'web' process, override the Docker CMD if (config.PROCFILE && config.PROCFILE.web) { // e.g., ["gunicorn", "myproject.wsgi"] -> JSON string for Terraform config.TASK_COMMAND = `command = ${toHclStringArray(config.PROCFILE.web)}`; } else { // Fallback to the default Dockerfile CMD config.TASK_COMMAND = ''; } // Lambda equivalent: a Procfile `web:` command overrides the image CMD // via `image_config`. Omitted when empty (Dockerfile CMD wins). if (isLambda && Array.isArray(config.PROCFILE?.web) && config.PROCFILE.web.length > 0) { const webCommand = config.PROCFILE.web.map((part) => String(part)).join(' '); config.LAMBDA_IMAGE_CONFIG = ` image_config {\n command = ${toHclStringArray(['sh', '-c', webCommand])}\n }\n`; } else { config.LAMBDA_IMAGE_CONFIG = ''; } // A caller-provided WORKER_COMMAND (interactive init worker prompt, // possibly customized from the Procfile default) wins verbatim; // otherwise the Procfile worker process drives generation as before. // Lambda and static targets never provision the ECS worker service. const hasComputeWorkers = !isLambda && !isStatic; if (hasComputeWorkers && typeof config.WORKER_COMMAND === 'string' && config.WORKER_COMMAND.trim() !== '') { filesToProcess.push({ src: 'terraform/worker.tf', dest: 'terraform/worker.tf' }); } else if (hasComputeWorkers && config.PROCFILE && config.PROCFILE.worker) { config.WORKER_COMMAND = `command = ${toHclStringArray(config.PROCFILE.worker)}`; // Dynamically add worker.tf to the generation list filesToProcess.push({ src: 'terraform/worker.tf', dest: 'terraform/worker.tf' }); } else { config.WORKER_COMMAND = ''; } // Worker-only static env joins the union only when worker.tf renders — // otherwise a pushed NODE_ENV would trip the app precondition though // nothing would collide. if (config.WORKER_COMMAND !== '') managedEnvNames.push('NODE_ENV'); // 3.2. Inject Managed Database Variables. Static targets have no // compute to connect, so a database is never generated for them (init // warns and drops the request; this guard covers direct API callers). if (config.NEEDS_DATABASE && !isStatic) { const dbRefs = resolveDbEngineRefs(config.DB_ENGINE); const dbEngine = dbRefs.engine; filesToProcess.push({ src: dbRefs.template, dest: 'terraform/database.tf' }); const dbRef = dbRefs.dbRef; const dbHostAttr = dbRefs.dbHostAttr; const dbNameAttr = dbRefs.dbNameAttr; const dbPort = dbRefs.dbPort; if (isLambda) { // Lambda `environment.variables` map shape. The password flows as // a plain variable (see convertDatabaseTfForLambda) because // VPC-attached functions cannot reach Secrets Manager without a // paid VPC endpoint. // Own alignment group (leading blank line separates it from the // static PORT entries above): keys padded to DB_PASSWORD, the // longest key this emitter ever prints. config.DB_ENV_VARS = `\n DB_HOST = ${dbRef}.${dbHostAttr}\n` + ` DB_PORT = "${dbPort}"\n` + ` DB_NAME = ${dbRef}.${dbNameAttr}\n` + ` DB_USER = "dbadmin"\n` + ` DB_PASSWORD = random_password.db_password.result\n` + (dbEngine === 'postgres' ? '' : ` DB_ENGINE = "${dbEngine}"\n`); } else { config.DB_ENV_VARS = ` { "name" : "DB_HOST", "value" : ${dbRef}.${dbHostAttr} }, { "name" : "DB_PORT", "value" : "${dbPort}" }, { "name" : "DB_NAME", "value" : ${dbRef}.${dbNameAttr} }${dbEngine === 'postgres' ? '' : `,\n { "name" : "DB_ENGINE", "value" : "${dbEngine}" }`}`; secretsArray.push(`{ "name" : "DB_USER", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:username::" }`); secretsArray.push(`{ "name" : "DB_PASSWORD", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:password::" }`); managedEnvNames.push('DB_HOST', 'DB_PORT', 'DB_NAME'); if (dbEngine !== 'postgres') managedEnvNames.push('DB_ENGINE'); managedEnvNames.push('DB_USER', 'DB_PASSWORD'); } // VPC-attached functions reach RDS/ElastiCache over the VPC subnets; // non-database functions stay outside the VPC with direct internet. config.LAMBDA_VPC_CONFIG = isLambda ? ` vpc_config {\n subnet_ids = aws_subnet.public[*].id\n security_group_ids = [aws_security_group.ecs_tasks.id]\n }\n` : ''; } else { config.DB_ENV_VARS = ''; config.LAMBDA_VPC_CONFIG = ''; } // 3.3. Docker Compose Overrides & Sidecars let composeWebEnvVars = []; let extraContainersHCL = ""; // Names withheld by the secret filter, collected for the caller's // telemetry (the generator itself stays telemetry-free). config.COMPOSE_SECRETS_FILTERED = []; if (config.DOCKER_COMPOSE && config.DOCKER_COMPOSE.length > 0) { // Identify the main web service: build-key first, then the // framework default port, then the first non-datastore service. // init pre-selects through DOCKER_COMPOSE_WEB (null = skip); // direct callers run the full selector with its warnings here. const webService = resolveComposeWebService(config); if (webService) { // Extract Web Env Vars (secret-like entries are withheld, never inlined) const { safe: webEnv, skipped: webSkipped } = partitionComposeEnv(webService.environment); if (webSkipped.length > 0) { warnComposeSecretsFiltered(webSkipped); config.COMPOSE_SECRETS_FILTERED.push(...webSkipped); } for (const [key, val] of Object.entries(webEnv)) { if (isLambda) { composeWebEnvVars.push(` ${key} = "${String(val).replace(/"/g, '\\"')}"`); } else { composeWebEnvVars.push(`{ "name" : "${key}", "value" : "${String(val).replace(/"/g, '\\"')}" }`); managedEnvNames.push(key); } } // Extract Web Command Override (only if Procfile hasn't already set it) if (webService.command && !config.TASK_COMMAND && !isLambda) { config.TASK_COMMAND = `command = ${toHclStringArray(typeof webService.command === 'string' ? webService.command.split(' ') : webService.command)}`; } if (isLambda && webService.command && config.LAMBDA_IMAGE_CONFIG === '') { const composeCommand = typeof webService.command === 'string' ? webService.command : webService.command.join(' '); config.LAMBDA_IMAGE_CONFIG = ` image_config {\n command = ${toHclStringArray(['sh', '-c', composeCommand])}\n }\n`; } // Process Sidecar Containers (e.g., Redis, Memcached) const sidecars = config.DOCKER_COMPOSE.filter(s => s.name !== webService.name); if (isLambda && sidecars.length > 0) { console.log(color.yellow(`⚠️ Skipping ${sidecars.length} Docker Compose sidecar(s) (${sidecars.map((s) => s.name).join(', ')}): Lambda targets run a single container per function.`)); } if (!isLambda && sidecars.length > 0) { extraContainersHCL = sidecars.map(service => { const { safe: sidecarSafe, skipped: sidecarSkipped } = partitionComposeEnv(service.environment); if (sidecarSkipped.length > 0) { warnComposeSecretsFiltered(sidecarSkipped); config.COMPOSE_SECRETS_FILTERED.push(...sidecarSkipped); } const sidecarEnv = Object.entries(sidecarSafe) .map(([k, v]) => `{ "name" : "${k}", "value" : "${String(v).replace(/"/g, '\\"')}" }`) .join(',\n '); const sidecarCmd = service.command ? `\n command = ${toHclStringArray(typeof service.command === 'string' ? service.command.split(' ') : service.command)}` : ''; return `, { name = "${service.name}" image = "${service.image || 'alpine:latest'}" essential = false environment = [ ${sidecarEnv} ]${sidecarCmd} logConfiguration = { logDriver = "awslogs" options = { "awslogs-group" = aws_cloudwatch_log_group.app_logs.name "awslogs-region" = "${config.REGION}" "awslogs-stream-prefix" = "ecs-${service.name}" } } }`; }).join(''); } } } config.COMPOSE_WEB_ENV_VARS = composeWebEnvVars.length === 0 ? '' : isLambda // Own alignment group (leading blank line) with keys padded // to the longest compose key in this render. ? `\n${realignAssignmentRuns(composeWebEnvVars.join('\n'))}\n` : `${composeWebEnvVars.join(',\n ')},`; config.EXTRA_CONTAINERS = isLambda ? '' : extraContainersHCL; // 4. Configure AWS Secrets Manager Integration // Build the initial HCL map for AWS Secrets Manager let initialSecretMap = `{\n EXAMPLE_API_KEY = "replace_me_in_aws_console"`; // 4.1. Seed a placeholder for the Rails master key: the // live key must never render into committed .tf (or linger in // state), and no constant dummy may boot prod. The placeholder is // greppable and boot-failing; the loud instruction tells the // operator to push the real key before going live. if (config.finalFramework === 'rails') { secretsArray.push(`{ "name" : "RAILS_MASTER_KEY", "valueFrom" : "\${local.secret_arn}:RAILS_MASTER_KEY::" }`); if (!isLambda) managedEnvNames.push('RAILS_MASTER_KEY'); // Inject the string literal directly, avoiding Terraform variables entirely initialSecretMap += `,\n RAILS_MASTER_KEY = "${RAILS_MASTER_KEY_PLACEHOLDER}"`; if (!isLambda) { console.log(color.yellow(`⚠️ Rails app detected: terraform/secrets.tf seeds RAILS_MASTER_KEY with the placeholder "${RAILS_MASTER_KEY_PLACEHOLDER}" — push the real key before going live: npx grada-run secrets push .env (with RAILS_MASTER_KEY set from config/master.key).`)); } } initialSecretMap += `\n }`; // Lambda functions have no ECS `secrets` block: credentials flow via // environment variables (DB_*) or runtime Secrets Manager reads // (APP_SECRETS_ARN), so the task-level secret mappings stay empty. if (isLambda && config.finalFramework === 'rails') { console.log(color.yellow('⚠️ RAILS_MASTER_KEY is not auto-injected on Lambda targets: set it as a function environment variable after provisioning.')); } config.TASK_SECRETS = isLambda ? '' : secretsArray.join(',\n '); // Collision-guard list for the task-definition precondition. Unused on // Lambda/static targets (their templates carry no task definitions). config.MANAGED_ENV_NAMES = `[${[...new Set(managedEnvNames)].sort().map((name) => JSON.stringify(name)).join(', ')}]`; config.INITIAL_SECRET_MAP = initialSecretMap; config.SAFE_ALB_NAME = config.PROJECT_NAME.length > 27 ? config.PROJECT_NAME.substring(0, 27).replace(/-$/, '') // Remove trailing hyphens : config.PROJECT_NAME; // 4.5. Translate Vercel Rules to AWS ALB Listener Rules let vercelTerraformRules = ''; if (config.VERCEL_RULES && config.VERCEL_RULES.redirects) { config.VERCEL_RULES.redirects.forEach((rule, index) => { // Vercel uses 'permanent: true' for 301, false for 302 const statusCode = rule.permanent === false ? "HTTP_302" : "HTTP_301"; // Map Vercel's source path to AWS ALB Path Pattern let sourcePath = rule.source; // Vercel sometimes uses regex syntax like '/blog/(.*)'. ALB uses '/blog/*' sourcePath = sourcePath.replace(/\(\.\*\)/g, '*'); vercelTerraformRules += ` # Auto-generated from vercel.json redirect resource "aws_lb_listener_rule" "vercel_redirect_${index}" { listener_arn = aws_lb_listener.http.arn priority = ${100 + index} # Start at 100 to avoid conflicts action { type = "redirect" redirect { status_code = "${statusCode}" path = "${rule.destination}" } } condition { path_pattern { values = ["${sourcePath}"] } } } `; }); } // Assign the compiled HCL to the config object so the template engine can inject it // (Lambda targets have no ALB listener rules, so the routing stays empty). config.VERCEL_EDGE_ROUTING = isLambda ? '' : vercelTerraformRules; // 5. Process standard files for (const file of filesToProcess) { let content = await fs.readFile(path.join(templatesDir, file.src), 'utf-8'); // Inject variables. Replacement FUNCTION (not string): `$&`/`$'`/ // `$$` in values (Procfile commands, compose env vars) must land // byte-identical, not interpolate match text. for (const [key, value] of Object.entries(config)) { const literal = String(value ?? ''); content = content.replace(new RegExp(`{{${key}}}`, 'g'), () => literal); } if (isLambda && file.dest === 'Dockerfile') { content = injectLambdaAdapter(content, config.PORT); } if (isLambda && file.dest === 'terraform/database.tf') { content = convertDatabaseTfForLambda(content); } if (file.dest === 'terraform/backend.tf' && backendNeedsRandomProvider(target, config.NEEDS_DATABASE)) { content = addRandomProvider(content); } if (file.dest === 'terraform/worker.tf' && !config.NEEDS_DATABASE) { // {{DB_ENV_VARS}} expanded to empty, leaving a dangling comma + // blank line after NODE_ENV (main.tf shares the value shape, so // the cleanup stays worker-specific). content = content.replace( /(\{ "name" : "NODE_ENV", "value" : "production" \}),\s*\n\s*\n(\s*\])/, '$1\n$2' ); } // Empty placeholder expansions leave indented blank lines that // `terraform fmt` flags — normalize them on every rendered file. content = normalizeBlankLines(content); await atomicWriteFile(path.join(targetDir, file.dest), content); } // 6. Create empty secrets file (preserve previously pushed keys on re-init) const secretKeysPath = path.join(targetDir, 'terraform', 'secret_keys.json'); if (!fsSync.existsSync(secretKeysPath)) { await atomicWriteFile(secretKeysPath, "[]"); } // 7. Handle .gitignore dynamically based on framework const targetGitignore = path.join(targetDir, '.gitignore'); if (!fsSync.existsSync(targetGitignore)) { await atomicWriteFile(targetGitignore, getGitignoreContent(config.finalFramework)); } else { const existingGitignore = await fs.readFile(targetGitignore, 'utf-8'); if (!existingGitignore.includes('terraform/.terraform/')) { const appendIgnore = '\n# Added by grada (Terraform)\nterraform/.terraform/\nterraform/*.tfstate\nterraform/*.tfstate.backup\nterraform/.terraform.lock.hcl\n.env\n'; await fs.appendFile(targetGitignore, appendIgnore); } } // 8. Create .dockerignore to keep images lean and secure (static // targets build no images, so there is nothing to ignore). if (!isStatic) { const dockerignorePath = path.join(targetDir, '.dockerignore'); const appendDockerIgnore = '\n# Infrastructure (grada)\nterraform/\n**/.terraform/\n**/.terraform.*\n**/*.tfstate*\n.env\n'; if (!fsSync.existsSync(dockerignorePath)) { const dockerignoreContent = ` .git/ .github/ README.md node_modules/ npm-debug.log __pycache__/ *.pyc .DS_Store `.trim() + appendDockerIgnore; await atomicWriteFile(dockerignorePath, dockerignoreContent); } else { const existingDockerignore = await fs.readFile(dockerignorePath, 'utf-8'); if (!existingDockerignore.includes('terraform/')) { await fs.appendFile(dockerignorePath, appendDockerIgnore); } } } function getGitignoreContent(framework) { const baseIgnore = ` # Infrastructure (grada) terraform/.terraform/ terraform/*.tfstate terraform/*.tfstate.backup terraform/.terraform.lock.hcl # NOTE: terraform/secret_keys.json must stay committed (key names only, no values) — Terraform/CI reads it. terraform/*.auto.tfvars .env # OS .DS_Store Thumbs.db `; const presets = { node: '\n# Node.js\nnode_modules/\nnpm-debug.log\nyarn-error.log\n', nestjs: '\n# NestJS\nnode_modules/\ndist/\nnpm-debug.log\n', nextjs: '\n# Next.js\nnode_modules/\n.next/\nout/\nbuild/\nnext-env.d.ts\n', nuxt: '\n# Nuxt 3\nnode_modules/\n.nuxt/\n.output/\ndist/\n', python: '\n# Python\n__pycache__/\n*.py[cod]\n*$py.class\nvenv/\nenv/\n.venv/\n.pytest_cache/\n', django: '\n# Django\n*.log\n*.pot\n*.pyc\n__pycache__/\ndb.sqlite3\nmedia/\n', go: '\n# Go\n/bin/\n/pkg/\n/obj/\n*.exe\n*.exe~*\n*.dll\n*.so\n*.dylib\n', rails: '\n# Rails\n/*.log\n/tmp/\n/log/\n/public/system/\n/public/assets/\n/vendor/bundle/\n', static: '\n# Static Sites\nnode_modules/\ndist/\nbuild/\nout/\n.output/\n.cache/\npublic/\n' }; const frameworkIgnore = presets[framework] || ''; return (baseIgnore + frameworkIgnore).trim(); } // 9. Framework-specific cleanup // Disable default workflows that crash in isolated CI environments if (config.finalFramework === 'rails') { const railsCiPath = path.join(targetDir, '.github', 'workflows', 'ci.yml'); const dependabotPath = path.join(targetDir, '.github', 'dependabot.yml'); if (config.DISABLE_DEFAULT_CI) { if (fsSync.existsSync(railsCiPath)) { fsSync.renameSync(railsCiPath, `${railsCiPath}.bak`); console.log(' ✅ Safely disabled default Rails ci.yml (renamed to .bak).'); } if (fsSync.existsSync(dependabotPath)) { fsSync.renameSync(dependabotPath, `${dependabotPath}.bak`); console.log(' ✅ Safely disabled default dependabot.yml (renamed to .bak).'); } } else if (fsSync.existsSync(railsCiPath) || fsSync.existsSync(dependabotPath)) { console.log(' ⚠️ You chose to keep your existing GitHub Actions. Please note that default tests may fail until you configure a database service in your CI runner.'); } } }