-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (89 loc) · 2.91 KB
/
index.js
File metadata and controls
99 lines (89 loc) · 2.91 KB
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
const { getInput, setFailed } = require('@actions/core')
const AWS = require('aws-sdk')
async function run () {
try {
const repositoryName = getInput('DOCKER_REPO_NAME', { required: true })
const daysBeforeExpiringUntaggedImages = getInput('NUM_DAYS_BEFORE_EXPIRING_UNTAGGED_IMAGES', { required: true })
const tagPrefix = getInput('TAG_PREFIX')
const numImages = getInput('NUM_TAGGED_IMAGES_TO_RETAIN')
if (tagPrefix && !numImages) {
setFailed('If TAG_PREFIX is provided, NUM_TAGGED_IMAGES_TO_RETAIN is required')
return
}
if (!tagPrefix && numImages) {
setFailed('If NUM_TAGGED_IMAGES_TO_RETAIN is provided, TAG_PREFIX is required')
return
}
const ecr = new AWS.ECR({ apiVersion: '2015-09-21', region: process.env.AWS_REGION })
let repositoryExists = false
try {
await ecr.describeRepositories({ repositoryNames: [repositoryName] }).promise()
repositoryExists = true
} catch {}
if (repositoryExists) {
console.log('Repository already exists 🎉')
return
}
console.log('Repository does not exist. Creating...')
await ecr.createRepository({ repositoryName, imageScanningConfiguration: { scanOnPush: true } }).promise()
const accessPolicyText = JSON.stringify({
Version: '2008-10-17',
Statement: [
{
Sid: 'pull',
Effect: 'Allow',
Principal: {
Service: 'codebuild.amazonaws.com'
},
Action: [
'ecr:GetDownloadUrlForLayer',
'ecr:BatchGetImage',
'ecr:BatchCheckLayerAvailability'
]
}
]
})
const lifecyclePolicy = {
rules: [
{
rulePriority: 10,
description: `Expire untagged images after ${daysBeforeExpiringUntaggedImages} days`,
selection: {
tagStatus: 'untagged',
countType: 'sinceImagePushed',
countUnit: 'days',
countNumber: parseInt(daysBeforeExpiringUntaggedImages, 10)
},
action: {
type: 'expire'
}
}
]
}
if (tagPrefix && numImages) {
lifecyclePolicy.rules.push({
rulePriority: 20,
description: 'Expire old images as new ones are built',
selection: {
tagStatus: 'tagged',
tagPrefixList: [tagPrefix],
countType: 'imageCountMoreThan',
countNumber: parseInt(numImages, 10)
},
action: {
type: 'expire'
}
})
}
const lifecyclePolicyText = JSON.stringify(lifecyclePolicy)
console.log('Applying repository access and lifecycle policies...')
await Promise.all([
ecr.setRepositoryPolicy({ repositoryName, policyText: accessPolicyText }).promise(),
ecr.putLifecyclePolicy({ repositoryName, lifecyclePolicyText }).promise()
])
console.log('Done! 🎉')
} catch (e) {
setFailed(e.message || e)
}
}
run()