๐Ÿ“ฆ juspay / hyperswitch-cdk

๐Ÿ“„ image_builder_stack.ts ยท 281 lines
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
281import * as cdk from "aws-cdk-lib";
import * as image_builder from "aws-cdk-lib/aws-imagebuilder"
import * as iam from "aws-cdk-lib/aws-iam";

import { Function, Runtime, Code } from "aws-cdk-lib/aws-lambda";
import { LambdaSubscription } from 'aws-cdk-lib/aws-sns-subscriptions';
import { Vpc } from './networking';
import { Topic } from 'aws-cdk-lib/aws-sns';
import { Construct } from "constructs";
import { ImageBuilderConfig, VpcConfig } from "./config";
import { aws_logs as logs } from 'aws-cdk-lib';
import { MachineImage, SubnetType, SecurityGroup } from 'aws-cdk-lib/aws-ec2';

import { readFileSync } from "fs";

type ImageBuilderProperties = {
    pipeline_name: string;
    recipe_name: string;
    profile_name: string;
    comp_name: string;
    comp_id: string;
    infra_config_name: string;
    baseimageArn: string;
    description: string;
    compFilePath: string;
    snsTopicArn: string;
    subnetId: string;
    sgId: string;

}

type RecordLambdaProperties = {
    name: string;
    id: string;
    role: iam.Role;
    ssm_key: string;
    topic: Topic,
}

function CreateImagePipeline(
    stack: ImageBuilderStack,
    role: iam.Role,
    props: ImageBuilderProperties,
): string {
    const component = new image_builder.CfnComponent(stack, props.comp_id, {
        name: props.comp_name,
        description: props.description,
        platform: "Linux",
        version: "1.0.1",
        data: readFileSync(props.compFilePath).toString(),
    })
    let instance_profile = new iam.CfnInstanceProfile(stack, props.profile_name, { instanceProfileName: props.profile_name, roles: [role.roleName] })

    const squid_recipe = new image_builder.CfnImageRecipe(stack, props.recipe_name, {
        name: props.recipe_name,
        version: "1.0.4",
        components: [
            { "componentArn": component.attrArn }
        ],
        parentImage: props.baseimageArn,
    })

    let squid_infra_config = new image_builder.CfnInfrastructureConfiguration(stack, props.infra_config_name, {
        name: props.infra_config_name,
        instanceTypes: ["t3.medium"],
        instanceProfileName: props.profile_name,
        snsTopicArn: props.snsTopicArn,
        subnetId: props.subnetId,
        securityGroupIds: [props.sgId]
    })
    squid_infra_config.addDependency(instance_profile)

    let pipeline = new image_builder.CfnImagePipeline(stack, props.pipeline_name, {
        name: props.pipeline_name,
        imageRecipeArn: squid_recipe.attrArn,
        infrastructureConfigurationArn: squid_infra_config.attrArn
    })

    pipeline.addDependency(squid_infra_config)
    return pipeline.attrArn

}

export class ImageBuilderStack extends cdk.Stack {
    constructor(scope: Construct, config: ImageBuilderConfig) {
        super(scope, config.name, {
            stackName: config.name,
        });

        let vpcConfig: VpcConfig = {
            name: "imagebuilder-vpc",
            maxAzs: 2,
        };

        const envoy_channel = new Topic(this, 'ImgBuilderNotificationTopicEnvoy', {});
        const squid_channel = new Topic(this, 'ImgBuilderNotificationTopicSquid', {});
        const base_channel = new Topic(this, 'ImgBuilderNotificationTopicBase', {});

        let vpc = new Vpc(this, vpcConfig);

        let subnetId = vpc.vpc.selectSubnets({ subnetType: SubnetType.PUBLIC }).subnetIds[0];
        let ib_SG = new SecurityGroup(this, 'image-server-sg', {
            vpc: vpc.vpc,
            allowAllOutbound: true,
            description: 'security group for a image builder server',
        });

        let role = new iam.Role(this, "StationRole", { roleName: "StationRole", assumedBy: new iam.ServicePrincipal("ec2.amazonaws.com") })

        role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"))
        role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("EC2InstanceProfileForImageBuilder"))

        const base_image_id = config.ami_id || MachineImage.latestAmazonLinux2023().getImage(this).imageId 

        let squid_properties = {
            pipeline_name: "SquidImagePipeline",
            recipe_name: "SquidImageRecipe",
            profile_name: "SquidStationInstanceProfile",
            comp_name: "HyperswitchSquidImageBuilder",
            comp_id: "install_squid_component",
            infra_config_name: "SquidInfraConfig",
            baseimageArn: base_image_id,
            description: "Image builder for squid",
            compFilePath: "./components/squid.yml",
            sgId: ib_SG.securityGroupId,
            subnetId: subnetId,
            snsTopicArn: squid_channel.topicArn,
        };

        let envoy_arn = CreateImagePipeline(
            this,
            role,
            squid_properties,
        )


        let envoy_properties = {
            pipeline_name: "EnvoyImagePipeline",
            recipe_name: "EnvoyImageRecipe",
            profile_name: "EnvoyStationProfile",
            comp_name: "HyperswitchEnvoyImageBuilder",
            comp_id: "install_envoy_component",
            infra_config_name: "EnvoyInfraConfig",
            baseimageArn: base_image_id,
            description: "Image builder for Envoy",
            compFilePath: "./components/envoy.yml",
            sgId: ib_SG.securityGroupId,
            subnetId: subnetId,
            snsTopicArn: envoy_channel.topicArn,
        };

        let squid_arn = CreateImagePipeline(
            this,
            role,
            envoy_properties,
        )


        let base_properties = {
            pipeline_name: "BaseImagePipeline",
            recipe_name: "BaseImageRecipe",
            profile_name: "BaseStationProfile",
            comp_name: "HyperswitchBaseImageBuilder",
            comp_id: "install_base_component",
            infra_config_name: "BaseInfraConfig",
            baseimageArn: base_image_id,
            description: "Image builder for Base Image",
            compFilePath: "./components/base.yml",
            sgId: ib_SG.securityGroupId,
            subnetId: subnetId,
            snsTopicArn: base_channel.topicArn,
        };

        let base_arn = CreateImagePipeline(
            this,
            role,
            base_properties,
        )

        const start_ib_code = readFileSync(
            "lib/aws/lambda/start_ib.py",
        ).toString();


        const lambda_policy = new iam.PolicyDocument({
            statements: [
                new iam.PolicyStatement({
                    effect: iam.Effect.ALLOW,
                    actions: ['imagebuilder:StartImagePipelineExecution'],
                    resources: [
                        `arn:aws:imagebuilder:${cdk.Stack.of(this).region}:${cdk.Stack.of(this).account
                        }:image/*`,
                        `arn:aws:imagebuilder:${cdk.Stack.of(this).region}:${cdk.Stack.of(this).account
                        }:image-pipeline/*`,
                    ],
                }),
                new iam.PolicyStatement({
                    effect: iam.Effect.ALLOW,
                    actions: ['ssm:*'],
                    resources: ["*"],
                }),
            ],
        });

        const lambda_role = new iam.Role(this, "hyperswitch-ib-lambda-role", {
            assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
            inlinePolicies: {
                "ib-start-role": lambda_policy,
            },
        });

        const ib_lambda = new Function(this, "hyperswitch-ib-lambda", {
            functionName: "HyperswitchIbStartLambda",
            runtime: Runtime.PYTHON_3_9,
            handler: "index.lambda_handler",
            code: Code.fromInline(start_ib_code),
            timeout: cdk.Duration.minutes(15),
            role: lambda_role,
            environment: {
                envoy_image_pipeline_arn: envoy_arn,
                squid_image_pipeline_arn: squid_arn,
                base_image_pipeline_arn: base_arn,
            },
        });


        const triggerIbStart = new cdk.CustomResource(
            this,
            "HyperswitchIbStart",
            {
                serviceToken: ib_lambda.functionArn,
            },
        );

        addRecordLambda(this, {
            id: "hyperswitch-record-amid-squid",
            name: "HyperswitchRecordAmiIdSquid",
            role: lambda_role,
            topic: squid_channel,
            ssm_key: "squid_image_ami",
        })

        addRecordLambda(this, {
            id: "hyperswitch-record-amid-envoy",
            name: "HyperswitchRecordAmiIdEnvoy",
            role: lambda_role,
            topic: envoy_channel,
            ssm_key: "envoy_image_ami",
        })

        addRecordLambda(this, {
            id: "hyperswitch-record-amid-base",
            name: "HyperswitchRecordAmiIdBase",
            role: lambda_role,
            topic: base_channel,
            ssm_key: "base_image_ami",
        })
    }
}


function addRecordLambda(stack: cdk.Stack, props: RecordLambdaProperties) {
    const record_amid_code = readFileSync(
        "lib/aws/lambda/record_ami.py"
    ).toString();

    let ib_record_function = new Function(stack, props.id, {
        functionName: props.name,
        runtime: Runtime.PYTHON_3_9,
        handler: "index.lambda_handler",
        code: Code.fromInline(record_amid_code),
        timeout: cdk.Duration.minutes(15),
        role: props.role,
        environment: {
            IMAGE_SSM_NAME: props.ssm_key,
        },
    });

    props.topic.addSubscription(new LambdaSubscription(ib_record_function))
}