Search code examples
pythonamazon-web-servicesamazon-rdsaws-glueaws-cdk

Accessing RDS Instance subnet for Glue Connection using AWS CDK Python


Using CDK in Python, I've created a VPC with Public and Private subnets in two availability zones and deployed an RDS DB Instance into the Private subnets. How can I retrieve the Subnet ID that the RDS Instance is in so that I don't have to hardcode it into this glue connection? I've tried several different iterations of CfnOutputs and CDK constructs, but am not able to get the one that I need. Thanks for taking a look!

        glue_connection = aws_glue.CfnConnection(
        self,
        connection_id,
        catalog_id = self.account_name,
        connection_input = aws_glue.CfnConnection.ConnectionInputProperty(
            name = str(self.glue_connection_name),
            connection_type = 'JDBC',
            physical_connection_requirements = aws_glue.CfnConnection.PhysicalConnectionRequirementsProperty(
                subnet_id = 'PrivateSubnet2',
                security_group_id_list = [self.rds_SG.security_group_id, self.ec2_SG.security_group_id],
                availability_zone = 'us-east-1b',
            ),
            connection_properties = {
                'JDBC_CONNECTION_URL': f'jdbc:mysql://{self.DBInstance.db_instance_endpoint_address}:{self.DBInstance.db_instance_endpoint_port}/test',
                'PASSWORD': self.DBInstance.secret.secret_value_from_json("password").to_string(),
                'USERNAME': self.db_username,
                'JDBC_ENFORCE_SSL': 'false',
            },
        ),
    )

Solution

  • Use the L2 Connection construct - it's simpler - and get the first subnet from the list of subnets that the instance is in:

    
    glue_connection = aws_glue.Connection(
      self,
      "my_connection",
      type=aws_glue.ConnectionType.JDBC,
      properties={
         'JDBC_CONNECTION_URL': f'jdbc:mysql://{self.DBInstance.db_instance_endpoint_address}:{self.DBInstance.db_instance_endpoint_port}/test',
         'PASSWORD': self.DBInstance.secret.secret_value_from_json("password").to_string(),
         'USERNAME': self.db_username,
         'JDBC_ENFORCE_SSL': 'false',
       },
       security_groups=[my_rds_instance.connections.security_groups],
       subnet=my_vpc.private_subnets[0]
    )