def deploy_read_replica()

in static/Reliability/300_Testing_for_Resiliency_of_EC2_RDS_and_S3/Code/Python/ReadReplicaLambda/deploy_read_replica_lambda.py [0:0]


def deploy_read_replica(event):
    logger.debug("Running function deploy_read_replica")
    try:
        region = event['region_name']
        replica_region = event['secondary_region_name']
        cfn_region = event['cfn_region']
        bucket = event['cfn_bucket']
        key_prefix = event['folder']
    except Exception:
        region = os.environ.get('AWS_REGION', AWS_REGION)
        replica_region = os.environ.get('AWS_REGION', AWS_REGION)
        cfn_region = os.environ.get('AWS_REGION', AWS_REGION)
        bucket = "aws-well-architected-labs-ohio",
        key_prefix = "/"

    # Create CloudFormation client to get the VPC in the secondary region
    client = boto3.client('cloudformation', replica_region)

    # Get the outputs of the VPC stack
    vpc_stack = event['vpc']['stackname']
    try:
        stack_response = client.describe_stacks(StackName=vpc_stack)
        stack_list = stack_response['Stacks']
        if (len(stack_list) < 1):
            logger.debug("Cannot find stack named " + vpc_stack + ", so cannot parse outputs as inputs")
            return 1
    except Exception:
        logger.debug("Cannot find stack named " + vpc_stack + ", so cannot parse outputs as inputs")
        sys.exit(1)
    vpc_outputs = stack_list[0]['Outputs']

    # Create the list of subnets to pass
    private_subnets = find_in_outputs(vpc_outputs, 'PrivateSubnets')
    subnet_list = private_subnets.split(',')
    if (len(subnet_list) < 2):
        return 1
    rds_subnet_list = subnet_list[0] + ',' + subnet_list[1]

    # Create the list of security groups to pass
    rds_sg = find_in_outputs(vpc_outputs, 'MySQLSecurityGroup')

    # Find out the DB ID in the source region
    rds_stack = event['rds']['stackname']
    other_region_client = boto3.client('cloudformation', region)
    try:
        stack_response = other_region_client.describe_stacks(StackName=rds_stack)
        stack_list = stack_response['Stacks']
        if (len(stack_list) < 1):
            logger.debug("Cannot find stack named " + rds_stack + ", so cannot parse outputs as inputs")
            return 1
    except Exception:
        logger.debug("Cannot find stack named " + rds_stack + ", so cannot parse outputs as inputs")
        sys.exit(1)

    # Parse the output to find the name of the RDS instance
    rds_outputs = stack_list[0]['Outputs']
    rds_address = find_in_outputs(rds_outputs, 'DBAddress')
    rds_parsed = rds_address.split('.')
    if (len(rds_parsed) < 1):
        return 1
    rds_id = rds_parsed[0]

    # Get workshop name
    try:
        workshop_name = event['workshop']
    except Exception:
        logger.debug("Unexpected error! (when parsing workshop name)\n Stack Trace:", traceback.format_exc())
        workshop_name = 'UnknownWorkshop'
    
    logger.debug("Workshop Name: " + workshop_name)


    # Get DB instance type only if it was specified (it is optional)
    try:
        if 'db_instance_class' in event:
          db_instance_class = event['db_instance_class']
        else:
          db_instance_class = None
    except Exception:
        logger.debug("Unexpected error! (when parsing DB instance class)\n Stack Trace:", traceback.format_exc())
        db_instance_class = None

    # Prepare the stack parameters
    rds_parameters = []
    rds_parameters.append({'ParameterKey': 'SourceDatabaseRegion', 'ParameterValue': region, 'UsePreviousValue': True})
    rds_parameters.append({'ParameterKey': 'SourceDatabaseID', 'ParameterValue': rds_id, 'UsePreviousValue': True})
    rds_parameters.append({'ParameterKey': 'DBSubnetIds', 'ParameterValue': rds_subnet_list, 'UsePreviousValue': True})
    rds_parameters.append({'ParameterKey': 'DBSecurityGroups', 'ParameterValue': rds_sg, 'UsePreviousValue': True})
    rds_parameters.append({'ParameterKey': 'WorkshopName', 'ParameterValue': workshop_name, 'UsePreviousValue': True})
    # If DB instance class supplied then use it, otherwise CloudFormation template will use Parameter default
    if (db_instance_class is not None):
      rds_parameters.append({'ParameterKey': 'DBInstanceClass', 'ParameterValue': db_instance_class, 'UsePreviousValue': True})
    stack_tags = []

    rr_template_s3_url = "https://s3." + cfn_region + ".amazonaws.com/" + bucket + "/" + key_prefix + "mySQL_rds_readreplica.json"
    stack_tags.append({'Key': 'Workshop', 'Value': 'AWSWellArchitectedReliability' + workshop_name})
    client.create_stack(
        StackName=stackname,
        TemplateURL=rr_template_s3_url,
        Parameters=rds_parameters,
        DisableRollback=False,
        TimeoutInMinutes=30,
        Tags=stack_tags
    )

    return_dict = {'stackname': stackname}
    return return_dict