简体   繁体   中英

Unable to pass the ec2-instance details while creating AWS network load balancer using AWS CDK for python

I am trying to create two EC2 instances and a Network load balancer using python for AWS-CDK. I am unable to pass in the target type details which are the above two instances while creating the NLB target group. In short, I need to create EC2 instances and attach a network load balance along with it. Please refer to the below code.

from aws_cdk import core 
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_elasticloadbalancingv2 as elb
from aws_cdk import aws_elasticloadbalancingv2_targets as targets
from cdk_splunk_servers.myconstants import *


 class CdkDeploymentStack(core.Stack):

   def __init__(
    self,
    scope: core.Construct,
    construct_id: str,
    env_vars,
    inbound_rules,
    **kwargs
) -> None:
    super().__init__(scope, construct_id, **kwargs)

    myvpc = ec2.Vpc.from_lookup(self, "myvpc", vpc_name=env_vars["vpc_name"])

    ### Create the security group with required ingress rules
    ec2_sg = ec2.SecurityGroup(self, "sg-splunk", vpc=myvpc)
    core.Tags.of(ec2_sg).add("Name", ec2_sg.node.path)

    # Add the required inbound rules to the security group
    for rule in inbound_rules:
        peer = ec2.Peer.ipv4(rule["source"])
        if rule["protocol"] == "tcp":
            if rule["portRange"] == "":
                connection = ec2.Port.tcp(rule["port"])
            else:
                portRange = rule["portRange"].split("-")
                if portRange.__len__() != 2:
                    print("Port range should be in format startport-endport")
                print(dir(ec2.Port))
                connection = ec2.Port.tcp_range(
                    int(portRange[0]), int(portRange[1])
                )
        elif rule["protocol"] == "udp":
            if rule["portRange"] == "":
                connection = ec2.Port.udp(rule["port"])
            else:
                portRange = rule["portRange"].split("-")
                if portRange.__len__() != 2:
                    print("Port range should be in format startport-endport")
                connection = ec2.Port.udp_range(
                    int(portRange[0]), int(portRange[1])
                )
        description = rule["description"]
        ec2_sg.add_ingress_rule(
            peer=peer, connection=connection, description=description
        )
    
    ### Create EC2 instance for Deployment servers
    deployment_01 = ec2.CfnInstance(
        self,
        env_vars["deployment_server_name1"],
        block_device_mappings=[
            ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sda1",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_root_volume"]
                ),
            ),
            ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sdb",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_user_volume1"]
                ),
            ),
            ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sdc",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_user_volume2"]
                ),
            )
        ],
        ebs_optimized=True,
        image_id=env_vars["ami_id_rhel"],
        instance_type=env_vars["instance_type_dep"],
        key_name=env_vars["key_pair_name"],
        security_group_ids=[ec2_sg.security_group_id],
        subnet_id=env_vars["general_subnet1"]
    )
    deployment_02 = ec2.CfnInstance(
        self,
        env_vars["deployment_server_name2"],
        block_device_mappings=[
           ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sda1",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_root_volume"]
                ),
            ),
            ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sdb",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_user_volume1"]
                ),
            ),
            ec2.CfnInstance.BlockDeviceMappingProperty(
                device_name="/dev/sdc",
                ebs=ec2.CfnInstance.EbsProperty(
                    delete_on_termination=False, encrypted=True, volume_size=env_vars["deployment_user_volume2"]
                ),
            )
        ],
        ebs_optimized=True,
        image_id=env_vars["ami_id_rhel"],
        instance_type=env_vars["instance_type_dep"],
        key_name=env_vars["key_pair_name"],
        security_group_ids=[ec2_sg.security_group_id],
        subnet_id=env_vars["general_subnet2"]
    )

   
    myvpc = ec2.Vpc.from_lookup(
        self,
        "SecurityVpc",
        vpc_name=env_vars["vpc_name"],
    )

    subnet_id_1 = env_vars["general_subnet1"]
    subnet_id_2 = env_vars["general_subnet2"]

    # Import the corresponding subnets into CDK
    subnet_1 = ec2.Subnet.from_subnet_id(
        self, id="elbsubnet1", subnet_id=subnet_id_1
    )
    subnet_2 = ec2.Subnet.from_subnet_id(
        self, id="elbsubnet2", subnet_id=subnet_id_2
    )

    ### NLB creation in security account
    nlb_security_deployment_server = elb.NetworkLoadBalancer(
        self,
        env_vars["nlb_name"],
        cross_zone_enabled= True,
        vpc=myvpc,
        vpc_subnets=ec2.SubnetSelection(subnets=[subnet_1, subnet_2]),
        internet_facing=False,
        load_balancer_name=env_vars["nlb_name"],
    )

    # Add a listener on a particular port
    listener_security_deployment_server1 = nlb_security_deployment_server.add_listener(
        "listener1", port=LISTENER_PORT1
    )
    listener_security_deployment_server2 = nlb_security_deployment_server.add_listener(
        "listener2", port=LISTENER_PORT2
    )

    listener_security_deployment_server1.add_targets(
        "tg1-deployment-server-security",
        port=LISTENER_PORT1,
        target_group_name="tg1-deployment-server-security",
        targets=[
            targets.InstanceTarget(
                #NEED HELP HERE
                instance=deployment01,
                port=TARGET_PORT1, 
            ),
            targets.InstanceTarget(
                instance=deployment01,
                port=TARGET_PORT2,
            )
        ],
    )
    listener_security_deployment_server2.add_targets(
        "tg2-deployment-server-security",
        port=LISTENER_PORT2,
        target_group_name="tg2-deployment-server-security",
        targets=[
            targets.InstanceTarget(
                instance=deployment_02,
                port=TARGET_PORT1,
            ),
            targets.InstanceTarget(
                instance=deployment_02,
                port=TARGET_PORT2,
            )
        ],
    )

    core.Tags.of(deployment_01).add("Name", deployment_01.node.path)
    core.Tags.of(deployment_02).add("Name", deployment_02.node.path)

    ### Common Tagging
    core.Tags.of(self).add("Project", PROJECT)
    core.Tags.of(self).add("Environment", env_vars["env_name"])
    core.Tags.of(self).add("CostCenter", COST_CENTER)
    core.Tags.of(self).add("LineOfBusiness", LINE_OF_BUSINESS)
    core.Tags.of(self).add("Owner", OWNER)

The problem is that you're mixing L1 and L2 constructs. So if you use ec2.Instance (L2 construct) rather than ec2.CfnInstance (L1 construct) this should work.

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