-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathcli.integtest.ts
1587 lines (1373 loc) · 56.5 KB
/
cli.integtest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { promises as fs, existsSync } from 'fs';
import * as os from 'os';
import * as path from 'path';
import { integTest, cloneDirectory, shell, withDefaultFixture, retry, sleep, randomInteger, withSamIntegrationFixture, RESOURCES_DIR, withCDKMigrateFixture, withExtendedTimeoutFixture } from '../../lib';
jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime
describe('ci', () => {
integTest('output to stderr', withDefaultFixture(async (fixture) => {
const deployOutput = await fixture.cdkDeploy('test-2', { captureStderr: true, onlyStderr: true });
const diffOutput = await fixture.cdk(['diff', fixture.fullStackName('test-2')], { captureStderr: true, onlyStderr: true });
const destroyOutput = await fixture.cdkDestroy('test-2', { captureStderr: true, onlyStderr: true });
expect(deployOutput).not.toEqual('');
expect(destroyOutput).not.toEqual('');
expect(diffOutput).not.toEqual('');
}));
describe('ci=true', () => {
integTest('output to stdout', withDefaultFixture(async (fixture) => {
const execOptions = {
captureStderr: true,
onlyStderr: true,
modEnv: {
CI: 'true',
JSII_SILENCE_WARNING_KNOWN_BROKEN_NODE_VERSION: 'true',
JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION: 'true',
JSII_SILENCE_WARNING_DEPRECATED_NODE_VERSION: 'true',
},
};
const deployOutput = await fixture.cdkDeploy('test-2', execOptions);
const diffOutput = await fixture.cdk(['diff', fixture.fullStackName('test-2')], execOptions);
const destroyOutput = await fixture.cdkDestroy('test-2', execOptions);
expect(deployOutput).toEqual('');
expect(destroyOutput).toEqual('');
expect(diffOutput).toEqual('');
}));
});
});
integTest('VPC Lookup', withDefaultFixture(async (fixture) => {
fixture.log('Making sure we are clean before starting.');
await fixture.cdkDestroy('define-vpc', { modEnv: { ENABLE_VPC_TESTING: 'DEFINE' } });
fixture.log('Setting up: creating a VPC with known tags');
await fixture.cdkDeploy('define-vpc', { modEnv: { ENABLE_VPC_TESTING: 'DEFINE' } });
fixture.log('Setup complete!');
fixture.log('Verifying we can now import that VPC');
await fixture.cdkDeploy('import-vpc', { modEnv: { ENABLE_VPC_TESTING: 'IMPORT' } });
}));
// testing a construct with a builtin Nodejs Lambda Function.
// In this case we are testing the s3.Bucket construct with the
// autoDeleteObjects prop set to true, which creates a Lambda backed
// CustomResource. Since the compiled Lambda code (e.g. __entrypoint__.js)
// is bundled as part of the CDK package, we want to make sure we don't
// introduce changes to the compiled code that could prevent the Lambda from
// executing. If we do, this test will timeout and fail.
integTest('Construct with builtin Lambda function', withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('builtin-lambda-function');
fixture.log('Setup complete!');
await fixture.cdkDestroy('builtin-lambda-function');
}));
// this is to ensure that asset bundling for apps under a stage does not break
integTest('Stage with bundled Lambda function', withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('bundling-stage/BundlingStack');
fixture.log('Setup complete!');
await fixture.cdkDestroy('bundling-stage/BundlingStack');
}));
integTest('Two ways of showing the version', withDefaultFixture(async (fixture) => {
const version1 = await fixture.cdk(['version'], { verbose: false });
const version2 = await fixture.cdk(['--version'], { verbose: false });
expect(version1).toEqual(version2);
}));
integTest('Termination protection', withDefaultFixture(async (fixture) => {
const stackName = 'termination-protection';
await fixture.cdkDeploy(stackName);
// Try a destroy that should fail
await expect(fixture.cdkDestroy(stackName)).rejects.toThrow('exited with error');
// Can update termination protection even though the change set doesn't contain changes
await fixture.cdkDeploy(stackName, { modEnv: { TERMINATION_PROTECTION: 'FALSE' } });
await fixture.cdkDestroy(stackName);
}));
integTest('cdk synth', withDefaultFixture(async (fixture) => {
await fixture.cdk(['synth', fixture.fullStackName('test-1')]);
expect(fixture.template('test-1')).toEqual(expect.objectContaining({
Resources: {
topic69831491: {
Type: 'AWS::SNS::Topic',
Metadata: {
'aws:cdk:path': `${fixture.stackNamePrefix}-test-1/topic/Resource`,
},
},
},
}));
await fixture.cdk(['synth', fixture.fullStackName('test-2')], { verbose: false });
expect(fixture.template('test-2')).toEqual(expect.objectContaining({
Resources: {
topic152D84A37: {
Type: 'AWS::SNS::Topic',
Metadata: {
'aws:cdk:path': `${fixture.stackNamePrefix}-test-2/topic1/Resource`,
},
},
topic2A4FB547F: {
Type: 'AWS::SNS::Topic',
Metadata: {
'aws:cdk:path': `${fixture.stackNamePrefix}-test-2/topic2/Resource`,
},
},
},
}));
}));
integTest('ssm parameter provider error', withDefaultFixture(async (fixture) => {
await expect(fixture.cdk(['synth',
fixture.fullStackName('missing-ssm-parameter'),
'-c', 'test:ssm-parameter-name=/does/not/exist'], {
allowErrExit: true,
})).resolves.toContain('SSM parameter not available in account');
}));
integTest('automatic ordering', withDefaultFixture(async (fixture) => {
// Deploy the consuming stack which will include the producing stack
await fixture.cdkDeploy('order-consuming');
// Destroy the providing stack which will include the consuming stack
await fixture.cdkDestroy('order-providing');
}));
integTest('automatic ordering with concurrency', withDefaultFixture(async (fixture) => {
// Deploy the consuming stack which will include the producing stack
await fixture.cdkDeploy('order-consuming', { options: ['--concurrency', '2'] });
// Destroy the providing stack which will include the consuming stack
await fixture.cdkDestroy('order-providing');
}));
integTest('--exclusively selects only selected stack', withDefaultFixture(async (fixture) => {
// Deploy the "depends-on-failed" stack, with --exclusively. It will NOT fail (because
// of --exclusively) and it WILL create an output we can check for to confirm that it did
// get deployed.
const outputsFile = path.join(fixture.integTestDir, 'outputs', 'outputs.json');
await fs.mkdir(path.dirname(outputsFile), { recursive: true });
await fixture.cdkDeploy('depends-on-failed', {
options: [
'--exclusively',
'--outputs-file', outputsFile,
],
});
// Verify the output to see that the stack deployed
const outputs = JSON.parse((await fs.readFile(outputsFile, { encoding: 'utf-8' })).toString());
expect(outputs).toEqual({
[`${fixture.stackNamePrefix}-depends-on-failed`]: {
TopicName: `${fixture.stackNamePrefix}-depends-on-failedMyTopic`,
},
});
}));
integTest('context setting', withDefaultFixture(async (fixture) => {
await fs.writeFile(path.join(fixture.integTestDir, 'cdk.context.json'), JSON.stringify({
contextkey: 'this is the context value',
}));
try {
await expect(fixture.cdk(['context'])).resolves.toContain('this is the context value');
// Test that deleting the contextkey works
await fixture.cdk(['context', '--reset', 'contextkey']);
await expect(fixture.cdk(['context'])).resolves.not.toContain('this is the context value');
// Test that forced delete of the context key does not throw
await fixture.cdk(['context', '-f', '--reset', 'contextkey']);
} finally {
await fs.unlink(path.join(fixture.integTestDir, 'cdk.context.json'));
}
}));
integTest('context in stage propagates to top', withDefaultFixture(async (fixture) => {
await expect(fixture.cdkSynth({
// This will make it error to prove that the context bubbles up, and also that we can fail on command
options: ['--no-lookups'],
modEnv: {
INTEG_STACK_SET: 'stage-using-context',
},
allowErrExit: true,
})).resolves.toContain('Context lookups have been disabled');
}));
integTest('deploy', withDefaultFixture(async (fixture) => {
const stackArn = await fixture.cdkDeploy('test-2', { captureStderr: false });
// verify the number of resources in the stack
const response = await fixture.aws.cloudFormation('describeStackResources', {
StackName: stackArn,
});
expect(response.StackResources?.length).toEqual(2);
}));
integTest('deploy --method=direct', withDefaultFixture(async (fixture) => {
const stackArn = await fixture.cdkDeploy('test-2', {
options: ['--method=direct'],
captureStderr: false,
});
// verify the number of resources in the stack
const response = await fixture.aws.cloudFormation('describeStackResources', {
StackName: stackArn,
});
expect(response.StackResources?.length).toBeGreaterThan(0);
}));
integTest('deploy all', withDefaultFixture(async (fixture) => {
const arns = await fixture.cdkDeploy('test-*', { captureStderr: false });
// verify that we only deployed both stacks (there are 2 ARNs in the output)
expect(arns.split('\n').length).toEqual(2);
}));
integTest('deploy all concurrently', withDefaultFixture(async (fixture) => {
const arns = await fixture.cdkDeploy('test-*', {
captureStderr: false,
options: ['--concurrency', '2'],
});
// verify that we only deployed both stacks (there are 2 ARNs in the output)
expect(arns.split('\n').length).toEqual(2);
}));
integTest('nested stack with parameters', withDefaultFixture(async (fixture) => {
// STACK_NAME_PREFIX is used in MyTopicParam to allow multiple instances
// of this test to run in parallel, othewise they will attempt to create the same SNS topic.
const stackArn = await fixture.cdkDeploy('with-nested-stack-using-parameters', {
options: ['--parameters', `MyTopicParam=${fixture.stackNamePrefix}ThereIsNoSpoon`],
captureStderr: false,
});
// verify that we only deployed a single stack (there's a single ARN in the output)
expect(stackArn.split('\n').length).toEqual(1);
// verify the number of resources in the stack
const response = await fixture.aws.cloudFormation('describeStackResources', {
StackName: stackArn,
});
expect(response.StackResources?.length).toEqual(1);
}));
integTest('deploy without execute a named change set', withDefaultFixture(async (fixture) => {
const changeSetName = 'custom-change-set-name';
const stackArn = await fixture.cdkDeploy('test-2', {
options: ['--no-execute', '--change-set-name', changeSetName],
captureStderr: false,
});
// verify that we only deployed a single stack (there's a single ARN in the output)
expect(stackArn.split('\n').length).toEqual(1);
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].StackStatus).toEqual('REVIEW_IN_PROGRESS');
//verify a change set was created with the provided name
const changeSetResponse = await fixture.aws.cloudFormation('listChangeSets', {
StackName: stackArn,
});
const changeSets = changeSetResponse.Summaries || [];
expect(changeSets.length).toEqual(1);
expect(changeSets[0].ChangeSetName).toEqual(changeSetName);
expect(changeSets[0].Status).toEqual('CREATE_COMPLETE');
}));
integTest('security related changes without a CLI are expected to fail', withDefaultFixture(async (fixture) => {
// redirect /dev/null to stdin, which means there will not be tty attached
// since this stack includes security-related changes, the deployment should
// immediately fail because we can't confirm the changes
const stackName = 'iam-test';
await expect(fixture.cdkDeploy(stackName, {
options: ['<', '/dev/null'], // H4x, this only works because I happen to know we pass shell: true.
neverRequireApproval: false,
})).rejects.toThrow('exited with error');
// Ensure stack was not deployed
await expect(fixture.aws.cloudFormation('describeStacks', {
StackName: fixture.fullStackName(stackName),
})).rejects.toThrow('does not exist');
}));
integTest('deploy wildcard with outputs', withDefaultFixture(async (fixture) => {
const outputsFile = path.join(fixture.integTestDir, 'outputs', 'outputs.json');
await fs.mkdir(path.dirname(outputsFile), { recursive: true });
await fixture.cdkDeploy(['outputs-test-*'], {
options: ['--outputs-file', outputsFile],
});
const outputs = JSON.parse((await fs.readFile(outputsFile, { encoding: 'utf-8' })).toString());
expect(outputs).toEqual({
[`${fixture.stackNamePrefix}-outputs-test-1`]: {
TopicName: `${fixture.stackNamePrefix}-outputs-test-1MyTopic`,
},
[`${fixture.stackNamePrefix}-outputs-test-2`]: {
TopicName: `${fixture.stackNamePrefix}-outputs-test-2MyOtherTopic`,
},
});
}));
integTest('deploy with parameters', withDefaultFixture(async (fixture) => {
const stackArn = await fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}bazinga`,
],
captureStderr: false,
});
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].Parameters).toContainEqual(
{
ParameterKey: 'TopicNameParam',
ParameterValue: `${fixture.stackNamePrefix}bazinga`,
},
);
}));
integTest('update to stack in ROLLBACK_COMPLETE state will delete stack and create a new one', withDefaultFixture(async (fixture) => {
// GIVEN
await expect(fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}@aww`,
],
captureStderr: false,
})).rejects.toThrow('exited with error');
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: fixture.fullStackName('param-test-1'),
});
const stackArn = response.Stacks?.[0].StackId;
expect(response.Stacks?.[0].StackStatus).toEqual('ROLLBACK_COMPLETE');
// WHEN
const newStackArn = await fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}allgood`,
],
captureStderr: false,
});
const newStackResponse = await fixture.aws.cloudFormation('describeStacks', {
StackName: newStackArn,
});
// THEN
expect(stackArn).not.toEqual(newStackArn); // new stack was created
expect(newStackResponse.Stacks?.[0].StackStatus).toEqual('CREATE_COMPLETE');
expect(newStackResponse.Stacks?.[0].Parameters).toContainEqual(
{
ParameterKey: 'TopicNameParam',
ParameterValue: `${fixture.stackNamePrefix}allgood`,
},
);
}));
integTest('stack in UPDATE_ROLLBACK_COMPLETE state can be updated', withDefaultFixture(async (fixture) => {
// GIVEN
const stackArn = await fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}nice`,
],
captureStderr: false,
});
let response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].StackStatus).toEqual('CREATE_COMPLETE');
// bad parameter name with @ will put stack into UPDATE_ROLLBACK_COMPLETE
await expect(fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}@aww`,
],
captureStderr: false,
})).rejects.toThrow('exited with error');;
response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].StackStatus).toEqual('UPDATE_ROLLBACK_COMPLETE');
// WHEN
await fixture.cdkDeploy('param-test-1', {
options: [
'--parameters', `TopicNameParam=${fixture.stackNamePrefix}allgood`,
],
captureStderr: false,
});
response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
// THEN
expect(response.Stacks?.[0].StackStatus).toEqual('UPDATE_COMPLETE');
expect(response.Stacks?.[0].Parameters).toContainEqual(
{
ParameterKey: 'TopicNameParam',
ParameterValue: `${fixture.stackNamePrefix}allgood`,
},
);
}));
integTest('deploy with wildcard and parameters', withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('param-test-*', {
options: [
'--parameters', `${fixture.stackNamePrefix}-param-test-1:TopicNameParam=${fixture.stackNamePrefix}bazinga`,
'--parameters', `${fixture.stackNamePrefix}-param-test-2:OtherTopicNameParam=${fixture.stackNamePrefix}ThatsMySpot`,
'--parameters', `${fixture.stackNamePrefix}-param-test-3:DisplayNameParam=${fixture.stackNamePrefix}HeyThere`,
'--parameters', `${fixture.stackNamePrefix}-param-test-3:OtherDisplayNameParam=${fixture.stackNamePrefix}AnotherOne`,
],
});
}));
integTest('deploy with parameters multi', withDefaultFixture(async (fixture) => {
const paramVal1 = `${fixture.stackNamePrefix}bazinga`;
const paramVal2 = `${fixture.stackNamePrefix}=jagshemash`;
const stackArn = await fixture.cdkDeploy('param-test-3', {
options: [
'--parameters', `DisplayNameParam=${paramVal1}`,
'--parameters', `OtherDisplayNameParam=${paramVal2}`,
],
captureStderr: false,
});
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].Parameters).toContainEqual(
{
ParameterKey: 'DisplayNameParam',
ParameterValue: paramVal1,
},
);
expect(response.Stacks?.[0].Parameters).toContainEqual(
{
ParameterKey: 'OtherDisplayNameParam',
ParameterValue: paramVal2,
},
);
}));
integTest('deploy with notification ARN', withDefaultFixture(async (fixture) => {
const topicName = `${fixture.stackNamePrefix}-test-topic`;
const response = await fixture.aws.sns('createTopic', { Name: topicName });
const topicArn = response.TopicArn!;
try {
await fixture.cdkDeploy('test-2', {
options: ['--notification-arns', topicArn],
});
// verify that the stack we deployed has our notification ARN
const describeResponse = await fixture.aws.cloudFormation('describeStacks', {
StackName: fixture.fullStackName('test-2'),
});
expect(describeResponse.Stacks?.[0].NotificationARNs).toEqual([topicArn]);
} finally {
await fixture.aws.sns('deleteTopic', {
TopicArn: topicArn,
});
}
}));
// NOTE: this doesn't currently work with modern-style synthesis, as the bootstrap
// role by default will not have permission to iam:PassRole the created role.
integTest('deploy with role', withDefaultFixture(async (fixture) => {
if (fixture.packages.majorVersion() !== '1') {
return; // Nothing to do
}
const roleName = `${fixture.stackNamePrefix}-test-role`;
await deleteRole();
const createResponse = await fixture.aws.iam('createRole', {
RoleName: roleName,
AssumeRolePolicyDocument: JSON.stringify({
Version: '2012-10-17',
Statement: [{
Action: 'sts:AssumeRole',
Principal: { Service: 'cloudformation.amazonaws.com' },
Effect: 'Allow',
}, {
Action: 'sts:AssumeRole',
Principal: { AWS: (await fixture.aws.sts('getCallerIdentity', {})).Arn },
Effect: 'Allow',
}],
}),
});
const roleArn = createResponse.Role.Arn;
try {
await fixture.aws.iam('putRolePolicy', {
RoleName: roleName,
PolicyName: 'DefaultPolicy',
PolicyDocument: JSON.stringify({
Version: '2012-10-17',
Statement: [{
Action: '*',
Resource: '*',
Effect: 'Allow',
}],
}),
});
await retry(fixture.output, 'Trying to assume fresh role', retry.forSeconds(300), async () => {
await fixture.aws.sts('assumeRole', {
RoleArn: roleArn,
RoleSessionName: 'testing',
});
});
// In principle, the role has replicated from 'us-east-1' to wherever we're testing.
// Give it a little more sleep to make sure CloudFormation is not hitting a box
// that doesn't have it yet.
await sleep(5000);
await fixture.cdkDeploy('test-2', {
options: ['--role-arn', roleArn],
});
// Immediately delete the stack again before we delete the role.
//
// Since roles are sticky, if we delete the role before the stack, subsequent DeleteStack
// operations will fail when CloudFormation tries to assume the role that's already gone.
await fixture.cdkDestroy('test-2');
} finally {
await deleteRole();
}
async function deleteRole() {
try {
for (const policyName of (await fixture.aws.iam('listRolePolicies', { RoleName: roleName })).PolicyNames) {
await fixture.aws.iam('deleteRolePolicy', {
RoleName: roleName,
PolicyName: policyName,
});
}
await fixture.aws.iam('deleteRole', { RoleName: roleName });
} catch (e: any) {
if (e.message.indexOf('cannot be found') > -1) { return; }
throw e;
}
}
}));
// TODO add more testing that ensures the symmetry of the generated constructs to the resources.
['typescript', 'python', 'csharp', 'java'].forEach(language => {
integTest(`cdk migrate ${language} deploys successfully`, withCDKMigrateFixture(language, async (fixture) => {
if (language === 'python') {
await fixture.shell(['pip', 'install', '-r', 'requirements.txt']);
}
const stackArn = await fixture.cdkDeploy(fixture.stackNamePrefix, { neverRequireApproval: true, verbose: true, captureStderr: false }, true);
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
expect(response.Stacks?.[0].StackStatus).toEqual('CREATE_COMPLETE');
await fixture.cdkDestroy(fixture.stackNamePrefix);
}));
});
integTest('cdk migrate generates migrate.json', withCDKMigrateFixture('typescript', async (fixture) => {
const migrateFile = await fs.readFile(path.join(fixture.integTestDir, 'migrate.json'), 'utf8');
const expectedFile = `{
\"//\": \"This file is generated by cdk migrate. It will be automatically deleted after the first successful deployment of this app to the environment of the original resources.\",
\"Source\": \"localfile\"
}`;
expect(JSON.parse(migrateFile)).toEqual(JSON.parse(expectedFile));
await fixture.cdkDestroy(fixture.stackNamePrefix);
}));
// integTest('cdk migrate --from-scan with AND/OR filters correctly filters resources', withExtendedTimeoutFixture(async (fixture) => {
// const stackName = `cdk-migrate-integ-${fixture.randomString}`;
// await fixture.cdkDeploy('migrate-stack', {
// modEnv: { SAMPLE_RESOURCES: '1' },
// });
// await fixture.cdk(
// ['migrate', '--stack-name', stackName, '--from-scan', 'new', '--filter', 'type=AWS::SNS::Topic,tag-key=tag1', 'type=AWS::SQS::Queue,tag-key=tag3'],
// { modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
// );
// try {
// const response = await fixture.aws.cloudFormation('describeGeneratedTemplate', {
// GeneratedTemplateName: stackName,
// });
// const resourceNames = [];
// for (const resource of response.Resources || []) {
// if (resource.LogicalResourceId) {
// resourceNames.push(resource.LogicalResourceId);
// }
// }
// fixture.log(`Resources: ${resourceNames}`);
// expect(resourceNames.some(ele => ele && ele.includes('migratetopic1'))).toBeTruthy();
// expect(resourceNames.some(ele => ele && ele.includes('migratequeue1'))).toBeTruthy();
// } finally {
// await fixture.cdkDestroy('migrate-stack');
// await fixture.aws.cloudFormation('deleteGeneratedTemplate', {
// GeneratedTemplateName: stackName,
// });
// }
// }));
// integTest('cdk migrate --from-scan for resources with Write Only Properties generates warnings', withExtendedTimeoutFixture(async (fixture) => {
// const stackName = `cdk-migrate-integ-${fixture.randomString}`;
// await fixture.cdkDeploy('migrate-stack', {
// modEnv: {
// LAMBDA_RESOURCES: '1',
// },
// });
// await fixture.cdk(
// ['migrate', '--stack-name', stackName, '--from-scan', 'new', '--filter', 'type=AWS::Lambda::Function,tag-key=lambda-tag'],
// { modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
// );
// try {
// const response = await fixture.aws.cloudFormation('describeGeneratedTemplate', {
// GeneratedTemplateName: stackName,
// });
// const resourceNames = [];
// for (const resource of response.Resources || []) {
// if (resource.LogicalResourceId && resource.ResourceType === 'AWS::Lambda::Function') {
// resourceNames.push(resource.LogicalResourceId);
// }
// }
// fixture.log(`Resources: ${resourceNames}`);
// const readmePath = path.join(fixture.integTestDir, stackName, 'README.md');
// const readme = await fs.readFile(readmePath, 'utf8');
// expect(readme).toContain('## Warnings');
// for (const resourceName of resourceNames) {
// expect(readme).toContain(`### ${resourceName}`);
// }
// } finally {
// await fixture.cdkDestroy('migrate-stack');
// await fixture.aws.cloudFormation('deleteGeneratedTemplate', {
// GeneratedTemplateName: stackName,
// });
// }
// }));
['typescript', 'python', 'csharp', 'java'].forEach(language => {
integTest(`cdk migrate --from-stack creates deployable ${language} app`, withExtendedTimeoutFixture(async (fixture) => {
const migrateStackName = fixture.fullStackName('migrate-stack');
await fixture.aws.cloudFormation('createStack', {
StackName: migrateStackName,
TemplateBody: await fs.readFile(path.join(__dirname, '..', '..', 'resources', 'templates', 'sqs-template.json'), 'utf8'),
});
try {
let stackStatus = 'CREATE_IN_PROGRESS';
while (stackStatus === 'CREATE_IN_PROGRESS') {
stackStatus = await (await (fixture.aws.cloudFormation('describeStacks', { StackName: migrateStackName }))).Stacks?.[0].StackStatus!;
await sleep(1000);
}
await fixture.cdk(
['migrate', '--stack-name', migrateStackName, '--from-stack'],
{ modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
);
await fixture.shell(['cd', path.join(fixture.integTestDir, migrateStackName)]);
await fixture.cdk(['deploy', migrateStackName], { neverRequireApproval: true, verbose: true, captureStderr: false });
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: migrateStackName,
});
expect(response.Stacks?.[0].StackStatus).toEqual('UPDATE_COMPLETE');
} finally {
await fixture.cdkDestroy('migrate-stack');
}
}));
});
integTest('cdk diff', withDefaultFixture(async (fixture) => {
const diff1 = await fixture.cdk(['diff', fixture.fullStackName('test-1')]);
expect(diff1).toContain('AWS::SNS::Topic');
const diff2 = await fixture.cdk(['diff', fixture.fullStackName('test-2')]);
expect(diff2).toContain('AWS::SNS::Topic');
// We can make it fail by passing --fail
await expect(fixture.cdk(['diff', '--fail', fixture.fullStackName('test-1')]))
.rejects.toThrow('exited with error');
}));
integTest('enableDiffNoFail', withDefaultFixture(async (fixture) => {
await diffShouldSucceedWith({ fail: false, enableDiffNoFail: false });
await diffShouldSucceedWith({ fail: false, enableDiffNoFail: true });
await diffShouldFailWith({ fail: true, enableDiffNoFail: false });
await diffShouldFailWith({ fail: true, enableDiffNoFail: true });
await diffShouldFailWith({ fail: undefined, enableDiffNoFail: false });
await diffShouldSucceedWith({ fail: undefined, enableDiffNoFail: true });
async function diffShouldSucceedWith(props: DiffParameters) {
await expect(diff(props)).resolves.not.toThrowError();
}
async function diffShouldFailWith(props: DiffParameters) {
await expect(diff(props)).rejects.toThrow('exited with error');
}
async function diff(props: DiffParameters): Promise<string> {
await updateContext(props.enableDiffNoFail);
const flag = props.fail != null
? (props.fail ? '--fail' : '--no-fail')
: '';
return fixture.cdk(['diff', flag, fixture.fullStackName('test-1')]);
}
async function updateContext(enableDiffNoFail: boolean) {
const cdkJson = JSON.parse(await fs.readFile(path.join(fixture.integTestDir, 'cdk.json'), 'utf8'));
cdkJson.context = {
...cdkJson.context,
'aws-cdk:enableDiffNoFail': enableDiffNoFail,
};
await fs.writeFile(path.join(fixture.integTestDir, 'cdk.json'), JSON.stringify(cdkJson));
}
type DiffParameters = { fail?: boolean; enableDiffNoFail: boolean };
}));
integTest('cdk diff --fail on multiple stacks exits with error if any of the stacks contains a diff', withDefaultFixture(async (fixture) => {
// GIVEN
const diff1 = await fixture.cdk(['diff', fixture.fullStackName('test-1')]);
expect(diff1).toContain('AWS::SNS::Topic');
await fixture.cdkDeploy('test-2');
const diff2 = await fixture.cdk(['diff', fixture.fullStackName('test-2')]);
expect(diff2).toContain('There were no differences');
// WHEN / THEN
await expect(fixture.cdk(['diff', '--fail', fixture.fullStackName('test-1'), fixture.fullStackName('test-2')])).rejects.toThrow('exited with error');
}));
integTest('cdk diff --fail with multiple stack exits with if any of the stacks contains a diff', withDefaultFixture(async (fixture) => {
// GIVEN
await fixture.cdkDeploy('test-1');
const diff1 = await fixture.cdk(['diff', fixture.fullStackName('test-1')]);
expect(diff1).toContain('There were no differences');
const diff2 = await fixture.cdk(['diff', fixture.fullStackName('test-2')]);
expect(diff2).toContain('AWS::SNS::Topic');
// WHEN / THEN
await expect(fixture.cdk(['diff', '--fail', fixture.fullStackName('test-1'), fixture.fullStackName('test-2')])).rejects.toThrow('exited with error');
}));
integTest('cdk diff --security-only --fail exits when security changes are present', withDefaultFixture(async (fixture) => {
const stackName = 'iam-test';
await expect(fixture.cdk(['diff', '--security-only', '--fail', fixture.fullStackName(stackName)])).rejects.toThrow('exited with error');
}));
integTest('cdk diff --quiet does not print \'There were no differences\' message for stacks which have no differences', withDefaultFixture(async (fixture) => {
// GIVEN
await fixture.cdkDeploy('test-1');
// WHEN
const diff = await fixture.cdk(['diff', '--quiet', fixture.fullStackName('test-1')]);
// THEN
expect(diff).not.toContain('Stack test-1');
expect(diff).not.toContain('There were no differences');
}));
integTest('deploy stack with docker asset', withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('docker');
}));
integTest('deploy and test stack with lambda asset', withDefaultFixture(async (fixture) => {
const stackArn = await fixture.cdkDeploy('lambda', { captureStderr: false });
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: stackArn,
});
const lambdaArn = response.Stacks?.[0].Outputs?.[0].OutputValue;
if (lambdaArn === undefined) {
throw new Error('Stack did not have expected Lambda ARN output');
}
const output = await fixture.aws.lambda('invoke', {
FunctionName: lambdaArn,
});
expect(JSON.stringify(output.Payload)).toContain('dear asset');
}));
integTest('cdk ls', withDefaultFixture(async (fixture) => {
const listing = await fixture.cdk(['ls'], { captureStderr: false });
const expectedStacks = [
'conditional-resource',
'docker',
'docker-with-custom-file',
'failed',
'iam-test',
'lambda',
'missing-ssm-parameter',
'order-providing',
'outputs-test-1',
'outputs-test-2',
'param-test-1',
'param-test-2',
'param-test-3',
'termination-protection',
'test-1',
'test-2',
'with-nested-stack',
'with-nested-stack-using-parameters',
'order-consuming',
];
for (const stack of expectedStacks) {
expect(listing).toContain(fixture.fullStackName(stack));
}
}));
/**
* Type to store stack dependencies recursively
*/
type DependencyDetails = {
id: string;
dependencies: DependencyDetails[];
};
type StackDetails = {
id: string;
dependencies: DependencyDetails[];
};
integTest('cdk ls --show-dependencies --json', withDefaultFixture(async (fixture) => {
const listing = await fixture.cdk(['ls --show-dependencies --json'], { captureStderr: false });
const expectedStacks = [
{
id: 'test-1',
dependencies: [],
},
{
id: 'order-providing',
dependencies: [],
},
{
id: 'order-consuming',
dependencies: [
{
id: 'order-providing',
dependencies: [],
},
],
},
{
id: 'with-nested-stack',
dependencies: [],
},
{
id: 'list-stacks',
dependencies: [
{
id: 'list-stacks/DependentStack',
dependencies: [
{
id: 'list-stacks/DependentStack/InnerDependentStack',
dependencies: [],
},
],
},
],
},
{
id: 'list-multiple-dependent-stacks',
dependencies: [
{
id: 'list-multiple-dependent-stacks/DependentStack1',
dependencies: [],
},
{
id: 'list-multiple-dependent-stacks/DependentStack2',
dependencies: [],
},
],
},
];
function validateStackDependencies(stack: StackDetails) {
expect(listing).toContain(stack.id);
function validateDependencies(dependencies: DependencyDetails[]) {
for (const dependency of dependencies) {
expect(listing).toContain(dependency.id);
if (dependency.dependencies.length > 0) {
validateDependencies(dependency.dependencies);
}
}
}
if (stack.dependencies.length > 0) {
validateDependencies(stack.dependencies);
}
}
for (const stack of expectedStacks) {
validateStackDependencies(stack);
}
}));
integTest('cdk ls --show-dependencies --json --long', withDefaultFixture(async (fixture) => {
const listing = await fixture.cdk(['ls --show-dependencies --json --long'], { captureStderr: false });
const expectedStacks = [
{
id: 'order-providing',
name: 'order-providing',
enviroment: {
account: 'unknown-account',
region: 'unknown-region',
name: 'aws://unknown-account/unknown-region',
},
dependencies: [],
},
{
id: 'order-consuming',
name: 'order-consuming',
enviroment: {
account: 'unknown-account',
region: 'unknown-region',
name: 'aws://unknown-account/unknown-region',
},
dependencies: [
{
id: 'order-providing',
dependencies: [],
},
],
},
];
for (const stack of expectedStacks) {
expect(listing).toContain(fixture.fullStackName(stack.id));
expect(listing).toContain(fixture.fullStackName(stack.name));
expect(listing).toContain(stack.enviroment.account);
expect(listing).toContain(stack.enviroment.name);
expect(listing).toContain(stack.enviroment.region);
for (const dependency of stack.dependencies) {
expect(listing).toContain(fixture.fullStackName(dependency.id));
}
}
}));
integTest('synthing a stage with errors leads to failure', withDefaultFixture(async (fixture) => {
const output = await fixture.cdk(['synth'], {
allowErrExit: true,
modEnv: {
INTEG_STACK_SET: 'stage-with-errors',
},
});
expect(output).toContain('This is an error');
}));
integTest('synthing a stage with errors can be suppressed', withDefaultFixture(async (fixture) => {
await fixture.cdk(['synth', '--no-validation'], {
modEnv: {
INTEG_STACK_SET: 'stage-with-errors',
},
});
}));
integTest('synth --quiet can be specified in cdk.json', withDefaultFixture(async (fixture) => {
let cdkJson = JSON.parse(await fs.readFile(path.join(fixture.integTestDir, 'cdk.json'), 'utf8'));