Skip to content

cloud quest - cloud infrastructure with generative AI code errors

0

Hi All, I am getting errors on my code when I run cdk synth and can't figure out what is wrong. Most of the code is copied from the tutorial or generated by Code Editor. Error message and code below.

error

from aws_cdk import ( Duration, Stack, SecretValue, aws_ec2 as ec2, aws_rds as rds, aws_iam as iam, aws_elasticloadbalancingv2 as elbv2, ) from constructs import Construct

class CdkappStack(Stack):

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

    # create a vpc with IpAddresses 10.10.0.0/16, a NAT gateway, a public subnet, PRIVATE_WITH_EGRESS subnet and a RDS subnet
    vpc = ec2.Vpc(
        self,
        "VPC",
        ip_addresses=ec2.IpAddresses.cidr("10.10.0.0/16"),
        subnet_configuration=[
            ec2.SubnetConfiguration(
                name="Public",
                subnet_type=ec2.SubnetType.PUBLIC,
                cidr_mask=24,
            ),
            ec2.SubnetConfiguration(
                name="PrivateWithEgress",
                subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
                cidr_mask=24,
            ),
            ec2.SubnetConfiguration(
                name="Private",
                subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
                cidr_mask=24,
            ),
            ec2.SubnetConfiguration(
                name="RDS",
                subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
                cidr_mask=24,
            ),
        ],
    )


    # create a security group for the load balancer
    alb_sg = ec2.SecurityGroup(
        self,
        "ALBSG",
        vpc=vpc,
        allow_all_outbound=True,
    )

    # create a security group for the RDS instance
    rds_sg = ec2.SecurityGroup(
        self,
        "RDSSecurityGroup",
        vpc=vpc,
        allow_all_outbound=True,
    )

    # create a security group for the EC2 instance
    ec2_sg = ec2.SecurityGroup(
        self,
        "EC2SecurityGroup",
        vpc=vpc,
        allow_all_outbound=True,
    )

    # add ingress rules for the load balancer security group to allow all traffic on port 80
    alb_sg.add_ingress_rule(
        peer=ec2.Peer.any_ipv4(),
        connection=ec2.Port.tcp(80),
    )
   

    # add ingress rule for the EC2 instance security group to allow 8443 traffic from the load balance
    ec2_sg.add_ingress_rule(
        peer=alb_sg,
        connection=ec2.Port.tcp(8443),
    )

    # add ingress rule to RDS security group to allow 3306 traffic from EC2 security group
    rds_sg.add_ingress_rule(
        peer=ec2_sg,
        connection=ec2.Port.tcp(3306),
    )

    # add ingress rule for the RDS security group to allow 22 from the EC2 instance
    rds_sg.add_ingress_rule(
        peer=ec2_sg,
        connection=ec2.Port.tcp(22),
    )

# create an rds aurora mysql cluster
cluster = rds.DatabaseCluster(self, "MyDatabase",
        engine = rds.DatabaseClusterEngine.aurora_mysql(version = rds.AuroraMysqlEngineVersion.VER_3_04_0),
        # credentials using testuser and password1234!
        credentials = rds.Credentials.from_password("testuser", SecretValue.unsafe_plain_text("password1234!")),
        # add default database name Population
        default_database_name = "Population",
        instance_props={
            "vpc": vpc,
            "security_groups": [rds_sg],
            "vpc_subnets": ec2.SubnetSelection(subnet_type = ec2.SubnetType.PRIVATE_ISOLATED)
        },
        instances = 1
        )

# define an Amazon Linux 2023 image
ami = ec2.MachineImage.latest_amazon_linux2023()

# read userdata.sh file from cdkapp directory using readlines
with open("cdkapp/userdata.sh", "r") as f:
    userdata = f.readlines()

# Add each line from the script to ec2 UserData
ec2_user_data = ec2.UserData.for_linux()
for line in userdata:
    ec2_user_data.add_commands(line.strip())

