@fishawack/lab-env 5.7.0-beta.1 → 5.7.0-beta.11

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/_Ai/lab-env-@.md +3 -3
  3. package/_Scripts/post-release.sh +1 -1
  4. package/_Test/boilerplate-adonis.js +1 -1
  5. package/_Test/boilerplate-craftcms.js +1 -1
  6. package/_Test/boilerplate-drupal.js +1 -1
  7. package/_Test/boilerplate-laravel.js +1 -1
  8. package/_Test/boilerplate-python.js +1 -1
  9. package/_Test/boilerplate-wordpress.js +1 -1
  10. package/_Test/boilerplate.js +1 -1
  11. package/_Test/provision.js +4 -9
  12. package/_Test/prune.js +8 -5
  13. package/adonis/0/docker-compose.yml +1 -1
  14. package/bitbucket-pipelines.yml +2 -2
  15. package/cli.js +1 -0
  16. package/commands/create/cmds/dekey.js +13 -9
  17. package/commands/create/cmds/deprovision.js +36 -0
  18. package/commands/create/cmds/diagnose.js +10 -0
  19. package/commands/create/cmds/key.js +74 -41
  20. package/commands/create/cmds/provision.js +573 -69
  21. package/commands/create/cmds/rekey.js +283 -0
  22. package/commands/create/cmds/sync-secrets.js +2 -1
  23. package/commands/create/libs/aws-cloudfront-response.js +11 -0
  24. package/commands/create/libs/output-credentials.js +59 -0
  25. package/commands/create/libs/parallel-runner.js +296 -0
  26. package/commands/create/libs/resolve-operator.js +59 -0
  27. package/commands/create/libs/utilities.js +75 -8
  28. package/commands/create/libs/vars.js +124 -143
  29. package/commands/create/services/aws/acm.js +61 -0
  30. package/commands/create/services/aws/cloudfront.js +51 -45
  31. package/commands/create/services/aws/ec2.js +675 -48
  32. package/commands/create/services/aws/elasticache.js +159 -0
  33. package/commands/create/services/aws/elasticbeanstalk.js +155 -57
  34. package/commands/create/services/aws/iam.js +420 -86
  35. package/commands/create/services/aws/index.js +1401 -260
  36. package/commands/create/services/aws/opensearch.js +155 -0
  37. package/commands/create/services/aws/rds.js +98 -35
  38. package/commands/create/services/aws/s3.js +52 -31
  39. package/commands/create/services/aws/secretsmanager.js +21 -12
  40. package/commands/create/services/aws/ses.js +203 -0
  41. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/cron.config +45 -0
  42. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/queue-worker.config +29 -0
  43. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/software.config +12 -0
  44. package/commands/create/templates/elasticbeanstalk/.ebextensions/misc/setvars.config +2 -16
  45. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/restart_queue.sh +4 -0
  46. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/rewrite-flush.sh +1 -1
  47. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/prebuild/setvars.sh +19 -0
  48. package/commands/create/templates/elasticbeanstalk/.platform/hooks/postdeploy/restart_queue.sh +4 -0
  49. package/commands/create/templates/elasticbeanstalk/.platform/hooks/prebuild/setvars.sh +19 -0
  50. package/commands/scan.js +1 -1
  51. package/core/1/CHANGELOG.md +41 -0
  52. package/core/1/Dockerfile +3 -3
  53. package/core/1/bitbucket-pipelines.yml +5 -5
  54. package/core/1/package.json +1 -1
  55. package/drupal/9/docker-compose.yml +1 -2
  56. package/globals.js +4 -0
  57. package/laravel/10/docker-compose.yml +1 -1
  58. package/laravel/9/docker-compose.yml +1 -1
  59. package/package.json +7 -2
  60. package/wordpress/1/docker-compose.yml +1 -2
@@ -1,5 +1,3 @@
1
- const md5 = require("apache-md5");
2
- const fs = require("fs-extra");
3
1
  const generator = require("generate-password");
4
2
  const { S3Client, ListBucketsCommand } = require("@aws-sdk/client-s3");
