简体   繁体   中英

How to create custom construct library for aws-cdk in python

Recently I have been using aws-cdk to create EC2, VPC and S3 services.

But if I want to create my custom EC2 Library in python(not using JSII) than will be using aws_cdk's aws_ec2 library to actually create the EC2 Instance and a VPC.

The custom library will accept arguments like Instance Name(String) , InstanceType(String) , MachineImage(String) , Subnet Type (String)

Than this arguments will be refer like below:

Disclaimer: Code below Might not be correct

dummy_ec2 = ec2.Instance(self, <InstanceName>, 
                                vpc=<Created_VPC>,
                                instance_type=ec2.InstanceType(<InstanceType>),
                                machine_image=ec2.AmazonLinuxImage(
                                        generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
                                        edition=ec2.AmazonLinuxEdition.STANDARD,
                                        virtualization=ec2.AmazonLinuxVirt.HVM,
                                        storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
                                ),
                                key_name="demo-key",
                                vpc_subnets=ec2.SubnetSelection(subnet_type=<subnet_type>),
                                role=self.my_role
                                )

Any help Devs how to?

To create a construct, you just have to create a class inheriting from aws_cdk.core.Construct , here's an example:

class InstanceWithVPC(aws_cdk.core.Construct):
    def __init__(self, scope: aws_cdk.core.Construct, id: str, *, instanceType, subnet_type, role, key, **kwargs):
        super().__init__(scope, id)
        self.vpc = ec2.Vpc(...)
        self.instance = ec2.Instance(self, id, 
                                vpc=self.vpc,
                                instance_type=ec2.InstanceType(instanceType),
                                machine_image=ec2.AmazonLinuxImage(
                                        generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
                                        edition=ec2.AmazonLinuxEdition.STANDARD,
                                        virtualization=ec2.AmazonLinuxVirt.HVM,
                                        storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
                                ),
                                key_name=key,
                                vpc_subnets=ec2.SubnetSelection(subnet_type),
                                role=role
                                )

Of course keep in mind this is only usable in Python, the benefit of using Typescript would be it'd be usable in other languages too which would make more reusable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM