-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathrepository.ts
498 lines (433 loc) · 15.5 KB
/
repository.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
import events = require('@aws-cdk/aws-events');
import iam = require('@aws-cdk/aws-iam');
import { Construct, IConstruct, IResource, Lazy, RemovalPolicy, Resource, Stack, Token } from '@aws-cdk/core';
import { CfnRepository } from './ecr.generated';
import { LifecycleRule, TagStatus } from './lifecycle';
/**
* Represents an ECR repository.
*/
export interface IRepository extends IResource {
/**
* The name of the repository
* @attribute
*/
readonly repositoryName: string;
/**
* The ARN of the repository
* @attribute
*/
readonly repositoryArn: string;
/**
* The URI of this repository (represents the latest image):
*
* ACCOUNT.dkr.ecr.REGION.amazonaws.com/REPOSITORY
*
* @attribute
*/
readonly repositoryUri: string;
/**
* Returns the URI of the repository for a certain tag. Can be used in `docker push/pull`.
*
* ACCOUNT.dkr.ecr.REGION.amazonaws.com/REPOSITORY[:TAG]
*
* @param tag Image tag to use (tools usually default to "latest" if omitted)
*/
repositoryUriForTag(tag?: string): string;
/**
* Add a policy statement to the repository's resource policy
*/
addToResourcePolicy(statement: iam.PolicyStatement): void;
/**
* Grant the given principal identity permissions to perform the actions on this repository
*/
grant(grantee: iam.IGrantable, ...actions: string[]): iam.Grant;
/**
* Grant the given identity permissions to pull images in this repository.
*/
grantPull(grantee: iam.IGrantable): iam.Grant;
/**
* Grant the given identity permissions to pull and push images to this repository.
*/
grantPullPush(grantee: iam.IGrantable): iam.Grant;
/**
* Define a CloudWatch event that triggers when something happens to this repository
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
onCloudTrailEvent(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines an AWS CloudWatch event rule that can trigger a target when an image is pushed to this
* repository.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
onCloudTrailImagePushed(id: string, options?: OnCloudTrailImagePushedOptions): events.Rule;
}
/**
* Base class for ECR repository. Reused between imported repositories and owned repositories.
*/
export abstract class RepositoryBase extends Resource implements IRepository {
/**
* The name of the repository
*/
public abstract readonly repositoryName: string;
/**
* The ARN of the repository
*/
public abstract readonly repositoryArn: string;
/**
* Add a policy statement to the repository's resource policy
*/
public abstract addToResourcePolicy(statement: iam.PolicyStatement): void;
/**
* The URI of this repository (represents the latest image):
*
* ACCOUNT.dkr.ecr.REGION.amazonaws.com/REPOSITORY
*
*/
public get repositoryUri() {
return this.repositoryUriForTag();
}
/**
* Returns the URL of the repository. Can be used in `docker push/pull`.
*
* ACCOUNT.dkr.ecr.REGION.amazonaws.com/REPOSITORY[:TAG]
*
* @param tag Optional image tag
*/
public repositoryUriForTag(tag?: string): string {
const tagSuffix = tag ? `:${tag}` : '';
const parts = this.stack.parseArn(this.repositoryArn);
return `${parts.account}.dkr.ecr.${parts.region}.${this.stack.urlSuffix}/${this.repositoryName}${tagSuffix}`;
}
/**
* Define a CloudWatch event that triggers when something happens to this repository
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
public onCloudTrailEvent(id: string, options: events.OnEventOptions = {}): events.Rule {
const rule = new events.Rule(this, id, options);
rule.addTarget(options.target);
rule.addEventPattern({
source: ['aws.ecr'],
detailType: ['AWS API Call via CloudTrail'],
detail: {
requestParameters: {
repositoryName: [this.repositoryName],
}
}
});
return rule;
}
/**
* Defines an AWS CloudWatch event rule that can trigger a target when an image is pushed to this
* repository.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
public onCloudTrailImagePushed(id: string, options: OnCloudTrailImagePushedOptions = {}): events.Rule {
const rule = this.onCloudTrailEvent(id, options);
rule.addEventPattern({
detail: {
eventName: ['PutImage'],
requestParameters: {
imageTag: options.imageTag ? [options.imageTag] : undefined,
},
},
});
return rule;
}
/**
* Grant the given principal identity permissions to perform the actions on this repository
*/
public grant(grantee: iam.IGrantable, ...actions: string[]) {
return iam.Grant.addToPrincipalOrResource({
grantee,
actions,
resourceArns: [this.repositoryArn],
resourceSelfArns: [],
resource: this,
});
}
/**
* Grant the given identity permissions to use the images in this repository
*/
public grantPull(grantee: iam.IGrantable) {
const ret = this.grant(grantee, "ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage");
iam.Grant.addToPrincipal({
grantee,
actions: ["ecr:GetAuthorizationToken"],
resourceArns: ['*'],
scope: this,
});
return ret;
}
/**
* Grant the given identity permissions to pull and push images to this repository.
*/
public grantPullPush(grantee: iam.IGrantable) {
this.grantPull(grantee);
return this.grant(grantee,
"ecr:PutImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload");
}
}
/**
* Options for the onCloudTrailImagePushed method
*/
export interface OnCloudTrailImagePushedOptions extends events.OnEventOptions {
/**
* Only watch changes to this image tag
*
* @default - Watch changes to all tags
*/
readonly imageTag?: string;
}
export interface RepositoryProps {
/**
* Name for this repository
*
* @default Automatically generated name.
*/
readonly repositoryName?: string;
/**
* Life cycle rules to apply to this registry
*
* @default No life cycle rules
*/
readonly lifecycleRules?: LifecycleRule[];
/**
* The AWS account ID associated with the registry that contains the repository.
*
* @see https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_PutLifecyclePolicy.html
* @default The default registry is assumed.
*/
readonly lifecycleRegistryId?: string;
/**
* Determine what happens to the repository when the resource/stack is deleted.
*
* @default RemovalPolicy.Retain
*/
readonly removalPolicy?: RemovalPolicy;
}
export interface RepositoryAttributes {
readonly repositoryName: string;
readonly repositoryArn: string;
}
/**
* Define an ECR repository
*/
export class Repository extends RepositoryBase {
/**
* Import a repository
*/
public static fromRepositoryAttributes(scope: Construct, id: string, attrs: RepositoryAttributes): IRepository {
class Import extends RepositoryBase {
public readonly repositoryName = attrs.repositoryName;
public readonly repositoryArn = attrs.repositoryArn;
public addToResourcePolicy(_statement: iam.PolicyStatement) {
// dropped
}
}
return new Import(scope, id);
}
public static fromRepositoryArn(scope: Construct, id: string, repositoryArn: string): IRepository {
// if repositoryArn is a token, the repository name is also required. this is because
// repository names can include "/" (e.g. foo/bar/myrepo) and it is impossible to
// parse the name from an ARN using CloudFormation's split/select.
if (Token.isUnresolved(repositoryArn)) {
throw new Error('"repositoryArn" is a late-bound value, and therefore "repositoryName" is required. Use `fromRepositoryAttributes` instead');
}
const repositoryName = repositoryArn.split('/').slice(1).join('/');
class Import extends RepositoryBase {
public repositoryName = repositoryName;
public repositoryArn = repositoryArn;
public addToResourcePolicy(_statement: iam.PolicyStatement): void {
// dropped
}
}
return new Import(scope, id);
}
public static fromRepositoryName(scope: Construct, id: string, repositoryName: string): IRepository {
class Import extends RepositoryBase {
public repositoryName = repositoryName;
public repositoryArn = Repository.arnForLocalRepository(repositoryName, scope);
public addToResourcePolicy(_statement: iam.PolicyStatement): void {
// dropped
}
}
return new Import(scope, id);
}
/**
* Returns an ECR ARN for a repository that resides in the same account/region
* as the current stack.
*/
public static arnForLocalRepository(repositoryName: string, scope: IConstruct): string {
return Stack.of(scope).formatArn({
service: 'ecr',
resource: 'repository',
resourceName: repositoryName
});
}
public readonly repositoryName: string;
public readonly repositoryArn: string;
private readonly lifecycleRules = new Array<LifecycleRule>();
private readonly registryId?: string;
private policyDocument?: iam.PolicyDocument;
constructor(scope: Construct, id: string, props: RepositoryProps = {}) {
super(scope, id, {
physicalName: props.repositoryName,
});
const resource = new CfnRepository(this, 'Resource', {
repositoryName: this.physicalName,
// It says "Text", but they actually mean "Object".
repositoryPolicyText: Lazy.anyValue({ produce: () => this.policyDocument }),
lifecyclePolicy: Lazy.anyValue({ produce: () => this.renderLifecyclePolicy() }),
});
resource.applyRemovalPolicy(props.removalPolicy);
this.registryId = props.lifecycleRegistryId;
if (props.lifecycleRules) {
props.lifecycleRules.forEach(this.addLifecycleRule.bind(this));
}
this.repositoryName = this.getResourceNameAttribute(resource.ref);
this.repositoryArn = this.getResourceArnAttribute(resource.attrArn, {
service: 'ecr',
resource: 'repository',
resourceName: this.physicalName,
});
}
public addToResourcePolicy(statement: iam.PolicyStatement) {
if (this.policyDocument === undefined) {
this.policyDocument = new iam.PolicyDocument();
}
this.policyDocument.addStatements(statement);
}
/**
* Add a life cycle rule to the repository
*
* Life cycle rules automatically expire images from the repository that match
* certain conditions.
*/
public addLifecycleRule(rule: LifecycleRule) {
// Validate rule here so users get errors at the expected location
if (rule.tagStatus === undefined) {
rule = { ...rule, tagStatus: rule.tagPrefixList === undefined ? TagStatus.ANY : TagStatus.TAGGED };
}
if (rule.tagStatus === TagStatus.TAGGED && (rule.tagPrefixList === undefined || rule.tagPrefixList.length === 0)) {
throw new Error('TagStatus.Tagged requires the specification of a tagPrefixList');
}
if (rule.tagStatus !== TagStatus.TAGGED && rule.tagPrefixList !== undefined) {
throw new Error('tagPrefixList can only be specified when tagStatus is set to Tagged');
}
if ((rule.maxImageAge !== undefined) === (rule.maxImageCount !== undefined)) {
throw new Error(`Life cycle rule must contain exactly one of 'maxImageAge' and 'maxImageCount', got: ${JSON.stringify(rule)}`);
}
if (rule.tagStatus === TagStatus.ANY && this.lifecycleRules.filter(r => r.tagStatus === TagStatus.ANY).length > 0) {
throw new Error('Life cycle can only have one TagStatus.Any rule');
}
this.lifecycleRules.push({ ...rule });
}
/**
* Render the life cycle policy object
*/
private renderLifecyclePolicy(): CfnRepository.LifecyclePolicyProperty | undefined {
const stack = Stack.of(this);
let lifecyclePolicyText: any;
if (this.lifecycleRules.length === 0 && !this.registryId) { return undefined; }
if (this.lifecycleRules.length > 0) {
lifecyclePolicyText = JSON.stringify(stack.resolve({
rules: this.orderedLifecycleRules().map(renderLifecycleRule),
}));
}
return {
lifecyclePolicyText,
registryId: this.registryId,
};
}
/**
* Return life cycle rules with automatic ordering applied.
*
* Also applies validation of the 'any' rule.
*/
private orderedLifecycleRules(): LifecycleRule[] {
if (this.lifecycleRules.length === 0) { return []; }
const prioritizedRules = this.lifecycleRules.filter(r => r.rulePriority !== undefined && r.tagStatus !== TagStatus.ANY);
const autoPrioritizedRules = this.lifecycleRules.filter(r => r.rulePriority === undefined && r.tagStatus !== TagStatus.ANY);
const anyRules = this.lifecycleRules.filter(r => r.tagStatus === TagStatus.ANY);
if (anyRules.length > 0 && anyRules[0].rulePriority !== undefined && autoPrioritizedRules.length > 0) {
// Supporting this is too complex for very little value. We just prohibit it.
throw new Error("Cannot combine prioritized TagStatus.Any rule with unprioritized rules. Remove rulePriority from the 'Any' rule.");
}
const prios = prioritizedRules.map(r => r.rulePriority!);
let autoPrio = (prios.length > 0 ? Math.max(...prios) : 0) + 1;
const ret = new Array<LifecycleRule>();
for (const rule of prioritizedRules.concat(autoPrioritizedRules).concat(anyRules)) {
ret.push({
...rule,
rulePriority: rule.rulePriority !== undefined ? rule.rulePriority : autoPrio++
});
}
// Do validation on the final array--might still be wrong because the user supplied all prios, but incorrectly.
validateAnyRuleLast(ret);
return ret;
}
}
function validateAnyRuleLast(rules: LifecycleRule[]) {
const anyRules = rules.filter(r => r.tagStatus === TagStatus.ANY);
if (anyRules.length === 1) {
const maxPrio = Math.max(...rules.map(r => r.rulePriority!));
if (anyRules[0].rulePriority !== maxPrio) {
throw new Error(`TagStatus.Any rule must have highest priority, has ${anyRules[0].rulePriority} which is smaller than ${maxPrio}`);
}
}
}
/**
* Render the lifecycle rule to JSON
*/
function renderLifecycleRule(rule: LifecycleRule) {
return {
rulePriority: rule.rulePriority,
description: rule.description,
selection: {
tagStatus: rule.tagStatus || TagStatus.ANY,
tagPrefixList: rule.tagPrefixList,
countType: rule.maxImageAge !== undefined ? CountType.SINCE_IMAGE_PUSHED : CountType.IMAGE_COUNT_MORE_THAN,
countNumber: rule.maxImageAge !== undefined ? rule.maxImageAge.toDays() : rule.maxImageCount,
countUnit: rule.maxImageAge !== undefined ? 'days' : undefined,
},
action: {
type: 'expire'
}
};
}
/**
* Select images based on counts
*/
const enum CountType {
/**
* Set a limit on the number of images in your repository
*/
IMAGE_COUNT_MORE_THAN = 'imageCountMoreThan',
/**
* Set an age limit on the images in your repository
*/
SINCE_IMAGE_PUSHED = 'sinceImagePushed',
}