5
3
  const {
@@ -10,9 +8,17 @@ const {
10
8
  SecretsManagerClient,
11
9
  DescribeSecretCommand,
12
10
  } = require("@aws-sdk/client-secrets-manager");
11
+ const {
12
+ OpenSearchClient,
13
+ DescribeDomainCommand,
14
+ } = require("@aws-sdk/client-opensearch");
15
+ const {
16
+ ElastiCacheClient,
17
+ DescribeReplicationGroupsCommand,
18
+ } = require("@aws-sdk/client-elasticache");
13
19
 
14
- const { nameSafe, Spinner } = require("../../libs/utilities.js");
15
- const { eb } = require("../../libs/vars.js");
20
+ const { nameSafe, Spinner, pollAll } = require("../../libs/utilities.js");
21
+ const { eb, secretGroups } = require("../../libs/vars.js");
16
22
 
17
23
  module.exports.s3 = require("./s3.js");
18
24
  module.exports.cloudfront = require("./cloudfront.js");
@@ -20,7 +26,11 @@ module.exports.iam = require("./iam.js");
20
26
  module.exports.elasticbeanstalk = require("./elasticbeanstalk.js");
21
27
  module.exports.ec2 = require("./ec2.js");
22
28
  module.exports.rds = require("./rds.js");
29
+ module.exports.opensearch = require("./opensearch.js");
30
+ module.exports.elasticache = require("./elasticache.js");
23
31
  module.exports.secretsmanager = require("./secretsmanager.js");
32
+ module.exports.acm = require("./acm.js");
33
+ module.exports.ses = require("./ses.js");
24
34
 
25
35
  module.exports.slug = (repo, client, branch, service = "s3") =>
26
36
  nameSafe(`${branch}-${repo}-${client}`, service);
@@ -29,13 +39,27 @@ module.exports.fullstackPreflight = async (
29
39
  name,
30
40
  repo,
31
41
  branch,
32
- { storage = false, database = false } = {},
42
+ {
43
+ storage = false,
44
+ database = false,
45
+ opensearch = false,
46
+ cache = false,
47
+ } = {},
33
48
  ) => {
34
- const conflicts = [];
35
49
  const existing = {
50
+ environment: false,
36
51
  storage: false,
37
52
  database: false,
38
- secrets: { app: null, storage: null, database: null },
53
+ opensearch: false,
54
+ cache: false,
55
+ secrets: {
56
+ app: null,
57
+ storage: null,
58
+ database: null,
59
+ opensearch: null,
60
+ cache: null,
61
+ mail: null,
62
+ },
39
63
  };
40
64
 
41
65
  const spinner = new Spinner("Running pre-flight checks", true);
@@ -50,9 +74,7 @@ module.exports.fullstackPreflight = async (
50
74
  (e) => e.Status !== "Terminated",
51
75
  );
52
76
  if (active.length) {
53
- conflicts.push(
54
- `Elastic Beanstalk environment "${name}" already exists (status: ${active[0].Status})`,
55
- );
77
+ existing.environment = active[0];
56
78
  }
57
79
  } catch {
58
80
  /* does not exist */
@@ -105,8 +127,56 @@ module.exports.fullstackPreflight = async (
105
127
  }
106
128
  }
107
129
 
130
+ // Check OpenSearch
131
+ if (opensearch) {
132
+ const osSlug = module.exports.slug(
133
+ repo,
134
+ process.env.AWS_PROFILE,
135
+ branch,
136
+ "os",
137
+ );
138
+
139
+ spinner.ora.text = "Checking for existing OpenSearch domain";
140
+ try {
141
+ const { DomainStatus } = await new OpenSearchClient({}).send(
142
+ new DescribeDomainCommand({ DomainName: osSlug }),
143
+ );
144
+ if (DomainStatus && !DomainStatus.Deleted) {
145
+ existing.opensearch = true;
146
+ }
147
+ } catch {
148
+ /* does not exist */
149
+ }
150
+ }
151
+
152
+ // Check ElastiCache
153
+ if (cache) {
154
+ const cacheSlug = module.exports.slug(
155
+ repo,
156
+ process.env.AWS_PROFILE,
157
+ branch,
158
+ "cache",
159
+ );
160
+
161
+ spinner.ora.text = "Checking for existing ElastiCache cluster";
162
+ try {
163
+ const { ReplicationGroups } = await new ElastiCacheClient(
164
+ {},
165
+ ).send(
166
+ new DescribeReplicationGroupsCommand({
167
+ ReplicationGroupId: cacheSlug,
168
+ }),
169
+ );
170
+ const group = ReplicationGroups[0];
171
+ if (group && group.Status !== "deleting") {
172
+ existing.cache = true;
173
+ }
174
+ } catch {
175
+ /* does not exist */
176
+ }
177
+ }
178
+
108
179
  // Check for existing secrets
109
- const secretGroups = ["app", "storage", "database"];
110
180
  for (const group of secretGroups) {
111
181
  spinner.ora.text = `Checking for existing ${group} secret`;
112
182
  try {
@@ -125,7 +195,7 @@ module.exports.fullstackPreflight = async (
125
195
  throw e;
126
196
  }
127
197
 
128
- return { conflicts, existing };
198
+ return { existing };
129
199
  };
130
200
 
131
201
  module.exports.clients = [
@@ -173,6 +243,7 @@ module.exports.clients = [
173
243
  "dompe",
174
244
  "test",
175
245
  "bristolmyers",
246
+ "argenx",
176
247
  ];
177
248
 
178
249
  module.exports.static = async (
@@ -272,140 +343,656 @@ module.exports.staticTerminate = async (name, repo, branch, id) => {
272
343
  }
273
344
  };
274
345
 
275
- module.exports.fullstack = async (
276
- name,
277
- tags = [],
278
- credentials = [],
279
- repo,
280
- branch,
281
- framework,
282
- availability,
283
- database = false,
284
- storage = false,
285
- existingSecrets = { app: null, storage: null, database: null },
286
- snapshot = null,
287
- ) => {
288
- const { platform, language } = eb.configurations[framework];
346
+ // Private provisioner functions for parallel execution
289
347
 
290
- let s3Slug;
348
+ const provisionStorage = async (
349
+ aws,
350
+ s3Slug,
351
+ tags,
352
+ isLaravel,
353
+ existingResources,
354
+ ) => {
291
355
  let s3Data = {};
292
356
 
293
- if (storage) {
294
- s3Slug = module.exports.slug(
295
- repo,
296
- process.env.AWS_PROFILE,
297
- branch,
298
- "s3",
299
- );
357
+ if (!existingResources.storage) {
358
+ if (isLaravel) {
359
+ await aws.s3.createS3Bucket(s3Slug, tags, {
360
+ BlockPublicAcls: true,
361
+ IgnorePublicAcls: true,
362
+ BlockPublicPolicy: false,
363
+ RestrictPublicBuckets: false,
364
+ });
300
365
 
301
- await module.exports.iam.createIAMUser(s3Slug, tags);
302
- await module.exports.iam.attachIAMPolicy(
303
- s3Slug,
304
- "arn:aws:iam::aws:policy/AmazonS3FullAccess",
305
- );
306
- const {
307
- AccessKey: { AccessKeyId },
308
- AccessKey: { SecretAccessKey },
309
- } = await module.exports.iam.createAccessKey(s3Slug);
366
+ await aws.s3.setPublicReadPolicy(s3Slug, "public/*");
367
+ } else {
368
+ await aws.iam.createIAMUser(s3Slug, tags);
369
+ await aws.iam.attachIAMPolicy(
370
+ s3Slug,
371
+ "arn:aws:iam::aws:policy/AmazonS3FullAccess",
372
+ );
373
+ const {
374
+ AccessKey: { AccessKeyId },
375
+ AccessKey: { SecretAccessKey },
376
+ } = await aws.iam.createAccessKey(s3Slug);
310
377
 
311
- await module.exports.s3.createS3Bucket(
312
- s3Slug,
313
- tags,
314
- false,
315
- "BucketOwnerPreferred",
316
- );
378
+ await aws.s3.createS3Bucket(
379
+ s3Slug,
380
+ tags,
381
+ false,
382
+ "BucketOwnerPreferred",
383
+ );
317
384
 
318
- s3Data = { s3Slug, AccessKeyId, SecretAccessKey };
385
+ s3Data = { s3Slug, AccessKeyId, SecretAccessKey };
386
+ }
319
387
  }
320
388
 
321
- await module.exports.iam.ensureEBInstanceProfileExists();
322
- await module.exports.iam.ensureEBManagedUpdateProfileExists();
389
+ if (!s3Data.s3Slug) {
390
+ s3Data = { s3Slug };
391
+ }
323
392
 
324
- // Create decoupled RDS instance if database is required
325
- let rdsData = {};
393
+ return s3Data;
394
+ };
326
395
 
327
- if (database) {
328
- const rdsSlug = module.exports.slug(
329
- repo,
330
- process.env.AWS_PROFILE,
331
- branch,
332
- "rds",
333
- );
396
+ const provisionRDS = async (
397
+ aws,
398
+ name,
399
+ repo,
400
+ branch,
401
+ tags,
402
+ vpcData,
403
+ existingResources,
404
+ existingSecrets,
405
+ snapshot,
406
+ ) => {
407
+ const rdsSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "rds");
408
+ const rdsClient = new RDSClient({});
334
409
 
410
+ if (!existingResources.database) {
335
411
  const dbPassword = generator.generate({
336
412
  length: 10,
337
413
  numbers: true,
338
414
  });
339
415
 
340
- await module.exports.rds.ensureSSLParameterGroup();
416
+ await aws.rds.ensureSSLParameterGroup();
341
417
 
342
- const rdsSecurityGroupId =
343
- await module.exports.ec2.createRDSSecurityGroup(rdsSlug, tags);
418
+ const rdsSecurityGroupId = await aws.ec2.createRDSSecurityGroup(
419
+ rdsSlug,
420
+ tags,
421
+ );
422
+
423
+ const dbSubnetGroupName = await aws.rds.ensureDBSubnetGroup(
424
+ vpcData.privateSubnetIds,
425
+ );
344
426
 
345
427
  if (snapshot) {
346
- await module.exports.rds.restoreRDSInstanceFromSnapshot(
428
+ await aws.rds.restoreRDSInstanceFromSnapshot(
347
429
  rdsSlug,
348
430
  snapshot,
349
431
  rdsSecurityGroupId,
350
432
  tags,
433
+ dbSubnetGroupName,
351
434
  );
352
435
 
353
- await module.exports.rds.waitForRDSInstance(rdsSlug);
354
-
355
- await module.exports.rds.modifyRDSPassword(rdsSlug, dbPassword);
436
+ await aws.rds.waitForRDSInstance(rdsSlug);
437
+ await aws.rds.modifyRDSPassword(rdsSlug, dbPassword);
356
438
  } else {
357
- await module.exports.rds.createRDSInstance(
439
+ await aws.rds.createRDSInstance(
358
440
  rdsSlug,
359
441
  tags,
360
442
  dbPassword,
361
443
  rdsSecurityGroupId,
444
+ dbSubnetGroupName,
362
445
  );
363
446
  }
364
447
 
365
- const rdsInstance =
366
- await module.exports.rds.waitForRDSInstance(rdsSlug);
448
+ return {
449
+ rdsData: { RDS_PASSWORD: dbPassword },
450
+ rdsSlug,
451
+ poll: {
452
+ name: "RDS",
453
+ cb: async () =>
454
+ (
455
+ await rdsClient.send(
456
+ new DescribeDBInstancesCommand({
457
+ DBInstanceIdentifier: rdsSlug,
458
+ }),
459
+ )
460
+ ).DBInstances[0],
461
+ shouldContinue: ({ DBInstanceStatus }) =>
462
+ DBInstanceStatus !== "available",
463
+ },
464
+ };
465
+ } else if (existingResources.database && !existingSecrets.database) {
466
+ const dbPassword = generator.generate({
467
+ length: 10,
468
+ numbers: true,
469
+ });
470
+
471
+ await aws.rds.modifyRDSPassword(rdsSlug, dbPassword);
472
+
473
+ return {
474
+ rdsData: { RDS_PASSWORD: dbPassword },
475
+ rdsSlug,
476
+ poll: {
477
+ name: "RDS",
478
+ cb: async () =>
479
+ (
480
+ await rdsClient.send(
481
+ new DescribeDBInstancesCommand({
482
+ DBInstanceIdentifier: rdsSlug,
483
+ }),
484
+ )
485
+ ).DBInstances[0],
486
+ shouldContinue: ({ DBInstanceStatus }) =>
487
+ DBInstanceStatus !== "available",
488
+ },
489
+ };
490
+ } else {
491
+ const secretValue = await aws.secretsmanager.getSecretValue(
492
+ `${name}-database`,
493
+ );
494
+ return {
495
+ rdsData: {
496
+ RDS_HOSTNAME: secretValue.RDS_HOSTNAME,
497
+ RDS_PORT: secretValue.RDS_PORT,
498
+ RDS_PASSWORD: secretValue.RDS_PASSWORD,
499
+ },
500
+ rdsSlug,
501
+ };
502
+ }
503
+ };
504
+
505
+ const provisionOpenSearch = async (
506
+ aws,
507
+ osSlug,
508
+ tags,
509
+ vpcData,
510
+ instanceProfileName,
511
+ existingResources,
512
+ ) => {
513
+ const osClient = new OpenSearchClient({});
514
+
515
+ if (!existingResources.opensearch) {
516
+ await aws.iam.ensureOpenSearchServiceRole();
517
+
518
+ const roleArn = instanceProfileName
519
+ ? (await aws.iam.getRole(instanceProfileName)).Role.Arn
520
+ : undefined;
521
+
522
+ const osSecurityGroupId = await aws.ec2.createOpenSearchSecurityGroup(
523
+ osSlug,
524
+ tags,
525
+ );
526
+
527
+ await aws.opensearch.createOpenSearchDomain(
528
+ osSlug,
529
+ osSecurityGroupId,
530
+ vpcData.privateSubnetIds,
531
+ roleArn,
532
+ tags,
533
+ );
534
+
535
+ return {
536
+ osData: {},
537
+ poll: {
538
+ name: "OpenSearch",
539
+ cb: async () => {
540
+ const { DomainStatus } = await osClient.send(
541
+ new DescribeDomainCommand({ DomainName: osSlug }),
542
+ );
543
+ return DomainStatus;
544
+ },
545
+ shouldContinue: (status) =>
546
+ status.Processing ||
547
+ (!status.Endpoint && !status.Endpoints),
548
+ },
549
+ };
550
+ } else {
551
+ const osDomain = await aws.opensearch.describeOpenSearchDomain(osSlug);
552
+
553
+ const osEndpoint =
554
+ osDomain.Endpoint || (osDomain.Endpoints && osDomain.Endpoints.vpc);
555
+
556
+ return { osData: { SEARCH_HOST: `https://${osEndpoint}` } };
557
+ }
558
+ };
559
+
560
+ const provisionCache = async (
561
+ aws,
562
+ name,
563
+ cacheSlug,
564
+ tags,
565
+ vpcData,
566
+ existingResources,
567
+ existingSecrets,
568
+ ) => {
569
+ const cacheClient = new ElastiCacheClient({});
570
+
571
+ if (!existingResources.cache) {
572
+ const cachePassword = generator.generate({
573
+ length: 16,
574
+ numbers: true,
575
+ symbols: false,
576
+ strict: true,
577
+ });
578
+
579
+ const cacheSubnetGroupName =
580
+ await aws.elasticache.ensureCacheSubnetGroup(
581
+ vpcData.privateSubnetIds,
582
+ );
583
+
584
+ const cacheSecurityGroupId = await aws.ec2.createCacheSecurityGroup(
585
+ cacheSlug,
586
+ tags,
587
+ );
588
+
589
+ await aws.elasticache.createCacheCluster(
590
+ cacheSlug,
591
+ cacheSecurityGroupId,
592
+ cacheSubnetGroupName,
593
+ cachePassword,
594
+ tags,
595
+ );
596
+
597
+ return {
598
+ cacheData: { REDIS_PASSWORD: cachePassword },
599
+ poll: {
600
+ name: "ElastiCache",
601
+ cb: async () => {
602
+ const { ReplicationGroups } = await cacheClient.send(
603
+ new DescribeReplicationGroupsCommand({
604
+ ReplicationGroupId: cacheSlug,
605
+ }),
606
+ );
607
+ return ReplicationGroups[0];
608
+ },
609
+ shouldContinue: (group) => group.Status !== "available",
610
+ },
611
+ };
612
+ } else if (existingResources.cache && !existingSecrets.cache) {
613
+ const cluster = await aws.elasticache.describeCacheCluster(cacheSlug);
614
+
615
+ const cacheEndpoint = cluster.NodeGroups[0].PrimaryEndpoint;
367
616
 
368
- rdsData = {
369
- RDS_HOSTNAME: rdsInstance.Endpoint.Address,
370
- RDS_PORT: String(rdsInstance.Endpoint.Port),
371
- RDS_PASSWORD: dbPassword,
617
+ return {
618
+ cacheData: {
619
+ REDIS_HOST: cacheEndpoint.Address,
620
+ REDIS_PORT: String(cacheEndpoint.Port),
621
+ REDIS_PASSWORD: "",
622
+ },
623
+ };
624
+ } else {
625
+ const secretValue = await aws.secretsmanager.getSecretValue(
626
+ `${name}-cache`,
627
+ );
628
+ return {
629
+ cacheData: {
630
+ REDIS_HOST: secretValue.REDIS_HOST,
631
+ REDIS_PORT: secretValue.REDIS_PORT,
632
+ REDIS_PASSWORD: secretValue.REDIS_PASSWORD,
633
+ },
372
634
  };
373
635
  }
636
+ };
637
+
638
+ const provisionMail = async (aws, name, tags, mailData) => {
639
+ const {
640
+ IAMClient,
641
+ CreateUserCommand,
642
+ GetUserCommand,
643
+ CreateAccessKeyCommand,
644
+ ListAccessKeysCommand,
645
+ } = require("@aws-sdk/client-iam");
646
+ const { fromIni } = require("@aws-sdk/credential-providers");
647
+
648
+ const sesProfile = "fishawack";
649
+ const sesRegion = "us-east-1";
650
+ const groupName = "AWSSESSendingGroupDoNotRename";
651
+
652
+ const iamClient = new IAMClient({
653
+ region: sesRegion,
654
+ credentials: fromIni({ profile: sesProfile }),
655
+ });
656
+
657
+ const userName = `${name}-ses`;
374
658
 
659
+ // Create user in the fishawack account
375
660
  try {
376
- await module.exports.elasticbeanstalk.createElasticBeanstalkApplication(
377
- repo,
661
+ await Spinner.prototype.simple(
662
+ `Creating SES IAM user ${userName}`,
663
+ () => {
664
+ return iamClient.send(
665
+ new CreateUserCommand({
666
+ UserName: userName,
667
+ Tags: [
668
+ { Key: "client", Value: process.env.AWS_PROFILE },
669
+ ].concat(
670
+ tags.map((t) => ({
671
+ Key: t.Key,
672
+ Value: String(t.Value),
673
+ })),
674
+ ),
675
+ }),
676
+ );
677
+ },
678
+ );
679
+ } catch {
680
+ await Spinner.prototype.simple(
681
+ `Retrieving existing SES IAM user ${userName}`,
682
+ () => {
683
+ return iamClient.send(
684
+ new GetUserCommand({ UserName: userName }),
685
+ );
686
+ },
378
687
  );
688
+ }
689
+
690
+ // Add user to SES sending group
691
+ await aws.iam.addUserToGroup(userName, groupName, iamClient);
692
+
693
+ // Create access key
694
+ const existingKeys = await iamClient.send(
695
+ new ListAccessKeysCommand({ UserName: userName }),
696
+ );
697
+
698
+ if (existingKeys.AccessKeyMetadata.length) {
699
+ // Keys already exist — we can't retrieve the secret again so return what we have in secrets
700
+ return {
701
+ MAIL_USERNAME: existingKeys.AccessKeyMetadata[0].AccessKeyId,
702
+ MAIL_PASSWORD: "",
703
+ MAIL_FROM_ADDRESS: mailData.fromAddress,
704
+ MAIL_FROM_NAME: mailData.fromName,
705
+ };
706
+ }
707
+
708
+ const keyRes = await Spinner.prototype.simple(
709
+ `Creating access key for SES user`,
710
+ () => {
711
+ return iamClient.send(
712
+ new CreateAccessKeyCommand({ UserName: userName }),
713
+ );
714
+ },
715
+ );
716
+
717
+ // Derive SMTP credentials
718
+ const smtpPassword = aws.ses.deriveSmtpPassword(
719
+ keyRes.AccessKey.SecretAccessKey,
720
+ sesRegion,
721
+ );
722
+
723
+ return {
724
+ MAIL_USERNAME: keyRes.AccessKey.AccessKeyId,
725
+ MAIL_PASSWORD: smtpPassword,
726
+ MAIL_FROM_ADDRESS: mailData.fromAddress,
727
+ MAIL_FROM_NAME: mailData.fromName,
728
+ };
729
+ };
730
+
731
+ const authorizeIngress = async (aws, name, slug, service, authorizer) => {
732
+ try {
733
+ const sg = await aws.ec2.findSecurityGroupByName(`${slug}-${service}`);
734
+ const ebSg = await aws.ec2.findSecurityGroupByTag([
735
+ {
736
+ Name: "tag:elasticbeanstalk:environment-name",
737
+ Values: [name],
738
+ },
739
+ {
740
+ Name: "tag:aws:cloudformation:logical-id",
741
+ Values: ["AWSEBSecurityGroup"],
742
+ },
743
+ ]);
744
+ if (sg && ebSg) {
745
+ await authorizer(sg.GroupId, ebSg.GroupId);
746
+ }
379
747
  } catch {
380
748
  /* empty */
381
749
  }
750
+ };
751
+
752
+ module.exports.fullstack = async (
753
+ name,
754
+ tags = [],
755
+ repo,
756
+ branch,
757
+ framework,
758
+ database = false,
759
+ storage = false,
760
+ opensearch = false,
761
+ cache = false,
762
+ mail = false,
763
+ existingSecrets = {
764
+ app: null,
765
+ storage: null,
766
+ database: null,
767
+ opensearch: null,
768
+ cache: null,
769
+ mail: null,
770
+ },
771
+ snapshot = null,
772
+ elbScheme = "public",
773
+ existingEnvironment = false,
774
+ existingResources = {
775
+ storage: false,
776
+ database: false,
777
+ opensearch: false,
778
+ cache: false,
779
+ },
780
+ appName,
781
+ appDomain,
782
+ certArn,
783
+ instanceType = "t3.micro",
784
+ mailData = {},
785
+ ) => {
786
+ const { platform, language } = eb.configurations[framework];
787
+ const isLaravel = framework === "laravel";
788
+ const aws = module.exports;
789
+
790
+ // Compute slugs
791
+ const s3Slug =
792
+ storage || existingSecrets.storage
793
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "s3")
794
+ : undefined;
795
+
796
+ const osSlug =
797
+ opensearch || existingSecrets.opensearch
798
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "os")
799
+ : undefined;
800
+
801
+ const cacheSlug =
802
+ cache || existingSecrets.cache
803
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "cache")
804
+ : undefined;
805
+
806
+ const opensearchDomainArn = osSlug
807
+ ? `arn:aws:es:${process.env.AWS_REGION}:*:domain/${osSlug}`
808
+ : undefined;
809
+
810
+ // Phase 1: IAM prerequisites (needed before OpenSearch and EB env)
811
+ let instanceProfileName;
812
+
813
+ if (isLaravel) {
814
+ instanceProfileName = await aws.iam.ensureEnvironmentInstanceProfile(
815
+ name,
816
+ s3Slug,
817
+ opensearchDomainArn,
818
+ tags,
819
+ );
820
+ } else {
821
+ await aws.iam.ensureEBInstanceProfileExists();
822
+ }
382
823
 
383
- let hasKeyPair = false;
824
+ // Phase 2: VPC + EB app in parallel
825
+ const [vpcData] = await Promise.all([
826
+ aws.ec2.ensurePrivateSubnets(),
827
+ aws.iam.ensureEBManagedUpdateProfileExists(),
828
+ ]);
384
829
 
385
830
  try {
386
- await module.exports.ec2.getKeyPair("id_rsa_prev");
387
- hasKeyPair = true;
831
+ await aws.elasticbeanstalk.createElasticBeanstalkApplication(
832
+ repo,
833
+ tags,
834
+ );
388
835
  } catch {
389
836
  /* empty */
390
837
  }
391
838
 
392
- // LetsEncrypt CN records are limited to 64 chars so use only the hash from the generated name
839
+ // Phase 3: Provision services in parallel
840
+ const servicePromises = [];
841
+
842
+ if (storage) {
843
+ servicePromises.push(
844
+ provisionStorage(aws, s3Slug, tags, isLaravel, existingResources),
845
+ );
846
+ } else {
847
+ servicePromises.push(Promise.resolve(s3Slug ? { s3Slug } : {}));
848
+ }
849
+
850
+ if (database) {
851
+ servicePromises.push(
852
+ provisionRDS(
853
+ aws,
854
+ name,
855
+ repo,
856
+ branch,
857
+ tags,
858
+ vpcData,
859
+ existingResources,
860
+ existingSecrets,
861
+ snapshot,
862
+ ),
863
+ );
864
+ } else {
865
+ servicePromises.push(Promise.resolve({ rdsData: {}, rdsSlug: null }));
866
+ }
867
+
868
+ if (opensearch) {
869
+ servicePromises.push(
870
+ provisionOpenSearch(
871
+ aws,
872
+ osSlug,
873
+ tags,
874
+ vpcData,
875
+ instanceProfileName,
876
+ existingResources,
877
+ ),
878
+ );
879
+ } else {
880
+ servicePromises.push(Promise.resolve({ osData: {} }));
881
+ }
882
+
883
+ if (cache) {
884
+ servicePromises.push(
885
+ provisionCache(
886
+ aws,
887
+ name,
888
+ cacheSlug,
889
+ tags,
890
+ vpcData,
891
+ existingResources,
892
+ existingSecrets,
893
+ ),
894
+ );
895
+ } else {
896
+ servicePromises.push(Promise.resolve({ cacheData: {} }));
897
+ }
898
+
899
+ const [s3Data, rdsResult, osResult, cacheResult] =
900
+ await Promise.all(servicePromises);
901
+
902
+ // Phase 3b: Wait for all pending services with single spinner
903
+ const pendingPolls = [rdsResult, osResult, cacheResult]
904
+ .filter((r) => r && r.poll)
905
+ .map((r) => r.poll);
906
+
907
+ const pollResults = pendingPolls.length ? await pollAll(pendingPolls) : [];
908
+
909
+ // Extract endpoint data from poll results
910
+ let rdsData = rdsResult.rdsData || {};
911
+
912
+ if (rdsResult.poll) {
913
+ const rdsInstance = pollResults[pendingPolls.indexOf(rdsResult.poll)];
914
+ rdsData.RDS_HOSTNAME = rdsInstance.Endpoint.Address;
915
+ rdsData.RDS_PORT = String(rdsInstance.Endpoint.Port);
916
+ }
917
+
918
+ let osData = osResult.osData || {};
919
+
920
+ if (osResult.poll) {
921
+ const osDomain = pollResults[pendingPolls.indexOf(osResult.poll)];
922
+ const osEndpoint =
923
+ osDomain.Endpoint || (osDomain.Endpoints && osDomain.Endpoints.vpc);
924
+ osData.SEARCH_HOST = `https://${osEndpoint}`;
925
+ }
926
+
927
+ let cacheData = cacheResult.cacheData || {};
928
+
929
+ if (cacheResult.poll) {
930
+ const cluster = pollResults[pendingPolls.indexOf(cacheResult.poll)];
931
+ const cacheEndpoint = cluster.NodeGroups[0].PrimaryEndpoint;
932
+ cacheData.REDIS_HOST = cacheEndpoint.Address;
933
+ cacheData.REDIS_PORT = String(cacheEndpoint.Port);
934
+ }
935
+
936
+ // Phase 4: Build secrets and EB environment (sequential)
393
937
  const CNAMEPrefix = `fw-auto-${name.split("-")[name.split("-").length - 1]}`;
394
938
  process.env.DOMAIN_LINK = `${CNAMEPrefix}.${process.env.AWS_REGION}.elasticbeanstalk.com`;
395
939
 
396
- // Build secret payloads and create/reuse secrets
940
+ // Provision mail credentials if needed
941
+ let mailCreds = {};
942
+ if (mail && !existingSecrets.mail) {
943
+ mailCreds = await provisionMail(aws, name, tags, mailData);
944
+ }
945
+
397
946
  const payloads = eb.buildSecretPayloads(
398
- { framework, availability, platform, language, database, storage },
399
- { ...s3Data, ...rdsData },
947
+ {
948
+ framework,
949
+ platform,
950
+ language,
951
+ database,
952
+ storage,
953
+ opensearch,
954
+ cache,
955
+ mail: mail && !existingSecrets.mail,
956
+ },
957
+ {
958
+ ...s3Data,
959
+ ...rdsData,
960
+ ...osData,
961
+ ...cacheData,
962
+ ...mailCreds,
963
+ APP_NAME: appName,
964
+ APP_DOMAIN: appDomain,
965
+ SESSION_DOMAIN: appDomain || undefined,
966
+ },
400
967
  );
401
968
 
402
969
  const secretArns = {};
403
970
 
404
- for (const group of ["app", "storage", "database"]) {
971
+ for (const group of secretGroups) {
405
972
  if (existingSecrets[group]) {
406
973
  secretArns[`${group}SecretArn`] = existingSecrets[group];
974
+
975
+ if (Object.keys(payloads[group]).length) {
976
+ const currentValue = await aws.secretsmanager.getSecretValue(
977
+ `${name}-${group}`,
978
+ );
979
+ const newKeys = Object.keys(payloads[group]).filter(
980
+ (k) => !(k in currentValue),
981
+ );
982
+
983
+ if (newKeys.length) {
984
+ const merged = { ...currentValue };
985
+ for (const k of newKeys) {
986
+ merged[k] = payloads[group][k];
987
+ }
988
+ await aws.secretsmanager.updateSecretValue(
989
+ `${name}-${group}`,
990
+ merged,
991
+ );
992
+ }
993
+ }
407
994
  } else if (Object.keys(payloads[group]).length) {
408
- const res = await module.exports.secretsmanager.createSecret(
995
+ const res = await aws.secretsmanager.createSecret(
409
996
  `${name}-${group}`,
410
997
  payloads[group],
411
998
  tags,
@@ -414,20 +1001,18 @@ module.exports.fullstack = async (
414
1001
  }
415
1002
  }
416
1003
 
417
- // Auto-generate environmentsecrets entries from secret keys + ARNs
418
1004
  const secretSettings = [];
419
1005
 
420
- for (const group of ["app", "storage", "database"]) {
1006
+ for (const group of secretGroups) {
421
1007
  const arn = secretArns[`${group}SecretArn`];
422
1008
  if (!arn) continue;
423
1009
 
424
1010
  let keys;
425
1011
 
426
1012
  if (existingSecrets[group]) {
427
- const secretValue =
428
- await module.exports.secretsmanager.getSecretValue(
429
- `${name}-${group}`,
430
- );
1013
+ const secretValue = await aws.secretsmanager.getSecretValue(
1014
+ `${name}-${group}`,
1015
+ );
431
1016
  keys = Object.keys(secretValue);
432
1017
  } else {
433
1018
  keys = Object.keys(payloads[group]);
@@ -443,115 +1028,466 @@ module.exports.fullstack = async (
443
1028
  }
444
1029
  }
445
1030
 
446
- const OptionSettings = eb.merge(
447
- "environments",
448
- {
449
- framework,
450
- availability,
451
- platform,
452
- language,
453
- database,
454
- storage,
455
- },
456
- { ...s3Data, ...rdsData },
457
- );
1031
+ // Phase 5: Create or update EB environment
1032
+ let environment;
458
1033
 
459
- OptionSettings.push(...secretSettings);
1034
+ if (existingEnvironment) {
1035
+ const SECRETS_NAMESPACE =
1036
+ "aws:elasticbeanstalk:application:environmentsecrets";
1037
+ const currentSettings =
1038
+ await aws.elasticbeanstalk.describeConfigurationSettings(
1039
+ repo,
1040
+ name,
1041
+ );
1042
+ const currentSecrets = currentSettings.filter(
1043
+ (s) => s.Namespace === SECRETS_NAMESPACE,
1044
+ );
460
1045
 
461
- if (hasKeyPair) {
462
- OptionSettings.push({
463
- OptionName: "EC2KeyName",
464
- Value: "id_rsa_prev",
465
- Namespace: "aws:autoscaling:launchconfiguration",
1046
+ const currentKeys = new Set(currentSecrets.map((s) => s.OptionName));
1047
+ const expectedKeys = new Set(secretSettings.map((s) => s.OptionName));
1048
+
1049
+ const toAdd = secretSettings.filter(
1050
+ (s) => !currentKeys.has(s.OptionName),
1051
+ );
1052
+ const toUpdate = secretSettings.filter((s) => {
1053
+ const current = currentSecrets.find(
1054
+ (c) => c.OptionName === s.OptionName,
1055
+ );
1056
+ return current && current.Value !== s.Value;
466
1057
  });
467
- }
1058
+ const toRemove = currentSecrets
1059
+ .filter((s) => !expectedKeys.has(s.OptionName))
1060
+ .map((s) => ({
1061
+ OptionName: s.OptionName,
1062
+ Namespace: SECRETS_NAMESPACE,
1063
+ }));
1064
+
1065
+ const optionSettings = [...toAdd, ...toUpdate];
1066
+
1067
+ if (optionSettings.length || toRemove.length) {
1068
+ await aws.elasticbeanstalk.updateEnvironmentSettings(
1069
+ name,
1070
+ optionSettings,
1071
+ toRemove,
1072
+ );
1073
+ }
468
1074
 
469
- const environment =
470
- await module.exports.elasticbeanstalk.createElasticBeanstalkEnvironment(
471
- name,
472
- { framework, availability, platform, language },
473
- repo,
474
- OptionSettings,
475
- CNAMEPrefix,
476
- tags,
1075
+ environment = existingEnvironment;
1076
+ } else {
1077
+ const OptionSettings = eb.merge(
1078
+ "environments",
1079
+ {
1080
+ framework,
1081
+ platform,
1082
+ language,
1083
+ database,
1084
+ storage,
1085
+ opensearch,
1086
+ vpcId: vpcData.vpcId,
1087
+ privateSubnetIds: vpcData.privateSubnetIds.join(","),
1088
+ publicSubnetIds: vpcData.publicSubnetIds.join(","),
1089
+ elbScheme,
1090
+ instanceProfileName,
1091
+ instanceType,
1092
+ },
1093
+ {
1094
+ ...s3Data,
1095
+ ...rdsData,
1096
+ ...osData,
1097
+ ...cacheData,
1098
+ APP_NAME: appName,
1099
+ APP_DOMAIN: appDomain,
1100
+ SESSION_DOMAIN: appDomain || undefined,
1101
+ },
477
1102
  );
478
1103
 
479
- // Add RDS security group ingress rule from EB security group
480
- const rdsSlugForIngress = module.exports.slug(
1104
+ if (certArn) {
1105
+ OptionSettings.push(
1106
+ {
1107
+ OptionName: "ListenerEnabled",
1108
+ Value: "true",
1109
+ Namespace: "aws:elbv2:listener:443",
1110
+ },
1111
+ {
1112
+ OptionName: "Protocol",
1113
+ Value: "HTTPS",
1114
+ Namespace: "aws:elbv2:listener:443",
1115
+ },
1116
+ {
1117
+ OptionName: "SSLCertificateArns",
1118
+ Value: certArn,
1119
+ Namespace: "aws:elbv2:listener:443",
1120
+ },
1121
+ {
1122
+ OptionName: "SSLPolicy",
1123
+ Value: "ELBSecurityPolicy-FS-1-2-Res-2020-10",
1124
+ Namespace: "aws:elbv2:listener:443",
1125
+ },
1126
+ {
1127
+ OptionName: "DefaultProcess",
1128
+ Value: "default",
1129
+ Namespace: "aws:elbv2:listener:443",
1130
+ },
1131
+ );
1132
+ }
1133
+
1134
+ OptionSettings.push(...secretSettings);
1135
+
1136
+ environment =
1137
+ await aws.elasticbeanstalk.createElasticBeanstalkEnvironment(
1138
+ name,
1139
+ { framework, platform, language },
1140
+ repo,
1141
+ OptionSettings,
1142
+ CNAMEPrefix,
1143
+ tags,
1144
+ );
1145
+ }
1146
+
1147
+ // Phase 6: SG ingress rules in parallel
1148
+ const rdsSlugForIngress = aws.slug(
481
1149
  repo,
482
1150
  process.env.AWS_PROFILE,
483
1151
  branch,
484
1152
  "rds",
485
1153
  );
486
1154
 
487
- try {
488
- const rdsSg = await module.exports.ec2.findSecurityGroupByName(
489
- `${rdsSlugForIngress}-rds`,
1155
+ const ingressPromises = [
1156
+ authorizeIngress(
1157
+ aws,
1158
+ name,
1159
+ rdsSlugForIngress,
1160
+ "rds",
1161
+ aws.ec2.authorizeRDSIngress,
1162
+ ),
1163
+ ];
1164
+
1165
+ if (osSlug) {
1166
+ ingressPromises.push(
1167
+ authorizeIngress(
1168
+ aws,
1169
+ name,
1170
+ osSlug,
1171
+ "os",
1172
+ aws.ec2.authorizeOpenSearchIngress,
1173
+ ),
1174
+ );
1175
+ }
1176
+
1177
+ if (cacheSlug) {
1178
+ ingressPromises.push(
1179
+ authorizeIngress(
1180
+ aws,
1181
+ name,
1182
+ cacheSlug,
1183
+ "cache",
1184
+ aws.ec2.authorizeCacheIngress,
1185
+ ),
490
1186
  );
491
- const ebSg = await module.exports.ec2.findSecurityGroupByTag([
492
- {
493
- Name: "tag:elasticbeanstalk:environment-name",
494
- Values: [name],
495
- },
496
- {
497
- Name: "tag:aws:cloudformation:logical-id",
498
- Values: ["AWSEBSecurityGroup"],
499
- },
500
- ]);
501
- if (rdsSg && ebSg) {
502
- await module.exports.ec2.authorizeRDSIngress(
503
- rdsSg.GroupId,
504
- ebSg.GroupId,
505
- );
506
- }
507
- } catch {
508
- /* empty */
509
1187
  }
510
1188
 
1189
+ await Promise.all(ingressPromises);
1190
+
1191
+ // Phase 7: Copy configs and return
511
1192
  const configurations = eb.merge("configurations", {
512
1193
  framework,
513
- availability,
514
1194
  platform,
515
1195
  language,
516
1196
  });
517
1197
 
518
- if (credentials.length) {
519
- configurations.push(
520
- `.platform/${platform}/conf.d/elasticbeanstalk/${platform === "httpd" ? `z-${framework}-` : ""}htpasswd.conf`,
521
- );
522
- fs.outputFileSync(
523
- `.platform/${platform}/conf.d/elasticbeanstalk/.htpasswd-${branch}`,
524
- credentials
525
- .map((d) => `${d.username}:${md5(d.password)}`)
526
- .join("\n"),
1198
+ await aws.elasticbeanstalk.copyElasticBeanstalkConfigs(
1199
+ configurations,
1200
+ branch,
1201
+ );
1202
+
1203
+ let config = {
1204
+ url: `https://${environment.CNAME}`,
1205
+ environment: environment.EnvironmentName,
1206
+ paths: [`_IaC/${branch}/*`],
1207
+ copy: [
1208
+ {
1209
+ src: `_IaC/${branch}/.elasticbeanstalk/config.yml`,
1210
+ dest: `.elasticbeanstalk/config.yml`,
1211
+ },
1212
+ ],
1213
+ };
1214
+
1215
+ return config;
1216
+ };
1217
+
1218
+ module.exports.fullstackClone = async (
1219
+ name,
1220
+ tags,
1221
+ repo,
1222
+ branch,
1223
+ applicationName,
1224
+ sourceEnvironmentName,
1225
+ sourceVersionLabel,
1226
+ sourceBranch,
1227
+ ) => {
1228
+ const aws = module.exports;
1229
+
1230
+ // Phase 1: Read source configuration
1231
+ const sourceSettings =
1232
+ await aws.elasticbeanstalk.describeConfigurationSettings(
1233
+ applicationName,
1234
+ sourceEnvironmentName,
527
1235
  );
1236
+
1237
+ // Phase 2: Filter settings — keep relevant namespaces, exclude immutable/auto-managed
1238
+ const excludedOptions = new Set([
1239
+ "aws:elasticbeanstalk:environment::EnvironmentName",
1240
+ ]);
1241
+
1242
+ const includedNamespaces = new Set([
1243
+ "aws:elasticbeanstalk:application:environment",
1244
+ "aws:elasticbeanstalk:application:environmentsecrets",
1245
+ "aws:autoscaling:launchconfiguration",
1246
+ "aws:autoscaling:asg",
1247
+ "aws:ec2:vpc",
1248
+ "aws:elbv2:listener:443",
1249
+ "aws:elbv2:listener:default",
1250
+ "aws:elasticbeanstalk:environment",
1251
+ "aws:elasticbeanstalk:environment:process:default",
1252
+ "aws:elasticbeanstalk:healthreporting:system",
1253
+ "aws:elasticbeanstalk:managedactions",
1254
+ "aws:elasticbeanstalk:managedactions:platformupdate",
1255
+ "aws:elasticbeanstalk:cloudwatch:logs",
1256
+ "aws:elasticbeanstalk:cloudwatch:logs:health",
1257
+ ]);
1258
+
1259
+ const OptionSettings = sourceSettings
1260
+ .filter((s) => {
1261
+ if (!includedNamespaces.has(s.Namespace)) return false;
1262
+ const key = `${s.Namespace}::${s.OptionName}`;
1263
+ if (excludedOptions.has(key)) return false;
1264
+ // Exclude empty values
1265
+ if (s.Value === undefined || s.Value === null || s.Value === "")
1266
+ return false;
1267
+ return true;
1268
+ })
1269
+ .map((s) => ({
1270
+ Namespace: s.Namespace,
1271
+ OptionName: s.OptionName,
1272
+ Value: s.Value,
1273
+ }));
1274
+
1275
+ // Detect which services exist from source secrets
1276
+ const sourceSecrets = sourceSettings.filter(
1277
+ (s) =>
1278
+ s.Namespace ===
1279
+ "aws:elasticbeanstalk:application:environmentsecrets",
1280
+ );
1281
+
1282
+ const hasOpenSearch = sourceSecrets.some(
1283
+ (s) => s.OptionName === "SEARCH_HOST",
1284
+ );
1285
+
1286
+ // Set SECRET_MIRROR_ENV so setvars.sh reads secrets from the source env
1287
+ OptionSettings.push({
1288
+ Namespace: "aws:elasticbeanstalk:application:environment",
1289
+ OptionName: "SECRET_MIRROR_ENV",
1290
+ Value: sourceEnvironmentName,
1291
+ });
1292
+
1293
+ // Override HealthCheckGracePeriod for initial deploy window
1294
+ const healthGraceIdx = OptionSettings.findIndex(
1295
+ (s) =>
1296
+ s.Namespace ===
1297
+ "aws:elasticbeanstalk:environment:process:default" &&
1298
+ s.OptionName === "HealthCheckGracePeriod",
1299
+ );
1300
+ if (healthGraceIdx !== -1) {
1301
+ OptionSettings[healthGraceIdx].Value = "600";
528
1302
  }
529
1303
 
530
- await module.exports.elasticbeanstalk.copyElasticBeanstalkConfigs(
531
- configurations,
1304
+ // Phase 4: Create the environment
1305
+ const CNAMEPrefix = `fw-auto-${name.split("-")[name.split("-").length - 1]}`;
1306
+
1307
+ const environment =
1308
+ await aws.elasticbeanstalk.createElasticBeanstalkEnvironment(
1309
+ name,
1310
+ { language: detectLanguageFromSettings(sourceSettings) },
1311
+ applicationName,
1312
+ OptionSettings,
1313
+ CNAMEPrefix,
1314
+ tags,
1315
+ sourceVersionLabel,
1316
+ );
1317
+
1318
+ // Phase 5: Authorize SG ingress on source service security groups
1319
+ const rdsSlug = aws.slug(
1320
+ repo,
1321
+ process.env.AWS_PROFILE,
1322
+ sourceBranch,
1323
+ "rds",
532
1324
  );
1325
+ const cacheSlug = aws.slug(
1326
+ repo,
1327
+ process.env.AWS_PROFILE,
1328
+ sourceBranch,
1329
+ "cache",
1330
+ );
1331
+
1332
+ const ingressPromises = [
1333
+ authorizeIngress(
1334
+ aws,
1335
+ name,
1336
+ rdsSlug,
1337
+ "rds",
1338
+ aws.ec2.authorizeRDSIngress,
1339
+ ),
1340
+ ];
1341
+
1342
+ if (hasOpenSearch) {
1343
+ const sourceOsSlug = aws.slug(
1344
+ repo,
1345
+ process.env.AWS_PROFILE,
1346
+ sourceBranch,
1347
+ "os",
1348
+ );
1349
+ ingressPromises.push(
1350
+ authorizeIngress(
1351
+ aws,
1352
+ name,
1353
+ sourceOsSlug,
1354
+ "os",
1355
+ aws.ec2.authorizeOpenSearchIngress,
1356
+ ),
1357
+ );
1358
+ }
533
1359
 
534
- if (credentials.length) {
535
- configurations.push(
536
- `.platform/${platform}/conf.d/elasticbeanstalk/.htpasswd-${branch}`,
1360
+ if (sourceSecrets.some((s) => s.OptionName === "REDIS_HOST")) {
1361
+ ingressPromises.push(
1362
+ authorizeIngress(
1363
+ aws,
1364
+ name,
1365
+ cacheSlug,
1366
+ "cache",
1367
+ aws.ec2.authorizeCacheIngress,
1368
+ ),
537
1369
  );
538
1370
  }
539
1371
 
540
- let config = {
1372
+ await Promise.all(ingressPromises);
1373
+
1374
+ // Phase 6: Copy configs
1375
+ const framework = detectFrameworkFromSettings(sourceSettings);
1376
+ const { platform, language } = eb.configurations[framework];
1377
+ const configurations = eb.merge("configurations", {
1378
+ framework,
1379
+ platform,
1380
+ language,
1381
+ });
1382
+
1383
+ await aws.elasticbeanstalk.copyElasticBeanstalkConfigs(
1384
+ configurations,
1385
+ branch,
1386
+ );
1387
+
1388
+ return {
541
1389
  url: `https://${environment.CNAME}`,
542
1390
  environment: environment.EnvironmentName,
543
- paths: configurations.map((d) => {
544
- const obj = { src: d, dest: d };
545
- // Fix for core mistakenly mapping .htpasswd to directory
546
- if (d.includes(`.htpasswd-${branch}`)) {
547
- obj.file = true;
548
- obj.dest = d.split(`-${branch}`)[0];
549
- }
550
- return obj;
551
- }),
1391
+ paths: [`_IaC/${branch}/*`],
1392
+ copy: [
1393
+ {
1394
+ src: `_IaC/${branch}/.elasticbeanstalk/config.yml`,
1395
+ dest: `.elasticbeanstalk/config.yml`,
1396
+ },
1397
+ ],
552
1398
  };
1399
+ };
553
1400
 
554
- return config;
1401
+ const detectLanguageFromSettings = (settings) => {
1402
+ const envVars = settings.filter(
1403
+ (s) =>
1404
+ s.Namespace === "aws:elasticbeanstalk:application:environment" ||
1405
+ s.Namespace ===
1406
+ "aws:elasticbeanstalk:application:environmentsecrets",
1407
+ );
1408
+ const keys = envVars.map((s) => s.OptionName);
1409
+ if (keys.includes("DJANGO_SETTINGS_MODULE")) return "python";
1410
+ if (keys.includes("NODE_ENV")) return "node";
1411
+ return "php";
1412
+ };
1413
+
1414
+ const detectFrameworkFromSettings = (settings) => {
1415
+ const envVars = settings.filter(
1416
+ (s) =>
1417
+ s.Namespace === "aws:elasticbeanstalk:application:environment" ||
1418
+ s.Namespace ===
1419
+ "aws:elasticbeanstalk:application:environmentsecrets",
1420
+ );
1421
+ const keys = envVars.map((s) => s.OptionName);
1422
+ if (keys.includes("DJANGO_SETTINGS_MODULE")) return "python";
1423
+ if (keys.includes("ADONIS_ACE_CWD")) return "adonis";
1424
+ if (keys.includes("APP_KEY")) return "laravel";
1425
+ return "laravel";
1426
+ };
1427
+
1428
+ module.exports.fullstackCloneTerminate = async (
1429
+ name,
1430
+ repo,
1431
+ branch,
1432
+ sourceBranch,
1433
+ ) => {
1434
+ const aws = module.exports;
1435
+
1436
+ const rdsSlug = aws.slug(
1437
+ repo,
1438
+ process.env.AWS_PROFILE,
1439
+ sourceBranch,
1440
+ "rds",
1441
+ );
1442
+ const osSlug = aws.slug(repo, process.env.AWS_PROFILE, sourceBranch, "os");
1443
+ const cacheSlug = aws.slug(
1444
+ repo,
1445
+ process.env.AWS_PROFILE,
1446
+ sourceBranch,
1447
+ "cache",
1448
+ );
1449
+
1450
+ // Phase 1: Revoke SG ingress rules
1451
+ await Promise.all([
1452
+ authorizeIngress(aws, name, rdsSlug, "rds", aws.ec2.revokeRDSIngress),
1453
+ authorizeIngress(
1454
+ aws,
1455
+ name,
1456
+ osSlug,
1457
+ "os",
1458
+ aws.ec2.revokeOpenSearchIngress,
1459
+ ),
1460
+ authorizeIngress(
1461
+ aws,
1462
+ name,
1463
+ cacheSlug,
1464
+ "cache",
1465
+ aws.ec2.revokeCacheIngress,
1466
+ ),
1467
+ ]);
1468
+
1469
+ // Phase 2: Terminate EB environment
1470
+ try {
1471
+ await aws.elasticbeanstalk.removeElasticBeanstalkEnvironment(name);
1472
+ } catch {
1473
+ /* empty */
1474
+ }
1475
+
1476
+ // Phase 3: Terminate EB environment + try removing app if empty
1477
+ await Promise.all([
1478
+ (async () => {
1479
+ try {
1480
+ const envs = await aws.elasticbeanstalk.listEnvironments(repo);
1481
+ if (!envs.length) {
1482
+ await aws.elasticbeanstalk.removeElasticBeanstalkApplication(
1483
+ repo,
1484
+ );
1485
+ }
1486
+ } catch {
1487
+ /* empty */
1488
+ }
1489
+ })(),
1490
+ ]);
555
1491
  };
556
1492
 
557
1493
  module.exports.fullstackTerminate = async (
@@ -561,128 +1497,333 @@ module.exports.fullstackTerminate = async (
561
1497
  {
562
1498
  deleteStorage = false,
563
1499
  deleteDatabase = false,
1500
+ deleteOpenSearch = false,
1501
+ deleteCache = false,
1502
+ deleteMail = false,
564
1503
  deleteAppSecret = false,
565
1504
  } = {},
566
1505
  ) => {
567
- if (deleteStorage) {
568
- const s3Slug = module.exports.slug(
569
- repo,
570
- process.env.AWS_PROFILE,
571
- branch,
572
- "s3",
573
- );
1506
+ const aws = module.exports;
574
1507
 
575
- try {
576
- await module.exports.iam.removeIAMUser(s3Slug);
577
- } catch {
578
- /* empty */
579
- }
1508
+ const rdsSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "rds");
1509
+ const osSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "os");
1510
+ const cacheSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "cache");
580
1511
 
581
- try {
582
- await module.exports.s3.emptyS3Bucket(s3Slug);
583
- } catch {
584
- /* empty */
585
- }
1512
+ // Phase 1: Storage cleanup + revoke all SG ingress rules in parallel
1513
+ const phase1 = [];
586
1514
 
587
- try {
588
- await module.exports.s3.removeS3Bucket(s3Slug);
589
- } catch {
590
- /* empty */
591
- }
1515
+ if (deleteStorage) {
1516
+ const s3Slug = aws.slug(repo, process.env.AWS_PROFILE, branch, "s3");
1517
+
1518
+ phase1.push(
1519
+ (async () => {
1520
+ try {
1521
+ await aws.iam.removeIAMUser(s3Slug);
1522
+ } catch {
1523
+ /* empty */
1524
+ }
1525
+ try {
1526
+ await aws.s3.emptyS3Bucket(s3Slug);
1527
+ } catch {
1528
+ /* empty */
1529
+ }
1530
+ try {
1531
+ await aws.s3.removeS3Bucket(s3Slug);
1532
+ } catch {
1533
+ /* empty */
1534
+ }
1535
+ })(),
1536
+ );
592
1537
  }
593
1538
 
594
- // Remove RDS inbound rule referencing EB security group before terminating EB
595
- const rdsSlug = module.exports.slug(
596
- repo,
597
- process.env.AWS_PROFILE,
598
- branch,
599
- "rds",
1539
+ phase1.push(
1540
+ authorizeIngress(aws, name, rdsSlug, "rds", aws.ec2.revokeRDSIngress),
1541
+ authorizeIngress(
1542
+ aws,
1543
+ name,
1544
+ osSlug,
1545
+ "os",
1546
+ aws.ec2.revokeOpenSearchIngress,
1547
+ ),
1548
+ authorizeIngress(
1549
+ aws,
1550
+ name,
1551
+ cacheSlug,
1552
+ "cache",
1553
+ aws.ec2.revokeCacheIngress,
1554
+ ),
600
1555
  );
601
1556
 
1557
+ await Promise.all(phase1);
1558
+
1559
+ // Phase 2: Terminate EB environment (must complete before SG deletion)
602
1560
  try {
603
- const rdsSg = await module.exports.ec2.findSecurityGroupByName(
604
- `${rdsSlug}-rds`,
605
- );
606
- const ebSg = await module.exports.ec2.findSecurityGroupByTag([
607
- {
608
- Name: "tag:elasticbeanstalk:environment-name",
609
- Values: [name],
610
- },
611
- {
612
- Name: "tag:aws:cloudformation:logical-id",
613
- Values: ["AWSEBSecurityGroup"],
614
- },
615
- ]);
616
- if (rdsSg && ebSg) {
617
- await module.exports.ec2.revokeRDSIngress(
618
- rdsSg.GroupId,
619
- ebSg.GroupId,
620
- );
621
- }
1561
+ await aws.elasticbeanstalk.removeElasticBeanstalkEnvironment(name);
622
1562
  } catch {
623
1563
  /* empty */
624
1564
  }
625
1565
 
626
- try {
627
- await module.exports.elasticbeanstalk.removeElasticBeanstalkEnvironment(
628
- name,
1566
+ // Phase 3: EB app + instance profile + initiate service deletions in parallel
1567
+ const phase3 = [
1568
+ (async () => {
1569
+ try {
1570
+ await aws.elasticbeanstalk.removeElasticBeanstalkApplication(
1571
+ repo,
1572
+ );
1573
+ } catch {
1574
+ /* empty */
1575
+ }
1576
+ })(),
1577
+ (async () => {
1578
+ try {
1579
+ await aws.iam.removeEnvironmentInstanceProfile(name);
1580
+ } catch {
1581
+ /* empty */
1582
+ }
1583
+ })(),
1584
+ ];
1585
+
1586
+ if (deleteDatabase) {
1587
+ phase3.push(aws.rds.deleteRDSInstance(rdsSlug).catch(() => {}));
1588
+ }
1589
+
1590
+ if (deleteOpenSearch) {
1591
+ phase3.push(
1592
+ aws.opensearch.deleteOpenSearchDomain(osSlug).catch(() => {}),
629
1593
  );
630
- } catch {
631
- /* empty */
632
1594
  }
633
1595
 
634
- try {
635
- await module.exports.elasticbeanstalk.removeElasticBeanstalkApplication(
636
- repo,
1596
+ if (deleteCache) {
1597
+ phase3.push(
1598
+ aws.elasticache.deleteCacheCluster(cacheSlug).catch(() => {}),
637
1599
  );
638
- } catch {
639
- /* empty */
640
1600
  }
641
1601
 
1602
+ await Promise.all(phase3);
1603
+
1604
+ // Phase 4: Wait for service deletions with round-robin polling
1605
+ const deletionPolls = [];
1606
+
642
1607
  if (deleteDatabase) {
643
- try {
644
- await module.exports.rds.deleteRDSInstance(rdsSlug);
645
- await module.exports.rds.waitForRDSDeletion(rdsSlug);
646
- } catch {
647
- /* empty */
648
- }
1608
+ const rdsClient = new RDSClient({});
1609
+
1610
+ deletionPolls.push({
1611
+ name: "RDS",
1612
+ cb: async () => {
1613
+ try {
1614
+ const res = await rdsClient.send(
1615
+ new DescribeDBInstancesCommand({
1616
+ DBInstanceIdentifier: rdsSlug,
1617
+ }),
1618
+ );
1619
+ return res.DBInstances[0];
1620
+ } catch (e) {
1621
+ if (
1622
+ e.name === "DBInstanceNotFoundFault" ||
1623
+ e.name === "InvalidParameterValue"
1624
+ ) {
1625
+ return { DBInstanceStatus: "deleted" };
1626
+ }
1627
+ throw e;
1628
+ }
1629
+ },
1630
+ shouldContinue: ({ DBInstanceStatus }) =>
1631
+ DBInstanceStatus !== "deleted",
1632
+ });
1633
+ }
649
1634
 
650
- try {
651
- const sg = await module.exports.ec2.findSecurityGroupByName(
652
- `${rdsSlug}-rds`,
653
- );
654
- if (sg) {
655
- await module.exports.ec2.deleteSecurityGroup(sg.GroupId);
656
- }
657
- } catch {
658
- /* empty */
659
- }
1635
+ if (deleteOpenSearch) {
1636
+ const osClient = new OpenSearchClient({});
1637
+
1638
+ deletionPolls.push({
1639
+ name: "OpenSearch",
1640
+ cb: async () => {
1641
+ try {
1642
+ const { DomainStatus } = await osClient.send(
1643
+ new DescribeDomainCommand({ DomainName: osSlug }),
1644
+ );
1645
+ return DomainStatus;
1646
+ } catch (e) {
1647
+ if (
1648
+ e.name === "ResourceNotFoundException" ||
1649
+ e.name === "ValidationException"
1650
+ ) {
1651
+ return { deleted: true };
1652
+ }
1653
+ throw e;
1654
+ }
1655
+ },
1656
+ shouldContinue: (status) => !status.deleted,
1657
+ });
660
1658
  }
661
1659
 
662
- // Delete secrets
663
- if (deleteStorage) {
664
- try {
665
- await module.exports.secretsmanager.deleteSecret(`${name}-storage`);
666
- } catch {
667
- /* empty */
668
- }
1660
+ if (deleteCache) {
1661
+ const cacheClient = new ElastiCacheClient({});
1662
+
1663
+ deletionPolls.push({
1664
+ name: "ElastiCache",
1665
+ cb: async () => {
1666
+ try {
1667
+ const { ReplicationGroups } = await cacheClient.send(
1668
+ new DescribeReplicationGroupsCommand({
1669
+ ReplicationGroupId: cacheSlug,
1670
+ }),
1671
+ );
1672
+ return ReplicationGroups[0];
1673
+ } catch (e) {
1674
+ if (
1675
+ e.name === "ReplicationGroupNotFoundFault" ||
1676
+ e.name === "InvalidParameterValue"
1677
+ ) {
1678
+ return { deleted: true };
1679
+ }
1680
+ throw e;
1681
+ }
1682
+ },
1683
+ shouldContinue: (group) => !group.deleted,
1684
+ });
669
1685
  }
670
1686
 
1687
+ if (deletionPolls.length) {
1688
+ await pollAll(deletionPolls, "Waiting for services to terminate");
1689
+ }
1690
+
1691
+ // Phase 5: Delete security groups after services are gone
1692
+ const sgDeletions = [];
1693
+
671
1694
  if (deleteDatabase) {
672
- try {
673
- await module.exports.secretsmanager.deleteSecret(
674
- `${name}-database`,
675
- );
676
- } catch {
677
- /* empty */
678
- }
1695
+ sgDeletions.push(
1696
+ (async () => {
1697
+ try {
1698
+ const sg = await aws.ec2.findSecurityGroupByName(
1699
+ `${rdsSlug}-rds`,
1700
+ );
1701
+ if (sg) {
1702
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1703
+ }
1704
+ } catch {
1705
+ /* empty */
1706
+ }
1707
+ })(),
1708
+ );
1709
+ }
1710
+
1711
+ if (deleteOpenSearch) {
1712
+ sgDeletions.push(
1713
+ (async () => {
1714
+ try {
1715
+ const sg = await aws.ec2.findSecurityGroupByName(
1716
+ `${osSlug}-os`,
1717
+ );
1718
+ if (sg) {
1719
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1720
+ }
1721
+ } catch {
1722
+ /* empty */
1723
+ }
1724
+ })(),
1725
+ );
679
1726
  }
680
1727
 
1728
+ if (deleteCache) {
1729
+ sgDeletions.push(
1730
+ (async () => {
1731
+ try {
1732
+ const sg = await aws.ec2.findSecurityGroupByName(
1733
+ `${cacheSlug}-cache`,
1734
+ );
1735
+ if (sg) {
1736
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1737
+ }
1738
+ } catch {
1739
+ /* empty */
1740
+ }
1741
+ })(),
1742
+ );
1743
+ }
1744
+
1745
+ if (sgDeletions.length) {
1746
+ await Promise.all(sgDeletions);
1747
+ }
1748
+
1749
+ // Phase 6: Delete secrets in parallel
1750
+ const secretDeletions = [];
1751
+
1752
+ if (deleteStorage) {
1753
+ secretDeletions.push(
1754
+ aws.secretsmanager.deleteSecret(`${name}-storage`).catch(() => {}),
1755
+ );
1756
+ }
1757
+ if (deleteDatabase) {
1758
+ secretDeletions.push(
1759
+ aws.secretsmanager.deleteSecret(`${name}-database`).catch(() => {}),
1760
+ );
1761
+ }
1762
+ if (deleteOpenSearch) {
1763
+ secretDeletions.push(
1764
+ aws.secretsmanager
1765
+ .deleteSecret(`${name}-opensearch`)
1766
+ .catch(() => {}),
1767
+ );
1768
+ }
1769
+ if (deleteCache) {
1770
+ secretDeletions.push(
1771
+ aws.secretsmanager.deleteSecret(`${name}-cache`).catch(() => {}),
1772
+ );
1773
+ }
681
1774
  if (deleteAppSecret) {
682
- try {
683
- await module.exports.secretsmanager.deleteSecret(`${name}-app`);
684
- } catch {
685
- /* empty */
686
- }
1775
+ secretDeletions.push(
1776
+ aws.secretsmanager.deleteSecret(`${name}-app`).catch(() => {}),
1777
+ );
1778
+ }
1779
+ if (deleteMail) {
1780
+ secretDeletions.push(
1781
+ aws.secretsmanager.deleteSecret(`${name}-mail`).catch(() => {}),
1782
+ );
1783
+ secretDeletions.push(
1784
+ (async () => {
1785
+ const {
1786
+ IAMClient,
1787
+ DeleteAccessKeyCommand,
1788
+ ListAccessKeysCommand,
1789
+ RemoveUserFromGroupCommand,
1790
+ DeleteUserCommand,
1791
+ } = require("@aws-sdk/client-iam");
1792
+ const { fromIni } = require("@aws-sdk/credential-providers");
1793
+
1794
+ const iamClient = new IAMClient({
1795
+ region: "us-east-1",
1796
+ credentials: fromIni({ profile: "fishawack" }),
1797
+ });
1798
+ const userName = `${name}-ses`;
1799
+
1800
+ try {
1801
+ const keys = await iamClient.send(
1802
+ new ListAccessKeysCommand({ UserName: userName }),
1803
+ );
1804
+ for (const key of keys.AccessKeyMetadata || []) {
1805
+ await iamClient.send(
1806
+ new DeleteAccessKeyCommand({
1807
+ UserName: userName,
1808
+ AccessKeyId: key.AccessKeyId,
1809
+ }),
1810
+ );
1811
+ }
1812
+ await iamClient.send(
1813
+ new RemoveUserFromGroupCommand({
1814
+ UserName: userName,
1815
+ GroupName: "AWSSESSendingGroupDoNotRename",
1816
+ }),
1817
+ );
1818
+ await iamClient.send(
1819
+ new DeleteUserCommand({ UserName: userName }),
1820
+ );
1821
+ } catch {
1822
+ /* user may not exist */
1823
+ }
1824
+ })(),
1825
+ );
687
1826
  }
1827
+
1828
+ await Promise.all(secretDeletions);
688
1829
  };