@guardian/cdk 59.4.0 → 59.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/experimental/patterns/ec2-app.d.ts +56 -0
- package/lib/experimental/patterns/ec2-app.d.ts.map +1 -0
- package/lib/experimental/patterns/ec2-app.js +289 -0
- package/lib/experimental/patterns/ec2-app.js.map +1 -0
- package/lib/riff-raff-yaml-file/index.d.ts.map +1 -1
- package/lib/riff-raff-yaml-file/index.js +10 -1
- package/lib/riff-raff-yaml-file/index.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Duration } from "aws-cdk-lib";
|
|
2
|
+
import type { GuStack } from "../../constructs/core";
|
|
3
|
+
import type { GuEc2AppProps } from "../../patterns";
|
|
4
|
+
import { GuEc2App } from "../../patterns";
|
|
5
|
+
interface AutoScalingRollingUpdateDurations {
|
|
6
|
+
/**
|
|
7
|
+
* The time between each check of an instance's health within the target group.
|
|
8
|
+
*/
|
|
9
|
+
sleep: Duration;
|
|
10
|
+
/**
|
|
11
|
+
* Additional time to cover the time spent polling an instance's health within the target group before sending the CloudFormation signal.
|
|
12
|
+
*/
|
|
13
|
+
buffer: Duration;
|
|
14
|
+
}
|
|
15
|
+
export declare const RollingUpdateDurations: AutoScalingRollingUpdateDurations;
|
|
16
|
+
export interface GuEc2AppExperimentalProps extends Omit<GuEc2AppProps, "updatePolicy"> {
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* An experimental pattern to instantiate an EC2 application that is updated entirely via CloudFormation.
|
|
20
|
+
* It sets the update policy of the `AWS::AutoScaling::AutoScalingGroup` to `AutoScalingRollingUpdate`.
|
|
21
|
+
* When a CloudFormation update is applied, the current instances in the ASG will be replaced.
|
|
22
|
+
*
|
|
23
|
+
* This pattern also updates the User Data, running some commands AFTER yours.
|
|
24
|
+
* These changes are wrapped in start and end marking comments.
|
|
25
|
+
*
|
|
26
|
+
* This pattern does not enable for scaling events to trigger _during_ a deployment
|
|
27
|
+
* as during testing it was found that scale-in events during deployment led to unpredictable service availability.
|
|
28
|
+
*
|
|
29
|
+
* If a deployment fails, for example when the healthcheck fails, CloudFormation will automatically rollback the changes.
|
|
30
|
+
* This improves on the behaviour of Riff-Raff's `autoscaling` deployment which requires manual intervention on deployment failure.
|
|
31
|
+
*
|
|
32
|
+
* To update the application's code, a CloudFormation update must be triggered.
|
|
33
|
+
* The best way to do this is to include the build number in the application artifact.
|
|
34
|
+
* TODO test User Data includes a build number.
|
|
35
|
+
*
|
|
36
|
+
* @remarks
|
|
37
|
+
* - The rate at which instances are replaced are conditional based on how scaled up the service is.
|
|
38
|
+
* The more an application is scaled, the longer it'll take to deploy.
|
|
39
|
+
* - It is not necessary to use the `autoscaling` Riff-Raff deployment type in conjunction with this.
|
|
40
|
+
* Doing so won't break anything, however it'll lengthen the deployment time as instances will be rotated twice.
|
|
41
|
+
* Please remove it from any manually created `riff-raff.yaml` file.
|
|
42
|
+
* - Your application should include a build number in its filename.
|
|
43
|
+
* This value will change across builds, and therefore create a CloudFormation template difference to be deployed.
|
|
44
|
+
* - Requires the AWS CLI and `cfn-signal` binaries to be available on the instance, and on the `PATH`.
|
|
45
|
+
* AMIgo adds these via the `aws-tools` role.
|
|
46
|
+
*
|
|
47
|
+
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html#cfn-attributes-updatepolicy-rollingupdate
|
|
48
|
+
* @see https://github.com/guardian/testing-asg-rolling-update
|
|
49
|
+
*
|
|
50
|
+
* @experimental
|
|
51
|
+
*/
|
|
52
|
+
export declare class GuEc2AppExperimental extends GuEc2App {
|
|
53
|
+
constructor(scope: GuStack, props: GuEc2AppExperimentalProps);
|
|
54
|
+
}
|
|
55
|
+
export {};
|
|
56
|
+
//# sourceMappingURL=ec2-app.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ec2-app.d.ts","sourceRoot":"","sources":["../../../src/experimental/patterns/ec2-app.ts"],"names":[],"mappings":"AACA,OAAO,EAAyB,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK9D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAG1C,UAAU,iCAAiC;IACzC;;OAEG;IACH,KAAK,EAAE,QAAQ,CAAC;IAEhB;;OAEG;IACH,MAAM,EAAE,QAAQ,CAAC;CAClB;AAED,eAAO,MAAM,sBAAsB,EAAE,iCAGpC,CAAC;AAiNF,MAAM,WAAW,yBAA0B,SAAQ,IAAI,CAAC,aAAa,EAAE,cAAc,CAAC;CAAG;AAEzF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,qBAAa,oBAAqB,SAAQ,QAAQ;gBACpC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,yBAAyB;CAoF7D"}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GuEc2AppExperimental = exports.RollingUpdateDurations = void 0;
|
|
4
|
+
const aws_cdk_lib_1 = require("aws-cdk-lib");
|
|
5
|
+
const aws_autoscaling_1 = require("aws-cdk-lib/aws-autoscaling");
|
|
6
|
+
const aws_iam_1 = require("aws-cdk-lib/aws-iam");
|
|
7
|
+
const autoscaling_1 = require("../../constructs/autoscaling");
|
|
8
|
+
const patterns_1 = require("../../patterns");
|
|
9
|
+
const singleton_1 = require("../../utils/singleton");
|
|
10
|
+
exports.RollingUpdateDurations = {
|
|
11
|
+
sleep: aws_cdk_lib_1.Duration.seconds(5),
|
|
12
|
+
buffer: aws_cdk_lib_1.Duration.minutes(1),
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Ensures the `AutoScalingRollingUpdate` of an AutoScaling Group has a `PauseTime` matching the healthcheck grace period.
|
|
16
|
+
* It also ensures the `CreationPolicy` resource signal `Timeout` matches the healthcheck grace period.
|
|
17
|
+
*
|
|
18
|
+
* @internal
|
|
19
|
+
*
|
|
20
|
+
* @privateRemarks
|
|
21
|
+
* The ASG healthcheck grace period is hard-coded by {@link GuEc2App}.
|
|
22
|
+
* Customisation of this value is performed via an escape hatch.
|
|
23
|
+
* An `Aspect` is the only way to observe any customisation.
|
|
24
|
+
*
|
|
25
|
+
* TODO Expose the healthcheck grace period as a property on {@link GuEc2App} and remove this `Aspect`.
|
|
26
|
+
*/
|
|
27
|
+
class AutoScalingRollingUpdateTimeout {
|
|
28
|
+
constructor(scope) {
|
|
29
|
+
this.stack = scope;
|
|
30
|
+
}
|
|
31
|
+
static getInstance(stack) {
|
|
32
|
+
if (!this.instance || !(0, singleton_1.isSingletonPresentInStack)(stack, this.instance)) {
|
|
33
|
+
this.instance = new AutoScalingRollingUpdateTimeout(stack);
|
|
34
|
+
}
|
|
35
|
+
return this.instance;
|
|
36
|
+
}
|
|
37
|
+
visit(construct) {
|
|
38
|
+
if (construct instanceof aws_autoscaling_1.CfnAutoScalingGroup) {
|
|
39
|
+
const currentRollingUpdate = construct.cfnOptions.updatePolicy?.autoScalingRollingUpdate;
|
|
40
|
+
const currentCreationPolicy = construct.cfnOptions.creationPolicy;
|
|
41
|
+
if (!construct.healthCheckGracePeriod) {
|
|
42
|
+
throw new Error(`The healthcheck grace period not set for autoscaling group ${construct.node.id}.`);
|
|
43
|
+
}
|
|
44
|
+
const signalTimeoutSeconds = construct.healthCheckGracePeriod + exports.RollingUpdateDurations.buffer.toSeconds();
|
|
45
|
+
if (currentRollingUpdate) {
|
|
46
|
+
construct.cfnOptions.updatePolicy = {
|
|
47
|
+
autoScalingRollingUpdate: {
|
|
48
|
+
...currentRollingUpdate,
|
|
49
|
+
pauseTime: aws_cdk_lib_1.Duration.seconds(signalTimeoutSeconds).toIsoString(),
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
if (currentCreationPolicy) {
|
|
54
|
+
construct.cfnOptions.creationPolicy = {
|
|
55
|
+
...currentCreationPolicy,
|
|
56
|
+
resourceSignal: {
|
|
57
|
+
...currentCreationPolicy.resourceSignal,
|
|
58
|
+
timeout: aws_cdk_lib_1.Duration.seconds(signalTimeoutSeconds).toIsoString(),
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* An `Aspect` that adjusts the properties of an AutoScaling Group using an `AutoScalingRollingUpdate` update policy.
|
|
67
|
+
*
|
|
68
|
+
* It'll unset the `DesiredCapacity` of the ASG as a rolling update sets `Desired` back to the template version,
|
|
69
|
+
* undoing any changes that a scale-out event may have done.
|
|
70
|
+
* Having `DesiredCapacity` unset ensures the service remains at-capacity at all times.
|
|
71
|
+
*
|
|
72
|
+
* It'll also make the `MinInstancesInService` property dynamic via a CFN Parameter that Riff-Raff will set.
|
|
73
|
+
* The value depends on the current capacity of the ASG:
|
|
74
|
+
* - If the service is running normally, it'll be set to the `MinSize` capacity
|
|
75
|
+
* - If the service is partially scaled, it'll be set to the current `DesiredCapacity`
|
|
76
|
+
* - If the service is fully scaled, it'll be set to (at least) `MaxSize` - 1
|
|
77
|
+
*
|
|
78
|
+
* @privateRemarks
|
|
79
|
+
* - Temporarily implemented as a singleton to ensure only one instance is added to a stack,
|
|
80
|
+
* else multiple attempts to add the same CFN Parameter will be made and fail.
|
|
81
|
+
* - Once out of experimental, instantiate this `Aspect` directly in {@link GuStack}.
|
|
82
|
+
*
|
|
83
|
+
* @see https://github.com/guardian/testing-asg-rolling-update
|
|
84
|
+
*/
|
|
85
|
+
class HorizontallyScalingDeploymentProperties {
|
|
86
|
+
constructor(scope) {
|
|
87
|
+
this.stack = scope;
|
|
88
|
+
this.asgToParamMap = new Map();
|
|
89
|
+
}
|
|
90
|
+
static getInstance(stack) {
|
|
91
|
+
if (!this.instance || !(0, singleton_1.isSingletonPresentInStack)(stack, this.instance)) {
|
|
92
|
+
this.instance = new HorizontallyScalingDeploymentProperties(stack);
|
|
93
|
+
}
|
|
94
|
+
return this.instance;
|
|
95
|
+
}
|
|
96
|
+
visit(construct) {
|
|
97
|
+
if (construct instanceof aws_autoscaling_1.CfnScalingPolicy) {
|
|
98
|
+
const { node } = construct;
|
|
99
|
+
const { scopes, path } = node;
|
|
100
|
+
/*
|
|
101
|
+
Requiring a `CfnScalingPolicy` to be created in the scope of a `GuAutoScalingGroup`
|
|
102
|
+
is the most reliable way to associate the two together.
|
|
103
|
+
|
|
104
|
+
Though the `autoScalingGroupName` property is passed to a `CfnScalingPolicy` when instantiating,
|
|
105
|
+
this does not create a concrete link as AWS CDK sets the value to be the ASG's `Ref`.
|
|
106
|
+
That is, it is a `Token` until it is synthesised.
|
|
107
|
+
This is even if the ASG has an explicit name set.
|
|
108
|
+
|
|
109
|
+
See also:
|
|
110
|
+
- https://docs.aws.amazon.com/cdk/v2/guide/tokens.html
|
|
111
|
+
- https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-autoscalinggroup.html#aws-resource-autoscaling-autoscalinggroup-return-values
|
|
112
|
+
- https://github.com/aws/aws-cdk/blob/f6b649d47f8bc30ca741fbb7a4852d51e8275002/packages/aws-cdk-lib/aws-autoscaling/lib/auto-scaling-group.ts#L1560
|
|
113
|
+
*/
|
|
114
|
+
const autoScalingGroup = scopes.find((_) => _ instanceof autoscaling_1.GuAutoScalingGroup);
|
|
115
|
+
if (!autoScalingGroup) {
|
|
116
|
+
throw new Error(`Failed to detect the autoscaling group relating to the scaling policy on path ${path}. Was it created in the scope of a GuAutoScalingGroup?`);
|
|
117
|
+
}
|
|
118
|
+
const cfnAutoScalingGroup = autoScalingGroup.node.defaultChild;
|
|
119
|
+
const currentRollingUpdate = cfnAutoScalingGroup.cfnOptions.updatePolicy?.autoScalingRollingUpdate;
|
|
120
|
+
if (currentRollingUpdate) {
|
|
121
|
+
/*
|
|
122
|
+
An autoscaling group that horizontally scales should not explicitly set `Desired`,
|
|
123
|
+
as a rolling update will set the current `Desired` back to the template version,
|
|
124
|
+
undoing any changes that a scale-out event may have done.
|
|
125
|
+
*/
|
|
126
|
+
cfnAutoScalingGroup.desiredCapacity = undefined;
|
|
127
|
+
const asgNodeId = autoScalingGroup.node.id;
|
|
128
|
+
if (!this.asgToParamMap.has(asgNodeId)) {
|
|
129
|
+
this.asgToParamMap.set(asgNodeId, new aws_cdk_lib_1.CfnParameter(this.stack, `MinInstancesInServiceFor${autoScalingGroup.app}`, {
|
|
130
|
+
type: "Number",
|
|
131
|
+
default: parseInt(cfnAutoScalingGroup.minSize),
|
|
132
|
+
maxValue: parseInt(cfnAutoScalingGroup.maxSize) - 1,
|
|
133
|
+
}));
|
|
134
|
+
}
|
|
135
|
+
const minInstancesInService = this.asgToParamMap.get(asgNodeId);
|
|
136
|
+
cfnAutoScalingGroup.cfnOptions.updatePolicy = {
|
|
137
|
+
autoScalingRollingUpdate: {
|
|
138
|
+
...currentRollingUpdate,
|
|
139
|
+
minInstancesInService: minInstancesInService.valueAsNumber,
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* An IAM Policy allowing the sending of a CloudFormation signal.
|
|
148
|
+
*
|
|
149
|
+
* @privateRemarks
|
|
150
|
+
* Implemented as a singleton as the resources can only be tightened at most to the CloudFormation stack.
|
|
151
|
+
*/
|
|
152
|
+
class AsgRollingUpdatePolicy extends aws_iam_1.Policy {
|
|
153
|
+
constructor(scope) {
|
|
154
|
+
const { stackId } = scope;
|
|
155
|
+
super(scope, "AsgRollingUpdatePolicy", {
|
|
156
|
+
statements: [
|
|
157
|
+
// Allow usage of command `cfn-signal`.
|
|
158
|
+
new aws_iam_1.PolicyStatement({
|
|
159
|
+
actions: ["cloudformation:SignalResource"],
|
|
160
|
+
effect: aws_iam_1.Effect.ALLOW,
|
|
161
|
+
resources: [stackId],
|
|
162
|
+
}),
|
|
163
|
+
/*
|
|
164
|
+
Allow usage of command `aws elbv2 describe-target-health`.
|
|
165
|
+
AWS Elastic Load Balancing does not support resource based policies, so the resource has to be `*` (any) here.
|
|
166
|
+
See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html
|
|
167
|
+
*/
|
|
168
|
+
new aws_iam_1.PolicyStatement({
|
|
169
|
+
actions: ["elasticloadbalancing:DescribeTargetHealth"],
|
|
170
|
+
effect: aws_iam_1.Effect.ALLOW,
|
|
171
|
+
resources: ["*"],
|
|
172
|
+
}),
|
|
173
|
+
],
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
static getInstance(stack) {
|
|
177
|
+
if (!this.instance || !(0, singleton_1.isSingletonPresentInStack)(stack, this.instance)) {
|
|
178
|
+
this.instance = new AsgRollingUpdatePolicy(stack);
|
|
179
|
+
}
|
|
180
|
+
return this.instance;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* An experimental pattern to instantiate an EC2 application that is updated entirely via CloudFormation.
|
|
185
|
+
* It sets the update policy of the `AWS::AutoScaling::AutoScalingGroup` to `AutoScalingRollingUpdate`.
|
|
186
|
+
* When a CloudFormation update is applied, the current instances in the ASG will be replaced.
|
|
187
|
+
*
|
|
188
|
+
* This pattern also updates the User Data, running some commands AFTER yours.
|
|
189
|
+
* These changes are wrapped in start and end marking comments.
|
|
190
|
+
*
|
|
191
|
+
* This pattern does not enable for scaling events to trigger _during_ a deployment
|
|
192
|
+
* as during testing it was found that scale-in events during deployment led to unpredictable service availability.
|
|
193
|
+
*
|
|
194
|
+
* If a deployment fails, for example when the healthcheck fails, CloudFormation will automatically rollback the changes.
|
|
195
|
+
* This improves on the behaviour of Riff-Raff's `autoscaling` deployment which requires manual intervention on deployment failure.
|
|
196
|
+
*
|
|
197
|
+
* To update the application's code, a CloudFormation update must be triggered.
|
|
198
|
+
* The best way to do this is to include the build number in the application artifact.
|
|
199
|
+
* TODO test User Data includes a build number.
|
|
200
|
+
*
|
|
201
|
+
* @remarks
|
|
202
|
+
* - The rate at which instances are replaced are conditional based on how scaled up the service is.
|
|
203
|
+
* The more an application is scaled, the longer it'll take to deploy.
|
|
204
|
+
* - It is not necessary to use the `autoscaling` Riff-Raff deployment type in conjunction with this.
|
|
205
|
+
* Doing so won't break anything, however it'll lengthen the deployment time as instances will be rotated twice.
|
|
206
|
+
* Please remove it from any manually created `riff-raff.yaml` file.
|
|
207
|
+
* - Your application should include a build number in its filename.
|
|
208
|
+
* This value will change across builds, and therefore create a CloudFormation template difference to be deployed.
|
|
209
|
+
* - Requires the AWS CLI and `cfn-signal` binaries to be available on the instance, and on the `PATH`.
|
|
210
|
+
* AMIgo adds these via the `aws-tools` role.
|
|
211
|
+
*
|
|
212
|
+
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html#cfn-attributes-updatepolicy-rollingupdate
|
|
213
|
+
* @see https://github.com/guardian/testing-asg-rolling-update
|
|
214
|
+
*
|
|
215
|
+
* @experimental
|
|
216
|
+
*/
|
|
217
|
+
class GuEc2AppExperimental extends patterns_1.GuEc2App {
|
|
218
|
+
constructor(scope, props) {
|
|
219
|
+
const { minimumInstances, maximumInstances = minimumInstances * 2 } = props.scaling;
|
|
220
|
+
const { applicationPort } = props;
|
|
221
|
+
const { region, stackId } = scope;
|
|
222
|
+
super(scope, {
|
|
223
|
+
...props,
|
|
224
|
+
updatePolicy: aws_autoscaling_1.UpdatePolicy.rollingUpdate({
|
|
225
|
+
maxBatchSize: maximumInstances,
|
|
226
|
+
minInstancesInService: minimumInstances,
|
|
227
|
+
minSuccessPercentage: 100,
|
|
228
|
+
waitOnResourceSignals: true,
|
|
229
|
+
/*
|
|
230
|
+
If a scale-in event fires during an `AutoScalingRollingUpdate` operation, the update could fail and rollback.
|
|
231
|
+
For this reason, we suspend the `AlarmNotification` process, else availability of a service cannot be guaranteed.
|
|
232
|
+
Consequently, services cannot scale-out during deployments.
|
|
233
|
+
If AWS ever supports suspending scale-out and scale-in independently, we should allow scale-out.
|
|
234
|
+
*/
|
|
235
|
+
suspendProcesses: [aws_autoscaling_1.ScalingProcess.ALARM_NOTIFICATION],
|
|
236
|
+
}),
|
|
237
|
+
});
|
|
238
|
+
const { autoScalingGroup, targetGroup } = this;
|
|
239
|
+
const { userData, role } = autoScalingGroup;
|
|
240
|
+
const cfnAutoScalingGroup = autoScalingGroup.node.defaultChild;
|
|
241
|
+
cfnAutoScalingGroup.desiredCapacity = minimumInstances.toString();
|
|
242
|
+
cfnAutoScalingGroup.cfnOptions.creationPolicy = {
|
|
243
|
+
autoScalingCreationPolicy: {
|
|
244
|
+
minSuccessfulInstancesPercent: 100,
|
|
245
|
+
},
|
|
246
|
+
resourceSignal: {
|
|
247
|
+
count: minimumInstances,
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
AsgRollingUpdatePolicy.getInstance(scope).attachToRole(role);
|
|
251
|
+
/*
|
|
252
|
+
`aws` is available via AMIgo baked AMIs.
|
|
253
|
+
See https://github.com/guardian/amigo/tree/main/roles/aws-tools.
|
|
254
|
+
*/
|
|
255
|
+
userData.addCommands(`# ${GuEc2AppExperimental.name} UserData Start`, `
|
|
256
|
+
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
|
|
257
|
+
INSTANCE_ID=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" "http://169.254.169.254/latest/meta-data/instance-id")
|
|
258
|
+
|
|
259
|
+
STATE=$(aws elbv2 describe-target-health \
|
|
260
|
+
--target-group-arn ${targetGroup.targetGroupArn} \
|
|
261
|
+
--region ${region} \
|
|
262
|
+
--targets Id=$INSTANCE_ID,Port=${applicationPort} \
|
|
263
|
+
--query "TargetHealthDescriptions[0].TargetHealth.State")
|
|
264
|
+
|
|
265
|
+
until [ "$STATE" == "\\"healthy\\"" ]; do
|
|
266
|
+
echo "Instance not yet healthy within target group. Current state $STATE. Sleeping..."
|
|
267
|
+
sleep ${exports.RollingUpdateDurations.sleep.toSeconds()}
|
|
268
|
+
STATE=$(aws elbv2 describe-target-health \
|
|
269
|
+
--target-group-arn ${targetGroup.targetGroupArn} \
|
|
270
|
+
--region ${region} \
|
|
271
|
+
--targets Id=$INSTANCE_ID,Port=${applicationPort} \
|
|
272
|
+
--query "TargetHealthDescriptions[0].TargetHealth.State")
|
|
273
|
+
done
|
|
274
|
+
|
|
275
|
+
echo "Instance is healthy in target group."
|
|
276
|
+
`, `# ${GuEc2AppExperimental.name} UserData End`);
|
|
277
|
+
userData.addOnExitCommands(`
|
|
278
|
+
cfn-signal --stack ${stackId} \
|
|
279
|
+
--resource ${cfnAutoScalingGroup.logicalId} \
|
|
280
|
+
--region ${region} \
|
|
281
|
+
--exit-code $exitCode || echo 'Failed to send Cloudformation Signal'
|
|
282
|
+
`);
|
|
283
|
+
// TODO Once out of experimental, instantiate these `Aspect`s directly in `GuStack`.
|
|
284
|
+
aws_cdk_lib_1.Aspects.of(scope).add(AutoScalingRollingUpdateTimeout.getInstance(scope));
|
|
285
|
+
aws_cdk_lib_1.Aspects.of(scope).add(HorizontallyScalingDeploymentProperties.getInstance(scope));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
exports.GuEc2AppExperimental = GuEc2AppExperimental;
|
|
289
|
+
//# sourceMappingURL=ec2-app.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ec2-app.js","sourceRoot":"","sources":["../../../src/experimental/patterns/ec2-app.ts"],"names":[],"mappings":";;;AACA,6CAA8D;AAC9D,iEAAkH;AAClH,iDAAsE;AAEtE,8DAAkE;AAGlE,6CAA0C;AAC1C,qDAAkE;AAcrD,QAAA,sBAAsB,GAAsC;IACvE,KAAK,EAAE,sBAAQ,CAAC,OAAO,C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e,GAAG,gBAAgB,CAAC,QAAQ,EAAE,CAAC;QAElE,mBAAmB,CAAC,UAAU,CAAC,cAAc,GAAG;YAC9C,yBAAyB,EAAE;gBACzB,6BAA6B,EAAE,GAAG;aACnC;YACD,cAAc,EAAE;gBACd,KAAK,EAAE,gBAAgB;aACxB;SACF,CAAC;QAEF,sBAAsB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAE7D;;;WAGG;QACH,QAAQ,CAAC,WAAW,CAClB,KAAK,oBAAoB,CAAC,IAAI,iBAAiB,EAC/C;;;;;6BAKuB,WAAW,CAAC,cAAc;mBACpC,MAAM;yCACgB,eAAe;;;;;gBAKxC,8BAAsB,CAAC,KAAK,CAAC,SAAS,EAAE;;+BAEzB,WAAW,CAAC,cAAc;qBACpC,MAAM;2CACgB,eAAe;;;;;OAKnD,EACD,KAAK,oBAAoB,CAAC,IAAI,eAAe,CAC9C,CAAC;QAEF,QAAQ,CAAC,iBAAiB,CACxB;6BACuB,OAAO;uBACb,mBAAmB,CAAC,SAAS;qBAC/B,MAAM;;SAElB,CACJ,CAAC;QAEF,oFAAoF;QACpF,qBAAO,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,+BAA+B,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;QAC1E,qBAAO,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,uCAAuC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;IACpF,CAAC;CACF;AArFD,oDAqFC","sourcesContent":["import type { IAspect } from \"aws-cdk-lib\";\nimport { Aspects, CfnParameter, Duration } from \"aws-cdk-lib\";\nimport { CfnAutoScalingGroup, CfnScalingPolicy, ScalingProcess, UpdatePolicy } from \"aws-cdk-lib/aws-autoscaling\";\nimport { Effect, Policy, PolicyStatement } from \"aws-cdk-lib/aws-iam\";\nimport type { IConstruct } from \"constructs\";\nimport { GuAutoScalingGroup } from \"../../constructs/autoscaling\";\nimport type { GuStack } from \"../../constructs/core\";\nimport type { GuEc2AppProps } from \"../../patterns\";\nimport { GuEc2App } from \"../../patterns\";\nimport { isSingletonPresentInStack } from \"../../utils/singleton\";\n\ninterface AutoScalingRollingUpdateDurations {\n /**\n * The time between each check of an instance's health within the target group.\n */\n sleep: Duration;\n\n /**\n * Additional time to cover the time spent polling an instance's health within the target group before sending the CloudFormation signal.\n */\n buffer: Duration;\n}\n\nexport const RollingUpdateDurations: AutoScalingRollingUpdateDurations = {\n sleep: Duration.seconds(5),\n buffer: Duration.minutes(1),\n};\n\n/**\n * Ensures the `AutoScalingRollingUpdate` of an AutoScaling Group has a `PauseTime` matching the healthcheck grace period.\n * It also ensures the `CreationPolicy` resource signal `Timeout` matches the healthcheck grace period.\n *\n * @internal\n *\n * @privateRemarks\n * The ASG healthcheck grace period is hard-coded by {@link GuEc2App}.\n * Customisation of this value is performed via an escape hatch.\n * An `Aspect` is the only way to observe any customisation.\n *\n * TODO Expose the healthcheck grace period as a property on {@link GuEc2App} and remove this `Aspect`.\n */\nclass AutoScalingRollingUpdateTimeout implements IAspect {\n public readonly stack: GuStack;\n private static instance: AutoScalingRollingUpdateTimeout | undefined;\n\n private constructor(scope: GuStack) {\n this.stack = scope;\n }\n\n public static getInstance(stack: GuStack): AutoScalingRollingUpdateTimeout {\n if (!this.instance || !isSingletonPresentInStack(stack, this.instance)) {\n this.instance = new AutoScalingRollingUpdateTimeout(stack);\n }\n return this.instance;\n }\n\n public visit(construct: IConstruct) {\n if (construct instanceof CfnAutoScalingGroup) {\n const currentRollingUpdate = construct.cfnOptions.updatePolicy?.autoScalingRollingUpdate;\n const currentCreationPolicy = construct.cfnOptions.creationPolicy;\n\n if (!construct.healthCheckGracePeriod) {\n throw new Error(`The healthcheck grace period not set for autoscaling group ${construct.node.id}.`);\n }\n\n const signalTimeoutSeconds = construct.healthCheckGracePeriod + RollingUpdateDurations.buffer.toSeconds();\n\n if (currentRollingUpdate) {\n construct.cfnOptions.updatePolicy = {\n autoScalingRollingUpdate: {\n ...currentRollingUpdate,\n pauseTime: Duration.seconds(signalTimeoutSeconds).toIsoString(),\n },\n };\n }\n\n if (currentCreationPolicy) {\n construct.cfnOptions.creationPolicy = {\n ...currentCreationPolicy,\n resourceSignal: {\n ...currentCreationPolicy.resourceSignal,\n timeout: Duration.seconds(signalTimeoutSeconds).toIsoString(),\n },\n };\n }\n }\n }\n}\n\n/**\n * An `Aspect` that adjusts the properties of an AutoScaling Group using an `AutoScalingRollingUpdate` update policy.\n *\n * It'll unset the `DesiredCapacity` of the ASG as a rolling update sets `Desired` back to the template version,\n * undoing any changes that a scale-out event may have done.\n * Having `DesiredCapacity` unset ensures the service remains at-capacity at all times.\n *\n * It'll also make the `MinInstancesInService` property dynamic via a CFN Parameter that Riff-Raff will set.\n * The value depends on the current capacity of the ASG:\n * - If the service is running normally, it'll be set to the `MinSize` capacity\n * - If the service is partially scaled, it'll be set to the current `DesiredCapacity`\n * - If the service is fully scaled, it'll be set to (at least) `MaxSize` - 1\n *\n * @privateRemarks\n * - Temporarily implemented as a singleton to ensure only one instance is added to a stack,\n * else multiple attempts to add the same CFN Parameter will be made and fail.\n * - Once out of experimental, instantiate this `Aspect` directly in {@link GuStack}.\n *\n * @see https://github.com/guardian/testing-asg-rolling-update\n */\nclass HorizontallyScalingDeploymentProperties implements IAspect {\n public readonly stack: GuStack;\n private readonly asgToParamMap: Map<string, CfnParameter>;\n private static instance: HorizontallyScalingDeploymentProperties | undefined;\n\n private constructor(scope: GuStack) {\n this.stack = scope;\n this.asgToParamMap = new Map();\n }\n\n public static getInstance(stack: GuStack): HorizontallyScalingDeploymentProperties {\n if (!this.instance || !isSingletonPresentInStack(stack, this.instance)) {\n this.instance = new HorizontallyScalingDeploymentProperties(stack);\n }\n\n return this.instance;\n }\n\n public visit(construct: IConstruct) {\n if (construct instanceof CfnScalingPolicy) {\n const { node } = construct;\n const { scopes, path } = node;\n\n /*\n Requiring a `CfnScalingPolicy` to be created in the scope of a `GuAutoScalingGroup`\n is the most reliable way to associate the two together.\n\n Though the `autoScalingGroupName` property is passed to a `CfnScalingPolicy` when instantiating,\n this does not create a concrete link as AWS CDK sets the value to be the ASG's `Ref`.\n That is, it is a `Token` until it is synthesised.\n This is even if the ASG has an explicit name set.\n\n See also:\n - https://docs.aws.amazon.com/cdk/v2/guide/tokens.html\n - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-autoscalinggroup.html#aws-resource-autoscaling-autoscalinggroup-return-values\n - https://github.com/aws/aws-cdk/blob/f6b649d47f8bc30ca741fbb7a4852d51e8275002/packages/aws-cdk-lib/aws-autoscaling/lib/auto-scaling-group.ts#L1560\n */\n const autoScalingGroup = scopes.find((_): _ is GuAutoScalingGroup => _ instanceof GuAutoScalingGroup);\n\n if (!autoScalingGroup) {\n throw new Error(\n `Failed to detect the autoscaling group relating to the scaling policy on path ${path}. Was it created in the scope of a GuAutoScalingGroup?`,\n );\n }\n\n const cfnAutoScalingGroup = autoScalingGroup.node.defaultChild as CfnAutoScalingGroup;\n const currentRollingUpdate = cfnAutoScalingGroup.cfnOptions.updatePolicy?.autoScalingRollingUpdate;\n\n if (currentRollingUpdate) {\n /*\n An autoscaling group that horizontally scales should not explicitly set `Desired`,\n as a rolling update will set the current `Desired` back to the template version,\n undoing any changes that a scale-out event may have done.\n */\n cfnAutoScalingGroup.desiredCapacity = undefined;\n\n const asgNodeId = autoScalingGroup.node.id;\n\n if (!this.asgToParamMap.has(asgNodeId)) {\n this.asgToParamMap.set(\n asgNodeId,\n new CfnParameter(this.stack, `MinInstancesInServiceFor${autoScalingGroup.app}`, {\n type: \"Number\",\n default: parseInt(cfnAutoScalingGroup.minSize),\n maxValue: parseInt(cfnAutoScalingGroup.maxSize) - 1,\n }),\n );\n }\n\n const minInstancesInService = this.asgToParamMap.get(asgNodeId)!;\n\n cfnAutoScalingGroup.cfnOptions.updatePolicy = {\n autoScalingRollingUpdate: {\n ...currentRollingUpdate,\n minInstancesInService: minInstancesInService.valueAsNumber,\n },\n };\n }\n }\n }\n}\n\n/**\n * An IAM Policy allowing the sending of a CloudFormation signal.\n *\n * @privateRemarks\n * Implemented as a singleton as the resources can only be tightened at most to the CloudFormation stack.\n */\nclass AsgRollingUpdatePolicy extends Policy {\n private static instance: AsgRollingUpdatePolicy | undefined;\n\n private constructor(scope: GuStack) {\n const { stackId } = scope;\n\n super(scope, \"AsgRollingUpdatePolicy\", {\n statements: [\n // Allow usage of command `cfn-signal`.\n new PolicyStatement({\n actions: [\"cloudformation:SignalResource\"],\n effect: Effect.ALLOW,\n resources: [stackId],\n }),\n\n /*\n Allow usage of command `aws elbv2 describe-target-health`.\n AWS Elastic Load Balancing does not support resource based policies, so the resource has to be `*` (any) here.\n See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html\n */\n new PolicyStatement({\n actions: [\"elasticloadbalancing:DescribeTargetHealth\"],\n effect: Effect.ALLOW,\n resources: [\"*\"],\n }),\n ],\n });\n }\n\n public static getInstance(stack: GuStack): AsgRollingUpdatePolicy {\n if (!this.instance || !isSingletonPresentInStack(stack, this.instance)) {\n this.instance = new AsgRollingUpdatePolicy(stack);\n }\n\n return this.instance;\n }\n}\n\nexport interface GuEc2AppExperimentalProps extends Omit<GuEc2AppProps, \"updatePolicy\"> {}\n\n/**\n * An experimental pattern to instantiate an EC2 application that is updated entirely via CloudFormation.\n * It sets the update policy of the `AWS::AutoScaling::AutoScalingGroup` to `AutoScalingRollingUpdate`.\n * When a CloudFormation update is applied, the current instances in the ASG will be replaced.\n *\n * This pattern also updates the User Data, running some commands AFTER yours.\n * These changes are wrapped in start and end marking comments.\n *\n * This pattern does not enable for scaling events to trigger _during_ a deployment\n * as during testing it was found that scale-in events during deployment led to unpredictable service availability.\n *\n * If a deployment fails, for example when the healthcheck fails, CloudFormation will automatically rollback the changes.\n * This improves on the behaviour of Riff-Raff's `autoscaling` deployment which requires manual intervention on deployment failure.\n *\n * To update the application's code, a CloudFormation update must be triggered.\n * The best way to do this is to include the build number in the application artifact.\n * TODO test User Data includes a build number.\n *\n * @remarks\n * - The rate at which instances are replaced are conditional based on how scaled up the service is.\n * The more an application is scaled, the longer it'll take to deploy.\n * - It is not necessary to use the `autoscaling` Riff-Raff deployment type in conjunction with this.\n * Doing so won't break anything, however it'll lengthen the deployment time as instances will be rotated twice.\n * Please remove it from any manually created `riff-raff.yaml` file.\n * - Your application should include a build number in its filename.\n * This value will change across builds, and therefore create a CloudFormation template difference to be deployed.\n * - Requires the AWS CLI and `cfn-signal` binaries to be available on the instance, and on the `PATH`.\n * AMIgo adds these via the `aws-tools` role.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html#cfn-attributes-updatepolicy-rollingupdate\n * @see https://github.com/guardian/testing-asg-rolling-update\n *\n * @experimental\n */\nexport class GuEc2AppExperimental extends GuEc2App {\n constructor(scope: GuStack, props: GuEc2AppExperimentalProps) {\n const { minimumInstances, maximumInstances = minimumInstances * 2 } = props.scaling;\n const { applicationPort } = props;\n const { region, stackId } = scope;\n\n super(scope, {\n ...props,\n updatePolicy: UpdatePolicy.rollingUpdate({\n maxBatchSize: maximumInstances,\n minInstancesInService: minimumInstances,\n minSuccessPercentage: 100,\n waitOnResourceSignals: true,\n\n /*\n If a scale-in event fires during an `AutoScalingRollingUpdate` operation, the update could fail and rollback.\n For this reason, we suspend the `AlarmNotification` process, else availability of a service cannot be guaranteed.\n Consequently, services cannot scale-out during deployments.\n If AWS ever supports suspending scale-out and scale-in independently, we should allow scale-out.\n */\n suspendProcesses: [ScalingProcess.ALARM_NOTIFICATION],\n }),\n });\n\n const { autoScalingGroup, targetGroup } = this;\n const { userData, role } = autoScalingGroup;\n const cfnAutoScalingGroup = autoScalingGroup.node.defaultChild as CfnAutoScalingGroup;\n\n cfnAutoScalingGroup.desiredCapacity = minimumInstances.toString();\n\n cfnAutoScalingGroup.cfnOptions.creationPolicy = {\n autoScalingCreationPolicy: {\n minSuccessfulInstancesPercent: 100,\n },\n resourceSignal: {\n count: minimumInstances,\n },\n };\n\n AsgRollingUpdatePolicy.getInstance(scope).attachToRole(role);\n\n /*\n `aws` is available via AMIgo baked AMIs.\n See https://github.com/guardian/amigo/tree/main/roles/aws-tools.\n */\n userData.addCommands(\n `# ${GuEc2AppExperimental.name} UserData Start`,\n `\n TOKEN=$(curl -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\")\n INSTANCE_ID=$(curl -H \"X-aws-ec2-metadata-token: $TOKEN\" \"http://169.254.169.254/latest/meta-data/instance-id\")\n\n STATE=$(aws elbv2 describe-target-health \\\n --target-group-arn ${targetGroup.targetGroupArn} \\\n --region ${region} \\\n --targets Id=$INSTANCE_ID,Port=${applicationPort} \\\n --query \"TargetHealthDescriptions[0].TargetHealth.State\")\n\n until [ \"$STATE\" == \"\\\\\"healthy\\\\\"\" ]; do\n echo \"Instance not yet healthy within target group. Current state $STATE. Sleeping...\"\n sleep ${RollingUpdateDurations.sleep.toSeconds()}\n STATE=$(aws elbv2 describe-target-health \\\n --target-group-arn ${targetGroup.targetGroupArn} \\\n --region ${region} \\\n --targets Id=$INSTANCE_ID,Port=${applicationPort} \\\n --query \"TargetHealthDescriptions[0].TargetHealth.State\")\n done\n\n echo \"Instance is healthy in target group.\"\n `,\n `# ${GuEc2AppExperimental.name} UserData End`,\n );\n\n userData.addOnExitCommands(\n `\n cfn-signal --stack ${stackId} \\\n --resource ${cfnAutoScalingGroup.logicalId} \\\n --region ${region} \\\n --exit-code $exitCode || echo 'Failed to send Cloudformation Signal'\n `,\n );\n\n // TODO Once out of experimental, instantiate these `Aspect`s directly in `GuStack`.\n Aspects.of(scope).add(AutoScalingRollingUpdateTimeout.getInstance(scope));\n Aspects.of(scope).add(HorizontallyScalingDeploymentProperties.getInstance(scope));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAWvC,OAAO,KAAK,EAMV,YAAY,EAGb,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAY;IACzC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAa;IAC1C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAa;IAC1C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAW;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC;;;;;;;;;;OAUG;IACH,SAAgB,YAAY,EAAE,YAAY,CAAC;IAE3C,OAAO,CAAC,iBAAiB;IASzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAqDG;IACH,OAAO,CAAC,mBAAmB;IAiC3B,OAAO,CAAC,6BAA6B;IAQrC,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,oBAAoB;IAI5B,OAAO,CAAC,sBAAsB;gBAKlB,GAAG,EAAE,GAAG;IAiFpB;;;OAGG;IACH,MAAM,IAAI,MAAM;IAiBhB;;;OAGG;IACH,KAAK,IAAI,IAAI;CAId"}
|
|
@@ -196,7 +196,16 @@ class RiffRaffYamlFile {
|
|
|
196
196
|
const lambdaDeployment = (0, lambda_2.updateLambdaDeployment)(lambda, cfnDeployment);
|
|
197
197
|
deployments.set(lambdaDeployment.name, lambdaDeployment.props);
|
|
198
198
|
});
|
|
199
|
-
|
|
199
|
+
/*
|
|
200
|
+
Instances in an ASG with an `AutoScalingRollingUpdate` update policy are rotated via CloudFormation.
|
|
201
|
+
Therefore, they do not need to also perform an `autoscaling` deployment via Riff-Raff.
|
|
202
|
+
*/
|
|
203
|
+
const legacyAutoscalingGroups = autoscalingGroups.filter((asg) => {
|
|
204
|
+
const { cfnOptions } = asg.node.defaultChild;
|
|
205
|
+
const { updatePolicy } = cfnOptions;
|
|
206
|
+
return updatePolicy?.autoScalingRollingUpdate === undefined;
|
|
207
|
+
});
|
|
208
|
+
legacyAutoscalingGroups.forEach((asg) => {
|
|
200
209
|
const asgDeployment = (0, autoscaling_2.autoscalingDeployment)(asg, cfnDeployment);
|
|
201
210
|
deployments.set(asgDeployment.name, asgDeployment.props);
|
|
202
211
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAmC;AACnC,gDAAwB;AAExB,6CAAoC;AACpC,qCAA+B;AAC/B,2DAA+D;AAC/D,6CAA6C;AAC7C,iDAAwD;AACxD,2DAA6F;AAC7F,iEAAoH;AACpH,iDAAoF;AACpF,yCAA8D;AAY9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,gBAAgB;IAoBnB,iBAAiB,CAAC,aAAuB,EAAE,aAAuB;QACxE,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE;YAClD,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC;YAClC,OAAO,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,aAAa,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAqDG;IACK,mBAA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AK,CAAC,CAAC;oBAC3D,CAAC,CAAC,CAAC;oBAEH,WAAW,CAAC,GAAG,CACb,aAAa,CAAC,IAAI,EAClB,IAAA,2DAA0C,EAAC,aAAa,EAAE,iBAAiB,CAAC,CAC7E,CAAC;gBACJ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG;YAClB,aAAa;YACb,WAAW;SACZ,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,MAAM;QACJ,qFAAqF;QACrF,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,KAAc,EAAE,EAAE;YAChD,IAAI,KAAK,YAAY,GAAG,EAAE;gBACxB,iGAAiG;gBACjG,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;aAC1B;YACD,IAAI,KAAK,YAAY,GAAG,EAAE;gBACxB,iGAAiG;gBACjG,OAAO,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;aAClC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;QAEF,OAAO,IAAA,cAAI,EAAC,IAAI,CAAC,YAAY,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACzD,IAAA,kBAAa,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACxC,CAAC;CACF;AA7OD,4CA6OC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../constructs/autoscaling\";\nimport { GuStack } from \"../constructs/core\";\nimport { GuLambdaFunction } from \"../constructs/lambda\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport { addAmiParametersToCloudFormationDeployment, cloudFormationDeployment } from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { groupByClassNameStackRegionStage } from \"./group-by\";\nimport type {\n GroupedCdkStacks,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFile {\n private readonly allCdkStacks: GuStack[];\n private readonly allStackTags: StackTag[];\n private readonly allStageTags: StageTag[];\n private readonly allRegions: Region[];\n private readonly outdir: string;\n\n /**\n * The `riff-raff.yaml` file as an object.\n *\n * It is useful for specifying additional deployment types that GuCDK does not support.\n * Consider raising an issue or pull request if you think it should be supported.\n *\n * In most cases, you shouldn't need to access this.\n * No validation is performed on the parameters you provide, so you might get deployment errors.\n *\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\n public readonly riffRaffYaml: RiffRaffYaml;\n\n private isCdkStackPresent(expectedStack: StackTag, expectedStage: StageTag): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const { stack, stage } = cdkStack;\n return stack === expectedStack && stage === expectedStage;\n });\n\n return !!matches;\n }\n\n /**\n * Check there are the appropriate number of `GuStack`s.\n * Expect to find an instance for each combination of `stack`, and `stage`.\n *\n * If not valid, a message is logged describing what is missing to aid debugging.\n *\n * Given the following:\n *\n * ```ts\n * const app = new App();\n *\n * class MyApplicationStack extends GuStack { }\n *\n * new MyApplicationStack(app, \"App-CODE-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"CODE\"\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-media-service\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"media-service\",\n * stage: \"PROD\",\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"PROD\"\n * });\n * ```\n *\n * This will log a message like this, where ❌ denotes something missing,\n * specifically there is no `CODE` template for `media-service`.\n *\n * ```log\n * Unable to produce a working riff-raff.yaml file; missing 1 definitions (details below)\n *\n * ┌───────────────┬──────┬──────┐\n * │ (index) │ CODE │ PROD │\n * ├───────────────┼──────┼──────┤\n * │ deploy │ '✅' │ '✅' │\n * │ media-service │ '❌' │ '✅' │\n * └───────────────┴──────┴──────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<StackTag, Record<StageTag, Found | NotFound>>;\n\n const { allStackTags, allStageTags } = this;\n\n const checks: AppValidation = allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(stackTag, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions: Array<Found | NotFound> = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).filter((_) => _ === \"❌\");\n });\n\n if (missingDefinitions.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingDefinitions.length} definitions`;\n\n console.log(`${message} (details below)`);\n console.table(checks);\n\n throw new Error(message);\n }\n }\n\n private validateAllRegionsAreResolved(): void {\n const unresolved = this.allRegions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n }\n\n private getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n }\n\n private getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n }\n\n private getGuStackDependencies(cdkStack: GuStack): GuStack[] {\n return cdkStack.dependencies.filter((_) => _ instanceof GuStack) as GuStack[];\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));\n this.allStageTags = Array.from(allowedStages);\n this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));\n this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));\n\n this.validateStacksInApp();\n this.validateAllRegionsAreResolved();\n\n this.outdir = app.outdir;\n\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n const groupedStacks: GroupedCdkStacks = groupByClassNameStackRegionStage(this.allCdkStacks);\n\n Object.values(groupedStacks).forEach((stackTagGroup) => {\n Object.values(stackTagGroup).forEach((regionGroup) => {\n Object.values(regionGroup).forEach((stageGroup) => {\n const stacks: GuStack[] = Object.values(stageGroup).flat();\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n const [stack] = stacks;\n\n if (!stack) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n const lambdas = this.getLambdas(stack);\n const autoscalingGroups = this.getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const parentStacks: RiffRaffDeployment[] = this.getGuStackDependencies(stack).map((x) =>\n cloudFormationDeployment([x], [], this.outdir),\n );\n\n const cfnDeployment = cloudFormationDeployment(stacks, [...artifactUploads, ...parentStacks], this.outdir);\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n autoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n deployments.set(\n cfnDeployment.name,\n addAmiParametersToCloudFormationDeployment(cfnDeployment, autoscalingGroups),\n );\n });\n });\n });\n\n this.riffRaffYaml = {\n allowedStages,\n deployments,\n };\n }\n\n /**\n * The `riff-raff.yaml` file as a string.\n * Useful for testing.\n */\n toYAML(): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n return dump(this.riffRaffYaml, { replacer });\n }\n\n /**\n * Write the `riff-raff.yaml` file to disk.\n * It'll be located with the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n const outPath = path.join(this.outdir, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAmC;AACnC,gDAAwB;AAExB,6CAAoC;AAEpC,qCAA+B;AAC/B,2DAA+D;AAC/D,6CAA6C;AAC7C,iDAAwD;AACxD,2DAA6F;AAC7F,iEAAoH;AACpH,iDAAoF;AACpF,yCAA8D;AAY9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,gBAAgB;IAoBnB,iBAAiB,CAAC,aAAuB,EAAE,aAAuB;QACxE,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE;YAClD,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC;YAClC,OAAO,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,aAAa,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,kBAAa,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACxC,CAAC;CACF;AAvPD,4CAuPC","sourcesContent":["import { writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport type { CfnAutoScalingGroup } from \"aws-cdk-lib/aws-autoscaling\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../constructs/autoscaling\";\nimport { GuStack } from \"../constructs/core\";\nimport { GuLambdaFunction } from \"../constructs/lambda\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport { addAmiParametersToCloudFormationDeployment, cloudFormationDeployment } from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { groupByClassNameStackRegionStage } from \"./group-by\";\nimport type {\n GroupedCdkStacks,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFile {\n private readonly allCdkStacks: GuStack[];\n private readonly allStackTags: StackTag[];\n private readonly allStageTags: StageTag[];\n private readonly allRegions: Region[];\n private readonly outdir: string;\n\n /**\n * The `riff-raff.yaml` file as an object.\n *\n * It is useful for specifying additional deployment types that GuCDK does not support.\n * Consider raising an issue or pull request if you think it should be supported.\n *\n * In most cases, you shouldn't need to access this.\n * No validation is performed on the parameters you provide, so you might get deployment errors.\n *\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\n public readonly riffRaffYaml: RiffRaffYaml;\n\n private isCdkStackPresent(expectedStack: StackTag, expectedStage: StageTag): boolean {\n const matches = this.allCdkStacks.find((cdkStack) => {\n const { stack, stage } = cdkStack;\n return stack === expectedStack && stage === expectedStage;\n });\n\n return !!matches;\n }\n\n /**\n * Check there are the appropriate number of `GuStack`s.\n * Expect to find an instance for each combination of `stack`, and `stage`.\n *\n * If not valid, a message is logged describing what is missing to aid debugging.\n *\n * Given the following:\n *\n * ```ts\n * const app = new App();\n *\n * class MyApplicationStack extends GuStack { }\n *\n * new MyApplicationStack(app, \"App-CODE-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"CODE\"\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-media-service\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"media-service\",\n * stage: \"PROD\",\n * });\n *\n * new MyApplicationStack(app, \"App-PROD-deploy\", {\n * env: {\n * region: \"eu-west-1\",\n * },\n * stack: \"deploy\",\n * stage: \"PROD\"\n * });\n * ```\n *\n * This will log a message like this, where ❌ denotes something missing,\n * specifically there is no `CODE` template for `media-service`.\n *\n * ```log\n * Unable to produce a working riff-raff.yaml file; missing 1 definitions (details below)\n *\n * ┌───────────────┬──────┬──────┐\n * │ (index) │ CODE │ PROD │\n * ├───────────────┼──────┼──────┤\n * │ deploy │ '✅' │ '✅' │\n * │ media-service │ '❌' │ '✅' │\n * └───────────────┴──────┴──────┘\n * ```\n *\n * @private\n */\n private validateStacksInApp(): void {\n type Found = \"✅\";\n type NotFound = \"❌\";\n type AppValidation = Record<StackTag, Record<StageTag, Found | NotFound>>;\n\n const { allStackTags, allStageTags } = this;\n\n const checks: AppValidation = allStackTags.reduce((accStackTag, stackTag) => {\n return {\n ...accStackTag,\n [stackTag]: allStageTags.reduce((accStageTag, stageTag) => {\n return {\n ...accStageTag,\n [stageTag]: this.isCdkStackPresent(stackTag, stageTag) ? \"✅\" : \"❌\",\n };\n }, {}),\n };\n }, {});\n\n const missingDefinitions: Array<Found | NotFound> = Object.values(checks).flatMap((groupedByStackTag) => {\n return Object.values(groupedByStackTag).filter((_) => _ === \"❌\");\n });\n\n if (missingDefinitions.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingDefinitions.length} definitions`;\n\n console.log(`${message} (details below)`);\n console.table(checks);\n\n throw new Error(message);\n }\n }\n\n private validateAllRegionsAreResolved(): void {\n const unresolved = this.allRegions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n }\n\n private getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n }\n\n private getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n }\n\n private getGuStackDependencies(cdkStack: GuStack): GuStack[] {\n return cdkStack.dependencies.filter((_) => _ instanceof GuStack) as GuStack[];\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n this.allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allowedStages = new Set(this.allCdkStacks.map(({ stage }) => stage));\n this.allStageTags = Array.from(allowedStages);\n this.allStackTags = Array.from(new Set(this.allCdkStacks.map(({ stack }) => stack)));\n this.allRegions = Array.from(new Set(this.allCdkStacks.map(({ region }) => region)));\n\n this.validateStacksInApp();\n this.validateAllRegionsAreResolved();\n\n this.outdir = app.outdir;\n\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n const groupedStacks: GroupedCdkStacks = groupByClassNameStackRegionStage(this.allCdkStacks);\n\n Object.values(groupedStacks).forEach((stackTagGroup) => {\n Object.values(stackTagGroup).forEach((regionGroup) => {\n Object.values(regionGroup).forEach((stageGroup) => {\n const stacks: GuStack[] = Object.values(stageGroup).flat();\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n const [stack] = stacks;\n\n if (!stack) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n const lambdas = this.getLambdas(stack);\n const autoscalingGroups = this.getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const parentStacks: RiffRaffDeployment[] = this.getGuStackDependencies(stack).map((x) =>\n cloudFormationDeployment([x], [], this.outdir),\n );\n\n const cfnDeployment = cloudFormationDeployment(stacks, [...artifactUploads, ...parentStacks], this.outdir);\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n /*\n Instances in an ASG with an `AutoScalingRollingUpdate` update policy are rotated via CloudFormation.\n Therefore, they do not need to also perform an `autoscaling` deployment via Riff-Raff.\n */\n const legacyAutoscalingGroups = autoscalingGroups.filter((asg) => {\n const { cfnOptions } = asg.node.defaultChild as CfnAutoScalingGroup;\n const { updatePolicy } = cfnOptions;\n return updatePolicy?.autoScalingRollingUpdate === undefined;\n });\n\n legacyAutoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n deployments.set(\n cfnDeployment.name,\n addAmiParametersToCloudFormationDeployment(cfnDeployment, autoscalingGroups),\n );\n });\n });\n });\n\n this.riffRaffYaml = {\n allowedStages,\n deployments,\n };\n }\n\n /**\n * The `riff-raff.yaml` file as a string.\n * Useful for testing.\n */\n toYAML(): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n return dump(this.riffRaffYaml, { replacer });\n }\n\n /**\n * Write the `riff-raff.yaml` file to disk.\n * It'll be located with the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n const outPath = path.join(this.outdir, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML());\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guardian/cdk",
|
|
3
3
|
"description": "Generic Guardian flavoured AWS CDK components",
|
|
4
|
-
"version": "59.
|
|
4
|
+
"version": "59.5.1",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"types": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
|
@@ -33,17 +33,17 @@
|
|
|
33
33
|
"@guardian/eslint-plugin-tsdoc-required": "^0.1.3",
|
|
34
34
|
"@guardian/tsconfig": "^1.0.0",
|
|
35
35
|
"@types/git-url-parse": "^9.0.3",
|
|
36
|
-
"@types/jest": "^29.5.
|
|
36
|
+
"@types/jest": "^29.5.13",
|
|
37
37
|
"@types/js-yaml": "^4.0.9",
|
|
38
38
|
"@types/lodash.camelcase": "^4.3.9",
|
|
39
39
|
"@types/lodash.kebabcase": "^4.1.9",
|
|
40
40
|
"@types/lodash.upperfirst": "^4.3.9",
|
|
41
|
-
"@types/node": "22.5.
|
|
41
|
+
"@types/node": "22.5.5",
|
|
42
42
|
"@types/yargs": "^17.0.33",
|
|
43
43
|
"aws-cdk": "2.157.0",
|
|
44
44
|
"aws-cdk-lib": "2.157.0",
|
|
45
45
|
"constructs": "10.3.0",
|
|
46
|
-
"eslint": "^8.57.
|
|
46
|
+
"eslint": "^8.57.1",
|
|
47
47
|
"eslint-plugin-custom-rules": "file:tools/eslint",
|
|
48
48
|
"gh-pages": "^6.1.1",
|
|
49
49
|
"jest": "^29.7.0",
|