-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathimage-asset.test.ts
461 lines (393 loc) · 18.6 KB
/
image-asset.test.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
import * as fs from 'fs';
import * as path from 'path';
import { Template } from '@aws-cdk/assertions';
import * as iam from '@aws-cdk/aws-iam';
import { describeDeprecated, testDeprecated, testFutureBehavior } from '@aws-cdk/cdk-build-tools';
import * as cxschema from '@aws-cdk/cloud-assembly-schema';
import { App, DefaultStackSynthesizer, IgnoreMode, Lazy, LegacyStackSynthesizer, Stack, Stage } from '@aws-cdk/core';
import * as cxapi from '@aws-cdk/cx-api';
import { DockerImageAsset, NetworkMode } from '../lib';
/* eslint-disable quote-props */
const DEMO_IMAGE_ASSET_HASH = '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14';
const flags = { [cxapi.DOCKER_IGNORE_SUPPORT]: true };
describe('image asset', () => {
testFutureBehavior('test instantiating Asset Image', flags, App, (app) => {
// WHEN
const stack = new Stack(app);
new DockerImageAsset(stack, 'Image', {
directory: path.join(__dirname, 'demo-image'),
});
// THEN
const asm = app.synth();
const artifact = asm.getStackArtifact(stack.artifactId);
expect(artifact.template).toEqual({});
expect(artifact.assets).toEqual([
{
repositoryName: 'aws-cdk/assets',
imageTag: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
id: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
packaging: 'container-image',
path: 'asset.0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
sourceHash: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
},
]);
});
testFutureBehavior('with build args', flags, App, (app) => {
// WHEN
const stack = new Stack(app);
new DockerImageAsset(stack, 'Image', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: {
a: 'b',
},
});
// THEN
const assetMetadata = stack.node.metadataEntry.find(({ type }) => type === cxschema.ArtifactMetadataEntryType.ASSET);
expect(assetMetadata && (assetMetadata.data as cxschema.ContainerImageAssetMetadataEntry).buildArgs).toEqual({ a: 'b' });
});
testFutureBehavior('with hash options', flags, App, (app) => {
// WHEN
const stack = new Stack(app);
new DockerImageAsset(stack, 'Image1', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: {
a: 'b',
},
invalidation: {
buildArgs: false,
},
});
new DockerImageAsset(stack, 'Image2', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: {
a: 'c',
},
invalidation: {
buildArgs: false,
},
});
new DockerImageAsset(stack, 'Image3', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: {
a: 'b',
},
});
// THEN
const asm = app.synth();
const artifact = asm.getStackArtifact(stack.artifactId);
expect(artifact.template).toEqual({});
expect(artifact.assets).toEqual([
{
buildArgs: { 'a': 'b' },
id: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
imageTag: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
packaging: 'container-image',
path: 'asset.0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
repositoryName: 'aws-cdk/assets',
sourceHash: '0a3355be12051c9984bf2b0b2bba4e6ea535968e5b6e7396449701732fe5ed14',
},
{
buildArgs: { 'a': 'b' },
id: '7f3aa0a36ecd282884e11463b3fde119d25d1ed424f934300f0c7b9cf6f63947',
imageTag: '7f3aa0a36ecd282884e11463b3fde119d25d1ed424f934300f0c7b9cf6f63947',
packaging: 'container-image',
path: 'asset.7f3aa0a36ecd282884e11463b3fde119d25d1ed424f934300f0c7b9cf6f63947',
repositoryName: 'aws-cdk/assets',
sourceHash: '7f3aa0a36ecd282884e11463b3fde119d25d1ed424f934300f0c7b9cf6f63947',
},
]);
});
testFutureBehavior('with target', flags, App, (app) => {
// WHEN
const stack = new Stack(app);
new DockerImageAsset(stack, 'Image', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: {
a: 'b',
},
target: 'a-target',
});
// THEN
const assetMetadata = stack.node.metadataEntry.find(({ type }) => type === cxschema.ArtifactMetadataEntryType.ASSET);
expect(assetMetadata && (assetMetadata.data as cxschema.ContainerImageAssetMetadataEntry).target).toEqual('a-target');
});
testFutureBehavior('with file', flags, App, (app) => {
// GIVEN
const stack = new Stack(app);
const directoryPath = path.join(__dirname, 'demo-image-custom-docker-file');
// WHEN
new DockerImageAsset(stack, 'Image', {
directory: directoryPath,
file: 'Dockerfile.Custom',
});
// THEN
const assetMetadata = stack.node.metadataEntry.find(({ type }) => type === cxschema.ArtifactMetadataEntryType.ASSET);
expect(assetMetadata && (assetMetadata.data as cxschema.ContainerImageAssetMetadataEntry).file).toEqual('Dockerfile.Custom');
});
testFutureBehavior('with networkMode', flags, App, (app) => {
// GIVEN
const stack = new Stack(app);
// WHEN
new DockerImageAsset(stack, 'Image', {
directory: path.join(__dirname, 'demo-image'),
networkMode: NetworkMode.DEFAULT,
});
// THEN
const assetMetadata = stack.node.metadataEntry.find(({ type }) => type === cxschema.ArtifactMetadataEntryType.ASSET);
expect(assetMetadata && (assetMetadata.data as cxschema.ContainerImageAssetMetadataEntry).networkMode).toEqual('default');
});
testFutureBehavior('asset.repository.grantPull can be used to grant a principal permissions to use the image', flags, App, (app) => {
// GIVEN
const stack = new Stack(app);
const user = new iam.User(stack, 'MyUser');
const asset = new DockerImageAsset(stack, 'Image', {
directory: path.join(__dirname, 'demo-image'),
});
// WHEN
asset.repository.grantPull(user);
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
'Statement': [
{
'Action': [
'ecr:BatchCheckLayerAvailability',
'ecr:GetDownloadUrlForLayer',
'ecr:BatchGetImage',
],
'Effect': 'Allow',
'Resource': {
'Fn::Join': [
'',
[
'arn:',
{
'Ref': 'AWS::Partition',
},
':ecr:',
{
'Ref': 'AWS::Region',
},
':',
{
'Ref': 'AWS::AccountId',
},
':repository/aws-cdk/assets',
],
],
},
},
{
'Action': 'ecr:GetAuthorizationToken',
'Effect': 'Allow',
'Resource': '*',
},
],
'Version': '2012-10-17',
},
'PolicyName': 'MyUserDefaultPolicy7B897426',
'Users': [
{
'Ref': 'MyUserDC45028B',
},
],
});
});
test('fails if the directory does not exist', () => {
const stack = new Stack();
// THEN
expect(() => {
new DockerImageAsset(stack, 'MyAsset', {
directory: `/does/not/exist/${Math.floor(Math.random() * 9999)}`,
});
}).toThrow(/Cannot find image directory at/);
});
test('fails if the directory does not contain a Dockerfile', () => {
const stack = new Stack();
// THEN
expect(() => {
new DockerImageAsset(stack, 'Asset', {
directory: __dirname,
});
}).toThrow(/Cannot find file at/);
});
test('fails if the file does not exist', () => {
const stack = new Stack();
// THEN
expect(() => {
new DockerImageAsset(stack, 'Asset', {
directory: __dirname,
file: 'doesnt-exist',
});
}).toThrow(/Cannot find file at/);
});
testFutureBehavior('docker directory is staged if asset staging is enabled', flags, App, (app) => {
const stack = new Stack(app);
const image = new DockerImageAsset(stack, 'MyAsset', {
directory: path.join(__dirname, 'demo-image'),
});
const session = app.synth();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'Dockerfile'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'index.py'))).toBeDefined();
});
describeDeprecated('docker ignore option', () => {
// The 'ignoreMode' property is both deprecated and not deprecated in DockerImageAssetProps interface.
// The interface through a complex set of inheritance chain has a 'ignoreMode' prop that is deprecated
// and another 'ignoreMode' prop that is not deprecated.
// Using a 'describeDeprecated' block here since there's no way to work around this craziness.
// When the deprecated property is removed source code, this block can be dropped.
testFutureBehavior('docker directory is staged without files specified in .dockerignore', flags, App, (app) => {
testDockerDirectoryIsStagedWithoutFilesSpecifiedInDockerignore(app);
});
testFutureBehavior('docker directory is staged without files specified in .dockerignore with IgnoreMode.GLOB', flags, App, (app) => {
testDockerDirectoryIsStagedWithoutFilesSpecifiedInDockerignore(app, IgnoreMode.GLOB);
});
});
testFutureBehavior('docker directory is staged with allow-listed files specified in .dockerignore', flags, App, (app) => {
const stack = new Stack(app);
const image = new DockerImageAsset(stack, 'MyAsset', {
directory: path.join(__dirname, 'allow-listed-image'),
});
const session = app.synth();
// Only the files exempted above should be included.
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, '.dockerignore'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'Dockerfile'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'index.py'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'foobar.txt'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory', 'baz.txt'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'node_modules'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'node_modules', 'one'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'node_modules', 'some_dep'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'node_modules', 'some_dep', 'file'))).toBeDefined();
});
testFutureBehavior('docker directory is staged without files specified in exclude option', flags, App, (app) => {
testDockerDirectoryIsStagedWithoutFilesSpecifiedInExcludeOption(app);
});
testFutureBehavior('docker directory is staged without files specified in exclude option with IgnoreMode.GLOB', flags, App, (app) => {
testDockerDirectoryIsStagedWithoutFilesSpecifiedInExcludeOption(app, IgnoreMode.GLOB);
});
test('fails if using tokens in build args keys or values', () => {
// GIVEN
const stack = new Stack();
const token = Lazy.string({ produce: () => 'foo' });
const expected = /Cannot use tokens in keys or values of "buildArgs" since they are needed before deployment/;
// THEN
expect(() => new DockerImageAsset(stack, 'MyAsset1', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: { [token]: 'value' },
})).toThrow(expected);
expect(() => new DockerImageAsset(stack, 'MyAsset2', {
directory: path.join(__dirname, 'demo-image'),
buildArgs: { key: token },
})).toThrow(expected);
});
testDeprecated('fails if using token as repositoryName', () => {
// GIVEN
const stack = new Stack();
const token = Lazy.string({ produce: () => 'foo' });
// THEN
expect(() => new DockerImageAsset(stack, 'MyAsset1', {
directory: path.join(__dirname, 'demo-image'),
repositoryName: token,
})).toThrow(/Cannot use Token as value of 'repositoryName'/);
});
testFutureBehavior('docker build options are included in the asset id', flags, App, (app) => {
// GIVEN
const stack = new Stack(app);
const directory = path.join(__dirname, 'demo-image-custom-docker-file');
const asset1 = new DockerImageAsset(stack, 'Asset1', { directory });
const asset2 = new DockerImageAsset(stack, 'Asset2', { directory, file: 'Dockerfile.Custom' });
const asset3 = new DockerImageAsset(stack, 'Asset3', { directory, target: 'NonDefaultTarget' });
const asset4 = new DockerImageAsset(stack, 'Asset4', { directory, buildArgs: { opt1: '123', opt2: 'boom' } });
const asset5 = new DockerImageAsset(stack, 'Asset5', { directory, file: 'Dockerfile.Custom', target: 'NonDefaultTarget' });
const asset6 = new DockerImageAsset(stack, 'Asset6', { directory, extraHash: 'random-extra' });
expect(asset1.assetHash).toEqual('13248c55633f3b198a628bb2ea4663cb5226f8b2801051bd0c725950266fd590');
expect(asset2.assetHash).toEqual('36bf205fb9adc5e45ba1c8d534158a0aed96d190eff433af1d90f3b94f96e751');
expect(asset3.assetHash).toEqual('4c85bd70e73117b7129c2defbe6dc40a8a3872329f4ddca18d75afa671b38276');
expect(asset4.assetHash).toEqual('8a91219a7bb0f58b3282dd84acbf4c03c49c765be54ffb7b125be6a50b6c5645');
expect(asset5.assetHash).toEqual('c02bfba13b2e7e1ff5c778a76e10296b9e8d17f7f8252d097f4170ae04ce0eb4');
expect(asset6.assetHash).toEqual('3528d6838647a5e9011b0f35aec514d03ad11af05a94653cdcf4dacdbb070a06');
});
testDeprecated('repositoryName is included in the asset id', () => {
const stack = new Stack();
const directory = path.join(__dirname, 'demo-image-custom-docker-file');
const asset1 = new DockerImageAsset(stack, 'Asset1', { directory });
const asset2 = new DockerImageAsset(stack, 'Asset2', { directory, repositoryName: 'foo' });
expect(asset1.assetHash).toEqual('91cd042be26211c28488a6994327fc579e75e355d9d3bf7043fa6a0bc8ad4265');
expect(asset2.assetHash).toEqual('6a6cab989dda908fa3d132d58f402f714d79858f3c89473f2b050096954e6827');
});
});
function testDockerDirectoryIsStagedWithoutFilesSpecifiedInDockerignore(app: App, ignoreMode?: IgnoreMode) {
const stack = new Stack(app);
const image = new DockerImageAsset(stack, 'MyAsset', {
ignoreMode,
directory: path.join(__dirname, 'dockerignore-image'),
});
const session = app.synth();
// .dockerignore itself should be included in output to be processed during docker build
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, '.dockerignore'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'Dockerfile'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'index.py'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'foobar.txt'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory', 'baz.txt'))).toBeDefined();
}
function testDockerDirectoryIsStagedWithoutFilesSpecifiedInExcludeOption(app: App, ignoreMode?: IgnoreMode) {
const stack = new Stack(app);
const image = new DockerImageAsset(stack, 'MyAsset', {
directory: path.join(__dirname, 'dockerignore-image'),
exclude: ['subdirectory'],
ignoreMode,
});
const session = app.synth();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, '.dockerignore'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'Dockerfile'))).toBeDefined();
expect(fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'index.py'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'foobar.txt'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory'))).toBeDefined();
expect(!fs.existsSync(path.join(session.directory, `asset.${image.assetHash}`, 'subdirectory', 'baz.txt'))).toBeDefined();
}
testFutureBehavior('nested assemblies share assets: legacy synth edition', flags, App, (app) => {
// GIVEN
const stack1 = new Stack(new Stage(app, 'Stage1'), 'Stack', { synthesizer: new LegacyStackSynthesizer() });
const stack2 = new Stack(new Stage(app, 'Stage2'), 'Stack', { synthesizer: new LegacyStackSynthesizer() });
// WHEN
new DockerImageAsset(stack1, 'Image', { directory: path.join(__dirname, 'demo-image') });
new DockerImageAsset(stack2, 'Image', { directory: path.join(__dirname, 'demo-image') });
// THEN
const assembly = app.synth();
// Read the assets from the stack metadata
for (const stageName of ['Stage1', 'Stage2']) {
const stackArtifact = assembly.getNestedAssembly(`assembly-${stageName}`).artifacts.filter(isStackArtifact)[0];
const assetMeta = stackArtifact.findMetadataByType(cxschema.ArtifactMetadataEntryType.ASSET);
expect(assetMeta[0]).toEqual(
expect.objectContaining({
data: expect.objectContaining({
path: `../asset.${DEMO_IMAGE_ASSET_HASH}`,
}),
}),
);
}
});
testFutureBehavior('nested assemblies share assets: default synth edition', flags, App, (app) => {
// GIVEN
const stack1 = new Stack(new Stage(app, 'Stage1'), 'Stack', { synthesizer: new DefaultStackSynthesizer() });
const stack2 = new Stack(new Stage(app, 'Stage2'), 'Stack', { synthesizer: new DefaultStackSynthesizer() });
// WHEN
new DockerImageAsset(stack1, 'Image', { directory: path.join(__dirname, 'demo-image') });
new DockerImageAsset(stack2, 'Image', { directory: path.join(__dirname, 'demo-image') });
// THEN
const assembly = app.synth();
// Read the asset manifests to verify the file paths
for (const stageName of ['Stage1', 'Stage2']) {
const manifestArtifact = assembly.getNestedAssembly(`assembly-${stageName}`).artifacts.filter(cxapi.AssetManifestArtifact.isAssetManifestArtifact)[0];
const manifest = JSON.parse(fs.readFileSync(manifestArtifact.file, { encoding: 'utf-8' }));
expect(manifest.dockerImages[DEMO_IMAGE_ASSET_HASH].source).toEqual({
directory: `../asset.${DEMO_IMAGE_ASSET_HASH}`,
});
}
});
function isStackArtifact(x: any): x is cxapi.CloudFormationStackArtifact {
return x instanceof cxapi.CloudFormationStackArtifact;
}