/
ami.ts
420 lines (379 loc) · 13.5 KB
/
ami.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
import * as cdk from 'aws-cdk-lib';
import {
aws_ec2 as ec2,
aws_events as events,
aws_events_targets as events_targets,
aws_iam as iam,
aws_imagebuilder as imagebuilder,
aws_logs as logs,
aws_s3_assets as s3_assets, CustomResource,
Duration,
RemovalPolicy,
Stack,
} from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { BundledNodejsFunction } from '../../utils';
import { Architecture, IAmiBuilder, Os, RunnerAmi, RunnerVersion } from '../common';
import { ImageBuilderBase, ImageBuilderComponent, ImageBuilderObjectBase, uniqueImageBuilderName } from './common';
import { LinuxUbuntuComponents } from './linux-components';
import { WindowsComponents } from './windows-components';
/**
* Properties for {@link AmiBuilder} construct.
*/
export interface AmiBuilderProps {
/**
* Image architecture.
*
* @default Architecture.X86_64
*/
readonly architecture?: Architecture;
/**
* Image OS.
*
* @default OS.LINUX
*/
readonly os?: Os;
/**
* Version of GitHub Runners to install.
*
* @default latest version available
*/
readonly runnerVersion?: RunnerVersion;
/**
* Schedule the AMI to be rebuilt every given interval. Useful for keeping the AMI up-do-date with the latest GitHub runner version and latest OS updates.
*
* Set to zero to disable.
*
* @default Duration.days(7)
*/
readonly rebuildInterval?: Duration;
/**
* VPC where builder instances will be launched.
*
* @default default account VPC
*/
readonly vpc?: ec2.IVpc;
/**
* Security group to assign to launched builder instances.
*
* @default new security group
*
* @deprecated use {@link securityGroups}
*/
readonly securityGroup?: ec2.ISecurityGroup;
/**
* Security groups to assign to launched builder instances.
*
* @default new security group
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* Where to place the network interfaces within the VPC. Only the first matched subnet will be used.
*
* @default default VPC subnet
*/
readonly subnetSelection?: ec2.SubnetSelection;
/**
* The instance type used to build the image.
*
* @default m5.large
*/
readonly instanceType?: ec2.InstanceType;
/**
* The number of days log events are kept in CloudWatch Logs. When updating
* this property, unsetting it doesn't remove the log retention policy. To
* remove the retention policy, set the value to `INFINITE`.
*
* @default logs.RetentionDays.ONE_MONTH
*/
readonly logRetention?: logs.RetentionDays;
/**
* Removal policy for logs of image builds. If deployment fails on the custom resource, try setting this to `RemovalPolicy.RETAIN`. This way the logs can still be viewed, and you can see why the build failed.
*
* We try to not leave anything behind when removed. But sometimes a log staying behind is useful.
*
* @default RemovalPolicy.DESTROY
*/
readonly logRemovalPolicy?: RemovalPolicy;
}
/**
* Properties for AmiRecipe construct.
*/
interface AmiRecipeProperties {
/**
* Target platform. Must match builder platform.
*/
readonly platform: 'Linux' | 'Windows';
/**
* Target architecture. Must match builder platform.
*/
readonly architecture: Architecture;
/**
* Components to add to target container image.
*/
readonly components: ImageBuilderComponent[];
}
/**
* Image builder recipe for Amazon Machine Image (AMI).
*/
class AmiRecipe extends ImageBuilderObjectBase {
public readonly arn: string;
public readonly name: string;
constructor(scope: Construct, id: string, props: AmiRecipeProperties) {
super(scope, id);
const name = uniqueImageBuilderName(this);
let components = props.components.map(component => {
return {
componentArn: component.arn,
};
});
let parentAmi;
let workingDirectory;
if (props.platform == 'Linux') {
let archUrl;
if (props.architecture.is(Architecture.X86_64)) {
archUrl = 'amd64';
} else if (props.architecture.is(Architecture.ARM64)) {
archUrl = 'arm64';
} else {
throw new Error(`Unsupported architecture for parent AMI: ${props.architecture.name}`);
}
parentAmi = ec2.MachineImage.fromSsmParameter(
`/aws/service/canonical/ubuntu/server/focal/stable/current/${archUrl}/hvm/ebs-gp2/ami-id`,
{
os: ec2.OperatingSystemType.LINUX,
},
).getImage(this).imageId;
workingDirectory = '/home/runner';
} else if (props.platform == 'Windows') {
parentAmi = ec2.MachineImage.latestWindows(ec2.WindowsVersion.WINDOWS_SERVER_2022_ENGLISH_FULL_CONTAINERSLATEST).getImage(this).imageId;
workingDirectory = 'C:/'; // must exist or Image Builder fails and must not be empty or git will stall installing from the default windows\system32
} else {
throw new Error(`Unsupported AMI recipe platform: ${props.platform}`);
}
const recipe = new imagebuilder.CfnImageRecipe(this, 'Recipe', {
name: name,
version: this.version('ImageRecipe', name, {
platform: props.platform,
components,
parentAmi,
}),
parentImage: parentAmi,
components,
workingDirectory,
});
this.arn = recipe.attrArn;
this.name = name;
}
}
/**
* An AMI builder that uses AWS Image Builder to build AMIs pre-baked with all the GitHub Actions runner requirements. Builders can be used with {@link Ec2Runner}.
*
* Each builder re-runs automatically at a set interval to make sure the AMIs contain the latest versions of everything.
*
* You can create an instance of this construct to customize the AMI used to spin-up runners. Some runner providers may require custom components. Check the runner provider documentation.
*
* For example, to set a specific runner version, rebuild the image every 2 weeks, and add a few packages for the EC2 provider, use:
*
* ```
* const builder = new AmiBuilder(this, 'Builder', {
* runnerVersion: RunnerVersion.specific('2.293.0'),
* rebuildInterval: Duration.days(14),
* });
* builder.addComponent(new ImageBuilderComponent(scope, id, {
* platform: 'Linux',
* displayName: 'p7zip',
* description: 'Install some more packages',
* commands: [
* 'set -ex',
* 'apt-get install p7zip',
* ],
* }));
* new Ec2Runner(this, 'EC2 provider', {
* label: 'custom-ec2',
* amiBuilder: builder,
* });
* ```
*/
export class AmiBuilder extends ImageBuilderBase implements IAmiBuilder {
private boundAmi?: RunnerAmi;
constructor(scope: Construct, id: string, props?: AmiBuilderProps) {
super(scope, id, {
os: props?.os,
supportedOs: [Os.LINUX, Os.WINDOWS],
architecture: props?.architecture,
supportedArchitectures: [Architecture.X86_64, Architecture.ARM64],
instanceType: props?.instanceType,
vpc: props?.vpc,
securityGroups: props?.securityGroup ? [props.securityGroup] : props?.securityGroups,
subnetSelection: props?.subnetSelection,
logRemovalPolicy: props?.logRemovalPolicy,
logRetention: props?.logRetention,
runnerVersion: props?.runnerVersion,
rebuildInterval: props?.rebuildInterval,
imageTypeName: 'AMI',
});
// add all basic components
if (this.os.is(Os.WINDOWS)) {
this.addBaseWindowsComponents();
} else if (this.os.is(Os.LINUX)) {
this.addBaseLinuxComponents();
}
}
private addBaseWindowsComponents() {
this.addComponent(WindowsComponents.cloudwatchAgent(this, 'CloudWatch agent'));
this.addComponent(WindowsComponents.awsCli(this, 'AWS CLI'));
this.addComponent(WindowsComponents.githubCli(this, 'GitHub CLI'));
this.addComponent(WindowsComponents.git(this, 'git'));
this.addComponent(WindowsComponents.githubRunner(this, 'GitHub Actions Runner', this.runnerVersion));
this.addComponent(WindowsComponents.docker(this, 'Docker'));
}
private addBaseLinuxComponents() {
this.addComponent(LinuxUbuntuComponents.requiredPackages(this, 'Upgrade packages and install basics', this.architecture));
this.addComponent(LinuxUbuntuComponents.runnerUser(this, 'User', this.architecture));
this.addComponent(LinuxUbuntuComponents.awsCli(this, 'AWS CLI', this.architecture));
this.addComponent(LinuxUbuntuComponents.githubCli(this, 'GitHub CLI', this.architecture));
this.addComponent(LinuxUbuntuComponents.git(this, 'git', this.architecture));
this.addComponent(LinuxUbuntuComponents.githubRunner(this, 'GitHub Actions Runner', this.runnerVersion, this.architecture));
this.addComponent(LinuxUbuntuComponents.docker(this, 'Docker', this.architecture));
}
/**
* Add a component to be installed before any other components. Useful for required system settings like certificates or proxy settings.
* @param component
*/
prependComponent(component: ImageBuilderComponent) {
if (this.boundAmi) {
throw new Error('AMI is already bound. Use this method before passing the builder to a runner provider.');
}
if (component.platform != this.platform) {
throw new Error('Component platform doesn\'t match builder platform');
}
this.components = [component].concat(this.components);
}
/**
* Add a component to be installed.
* @param component
*/
addComponent(component: ImageBuilderComponent) {
if (this.boundAmi) {
throw new Error('AMI is already bound. Use this method before passing the builder to a runner provider.');
}
if (component.platform != this.platform) {
throw new Error('Component platform doesn\'t match builder platform');
}
this.components.push(component);
}
/**
* Add extra trusted certificates. This helps deal with self-signed certificates for GitHub Enterprise Server.
*
* @param path path to directory containing a file called certs.pem containing all the required certificates
*/
public addExtraCertificates(path: string) {
this.prependComponent(new ImageBuilderComponent(this, 'Extra Certs', {
platform: this.platform,
displayName: 'GitHub Actions Runner',
description: 'Install latest version of GitHub Actions Runner',
commands: [
'$ErrorActionPreference = \'Stop\'',
'Import-Certificate -FilePath certs\\certs.pem -CertStoreLocation Cert:\\LocalMachine\\Root',
],
assets: [
{
path: 'certs',
asset: new s3_assets.Asset(this, 'Extra Certs Asset', { path }),
},
],
}));
}
/**
* Called by IRunnerProvider to finalize settings and create the AMI builder.
*/
bind(): RunnerAmi {
if (this.boundAmi) {
return this.boundAmi;
}
const launchTemplate = new ec2.LaunchTemplate(this, 'Launch template');
const stackName = cdk.Stack.of(this).stackName;
const builderName = this.node.path;
const dist = new imagebuilder.CfnDistributionConfiguration(this, 'Distribution', {
name: uniqueImageBuilderName(this),
description: this.description,
distributions: [
{
region: Stack.of(this).region,
amiDistributionConfiguration: {
Name: `${cdk.Names.uniqueResourceName(this, {
maxLength: 100,
separator: '-',
allowedSpecialCharacters: '_-',
})}-{{ imagebuilder:buildDate }}`,
AmiTags: {
'Name': this.node.id,
'GitHubRunners:Stack': stackName,
'GitHubRunners:Builder': builderName,
},
},
launchTemplateConfigurations: [
{
launchTemplateId: launchTemplate.launchTemplateId,
},
],
},
],
});
const recipe = new AmiRecipe(this, 'Ami Recipe', {
platform: this.platform,
components: this.components,
architecture: this.architecture,
});
const log = this.createLog(recipe.name);
const infra = this.createInfrastructure([
iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'),
iam.ManagedPolicy.fromAwsManagedPolicyName('EC2InstanceProfileForImageBuilder'),
]);
this.createImage(infra, dist, log, recipe.arn, undefined);
this.createPipeline(infra, dist, log, recipe.arn, undefined);
this.boundAmi = {
launchTemplate: launchTemplate,
architecture: this.architecture,
os: this.os,
logGroup: log,
runnerVersion: this.runnerVersion,
};
this.imageCleaner(launchTemplate, stackName, builderName);
return this.boundAmi;
}
private imageCleaner(launchTemplate: ec2.LaunchTemplate, stackName: string, builderName: string) {
const deleter = BundledNodejsFunction.singleton(this, 'delete-ami', {
initialPolicy: [
new iam.PolicyStatement({
actions: ['ec2:DescribeLaunchTemplateVersions', 'ec2:DescribeImages', 'ec2:DeregisterImage'],
resources: ['*'],
}),
],
timeout: cdk.Duration.minutes(5),
});
// delete old AMIs on schedule
const eventRule = new events.Rule(this, 'Delete AMI Schedule', {
schedule: events.Schedule.rate(cdk.Duration.days(1)),
description: `Delete old AMIs for ${builderName}`,
});
eventRule.addTarget(new events_targets.LambdaFunction(deleter, {
event: events.RuleTargetInput.fromObject({
RequestType: 'Scheduled',
LaunchTemplateId: launchTemplate.launchTemplateId,
StackName: stackName,
BuilderName: builderName,
}),
}));
// delete all AMIs when this construct is removed
new CustomResource(this, 'AMI Deleter', {
serviceToken: deleter.functionArn,
resourceType: 'Custom::AmiDeleter',
properties: {
StackName: stackName,
BuilderName: builderName,
},
});
}
}