create a t3.small ec2 instance for the web server in a private egress subnet and vpc.availability_zones[0]

ec2_instance = ec2.Instance(self, "MyInstance",
        instance_type = ec2.InstanceType("t3.small"),
        machine_image = amzn_linux,
        vpc = vpc,
        vpc_subnets = ec2.SubnetSelection(subnet_type = ec2.SubnetType.PRIVATE_WITH_EGRESS),
        availability_zone = vpc.availability_zones[0],
        user_data = user_data,
        security_group = ec2_sg,
        # add an existing role with name ec2_instance_role
        role = iam.Role.from_role_name(self, "ec2_instance_role", "ec2_instance_role")
)
    

# add depends
ec2_instance.node.add_dependency(cluster)

# create a load balancer in the public subnet
alb = elbv2.ApplicationLoadBalancer(
    self,
    "ALB",
    vpc=vpc,
    internet_facing=True,
    security_group=alb_sg
)

# add a listener on port 80 to the load balancer with open=True
listener = alb.add_listener("Listener", port=80, open=True)

# add targets to the load balancer using port 80 with unhealthy healthcheck threshold count 5

listener.add_targets("Target", port=80, targets=[ec2_instance], health_check=elbv2.HealthCheck(
    enabled=True,
    healthy_threshold_count=5,
    interval=Duration.seconds(60),
    path="/",
    timeout=Duration.seconds(10),
    unhealthy_threshold_count=2
))   

# add depends on for the listener to wait for the ec2 instance
listener.node.add_dependency(ec2_instance)
2 Answers
1

Hello.

If you look at the code, there doesn't seem to be any problem, but Python will generate an error if the indentation is incorrect.
Please adjust the indentation to fit within "def __init__" as shown below.
https://docs.aws.amazon.com/cdk/api/v2/python/aws_cdk.aws_rds/DatabaseCluster.html

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


    # create an rds aurora mysql cluster
    cluster = rds.DatabaseCluster(self, "MyDatabase",
EXPERT

answered 2 years ago

  • Many thanks, after playing around for a while, this worked. It looks like on the demo pictures, some were scrolled across so the full indents weren't shown

0

It appears you're encountering some errors while trying to run cdk synth for your Cloud Quest - Cloud Infrastructure with Generative AI project. Let's address a few issues in your code:

  1. The amzn_linux variable is not defined. You've defined ami as the Amazon Linux 2023 image, but you're using amzn_linux in the EC2 instance creation. Change machine_image = amzn_linux to machine_image = ami.

  2. The user_data variable in the EC2 instance creation should be ec2_user_data, which is what you defined earlier.

  3. In the RDS cluster creation, you're using SecretValue.unsafe_plain_text() for the password. While this works, it's not recommended for production use as it exposes the password in plain text. Consider using AWS Secrets Manager for sensitive information in a production environment.

  4. The availability_zone parameter in the EC2 instance creation might cause issues if the chosen AZ doesn't have a PRIVATE_WITH_EGRESS subnet. Consider removing this parameter to let AWS choose an appropriate AZ.

  5. Make sure the ec2_instance_role exists in your AWS account before referencing it.

  6. The health check settings for the ALB target group are quite lenient. Consider adjusting these values for better responsiveness to instance health changes.

After making these changes, try running cdk synth again. If you still encounter issues, double-check that all imported modules are correctly installed and that you're using the latest compatible versions of the AWS CDK and its dependencies.

Remember to bootstrap your CDK environment if you haven't already done so, especially if this is a new account or region. You can do this by running cdk bootstrap before attempting to deploy.

If the error persists, you may need to check your AWS credentials and ensure you have the necessary permissions to create these resources. Also, verify that you're not hitting any service limits in your AWS account.
Sources
Cloud Quest: Infrastructure with Generative AI issue | AWS re:Post
AWS Cloud Quest - Improve Code Quality using Generative AI Project | AWS re:Post
AWS CDK: Create a Subnet and Launch Instance in it With Existing VPC | AWS re:Post

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.