def main()

in network-load-balancer-copy-utility/copy_network_load_balancer.py [0:0]


def main():
    parser = argparse.ArgumentParser(
        description='Create an Network Load Balancer from a '
                    'Classic Load Balancer', usage='%(prog)s --name <elb name> --region')
    parser.add_argument(
        "--name", help="The name of the Classic Load Balancer", required=True)
    parser.add_argument("--region", help="The region of the Classic Load Balancer "
                                         "(will also be used for the Network Load Balancer)",
                        required=True)
    parser.add_argument("--debug", help="debug mode", action='store_true')
    parser.add_argument("--register-targets", help="Register the backend instances of "
                                                   "the Classic Load Balancer with the Network Load Balancer",
                        action='store_true')
    parser.add_argument("--dry-run", help="Validate that the current Classic Load Balancer configuration is compatible "
                                          "with Network Load Balancers, but do not perform create operations",
                        action='store_true')
    parser.add_argument("--allocationid", nargs='+', metavar='', help="Allocation ID for the VPC Elastic \
    IP address you want to associate with the Network Load Balancer")
    # if no options, print help
    if len(sys.argv[1:]) == 0:
        parser.print_help()
        parser.exit()
    args = parser.parse_args()
    load_balancer_name = args.name
    region = args.region
    eipalloc = args.allocationid
    global debug
    debug = args.debug
    global client
    session = botocore.session.get_session()
    session.user_agent_name = 'CopyClassicToNetwork/' + VERSION
    client = session.create_client('elbv2', region_name=region)
    ec2_client = session.create_client('ec2', region_name=region)

    # If input gets allocation ID. Verify allocation ID
    if eipalloc is not None:
        try:
            ip_addresses = ec2_client.describe_addresses(
                AllocationIds=eipalloc)
        except botocore.exceptions.ClientError as exception:
            # Verify if the input allocation IDs exist
            if 'InvalidAllocationID.NotFound' in exception.response['Error']['Code']:
                logger.error(exception.response['Error']['Message'])
        # Verify if the input allocation IDs are not in use
        for ip_address in ip_addresses['Addresses']:
            if 'AssociationId' in ip_address:
                logger.error('The EIPs {} ({}) are already in use'.format(
                    ip_address['PublicIp'], ip_address['AllocationId']))
                eipalloc.remove(ip_address['AllocationId'])
                sys.exit(0)
            if debug:
                logger.debug('EIP is valid and not in use. ')
    else:
        logger.debug(
            'No EIPs are provided. Auto-assign Public IP will be used')
    # validate that an existing NLB with same name does not exist
    if nlb_exist(load_balancer_name):
        logger.error('You already have a load balancer with the name {} in {}'.format(
            load_balancer_name, region))
        sys.exit(1)
    # Obtain Classic Load Balancer data
    elb_data = get_elb_data(load_balancer_name, region)
    # validate known failure scenarios
    if passed_hardfailure_detector(elb_data):
        logger.debug('hardfailure pass')
        softfailurecheck_result = passed_softfailure_detector(elb_data)
        if softfailurecheck_result[0]:
            ssl_hc_path = softfailurecheck_result[1]
            # quit early for dry run operation
            nlb_data = get_nlb_data(
                elb_data, region, load_balancer_name, ssl_hc_path)
            if args.dry_run:
                print ("Your load balancer configuration is supported by this migration utility.")
                print ("Your can find your Network Load Balancer's meta data in the utility log.")
                logger.debug(
                    'Pass both hard failure check and soft failure check.')
                logger.info(nlb_data)
                sys.exit(0)
            nlb_arn = create_nlb(nlb_data, eipalloc)
            target_group_arns = create_target_groups(nlb_data)
            create_listeners(nlb_arn, nlb_data, target_group_arns)
            target_group_attributes(nlb_data)
            add_tags(nlb_data, nlb_arn, target_group_arns)
            if args.register_targets:
                register_backends(target_group_arns, nlb_data)
            print("Your Network Load Balancer is ready!")
            print("Network Load Balancer ARN:")
            print(nlb_arn)
            print("Target group ARNs:")
            for target_group in target_group_arns:
                print(target_group['arn'])
            print("Considerations:")
            print("1. If your Classic Load Balancer is attached to an Auto Scaling group, "
                  "attach the target groups to the Auto Scaling group.")
            print(
                "2. To use Amazon EC2 Container Service (Amazon ECS), register your containers as targets.")
        else:
            logger.error("Soft failure check did not pass")
            sys.exit(1)
    else:
        logger.error("Hard failure check did not pass")