Beispiel #1
0
def update_vpc_command(args):
    """ handle vpc update command actions"""
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    else:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    if vpc:
        vpc.update(args.dry_run)
    else:
        print("No matching VPC found")
        sys.exit(2)
Beispiel #2
0
def destroy_vpc_command(args):
    """ handle vpc destroy command actions"""
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    else:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    if vpc:
        vpc.destroy()
    else:
        print("No matching VPC found")
        sys.exit(2)
Beispiel #3
0
def destroy_vpc_command(args):
    """ handle vpc destroy command actions"""
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    else:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    if vpc:
        vpc.destroy()
    else:
        print("No matching VPC found")
        sys.exit(2)
Beispiel #4
0
def update_vpc_command(args):
    """ handle vpc update command actions"""
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    else:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    if vpc:
        vpc.update(args.dry_run)
    else:
        print("No matching VPC found")
        sys.exit(2)
Beispiel #5
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    aws = DiscoAWS(config, env)
    disco_elasticache = DiscoElastiCache(vpc, aws=aws)

    if args['list']:
        for cluster in disco_elasticache.list():
            size = 'N/A'
            if cluster['Status'] == 'available':
                size = len(cluster['NodeGroups'][0]['NodeGroupMembers'])
            print("{0:<25} {1:5} {2:>5}".format(cluster['Description'],
                                                cluster['Status'], size))
    elif args['update']:
        if args['--cluster']:
            disco_elasticache.update(args['--cluster'])
        else:
            disco_elasticache.update_all()

    elif args['delete']:
        disco_elasticache.delete(args['--cluster'], wait=args['--wait'])
Beispiel #6
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    if args['list']:
        format_string = "{0:<50} {1:33} {2}"
        print(format_string.format("ELB Name", "Availability Zones", "ELB Id"),
              file=sys.stderr)
        for elb_info in sorted(DiscoELB(vpc).list_for_display()):
            print(
                format_string.format(elb_info['elb_name'],
                                     elb_info['availability_zones'],
                                     elb_info["elb_id"]))
    elif args['update']:
        DiscoAWS(config, env).update_elb(args['--hostclass'])
Beispiel #7
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    aws = DiscoAWS(config, env)
    disco_elasticache = DiscoElastiCache(vpc, aws=aws)

    if args['list']:
        for cluster in disco_elasticache.list():
            size = 'N/A'
            if cluster['Status'] == 'available':
                size = len(cluster['NodeGroups'][0]['NodeGroupMembers'])
            print("{0:<25} {1:5} {2:>5}".format(cluster['Description'],
                                                cluster['Status'],
                                                size))
    elif args['update']:
        if args['--cluster']:
            disco_elasticache.update(args['--cluster'])
        else:
            disco_elasticache.update_all()

    elif args['delete']:
        disco_elasticache.delete(args['--cluster'], wait=args['--wait'])
Beispiel #8
0
def create_vpc_command(args):
    """ handle vpc create command actions"""
    if DiscoVPC.fetch_environment(environment_name=args.vpc_name):
        logging.error("VPC with same name already exists.")
        sys.exit(1)
    else:
        vpc = DiscoVPC(args.vpc_name, args.vpc_type)
        logging.info("VPC %s(%s) has been created", args.vpc_name, vpc.vpc.id)
Beispiel #9
0
def create_vpc_command(args):
    """ handle vpc create command actions"""
    if DiscoVPC.fetch_environment(environment_name=args.vpc_name):
        logging.error("VPC with same name already exists.")
        sys.exit(1)
    else:
        vpc = DiscoVPC(args.vpc_name, args.vpc_type)
        logging.info("VPC %s(%s) has been created", args.vpc_name, vpc.vpc.id)
Beispiel #10
0
def create_vpc_command(args):
    """ handle vpc create command actions"""
    if DiscoVPC.fetch_environment(environment_name=args.vpc_name):
        print("VPC with same name already exists.")
        sys.exit(1)
    else:
        tags = key_values_to_tags(args.tags) if args.tags else None
        vpc = DiscoVPC(args.vpc_name, args.vpc_type, skip_enis_pre_allocate=args.skip_enis,
                       vpc_tags=tags)
        print("VPC {0}({1}) has been created".format(args.vpc_name, vpc.get_vpc_id()))
Beispiel #11
0
def create_vpc_command(args):
    """ handle vpc create command actions"""
    if DiscoVPC.fetch_environment(environment_name=args.vpc_name):
        print("VPC with same name already exists.")
        sys.exit(1)
    else:
        tags = tag2dict(key_values_to_tags(args.tags)) if args.tags else None
        vpc = DiscoVPC(args.vpc_name, args.vpc_type, skip_enis_pre_allocate=args.skip_enis,
                       vpc_tags=tags)
        print("VPC {0}({1}) has been created".format(args.vpc_name, vpc.get_vpc_id()))
Beispiel #12
0
def proxy_peerings_command(args):
    """ handle peerings command actions"""
    if args.vpc_name and args.vpc_id:
        print("Don't use vpc_name and vpc_id at the same time.")
        sys.exit(2)

    vpc = None
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    elif args.vpc_id:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    vpc_id = vpc.get_vpc_id() if vpc else None

    disco_peerings = DiscoVPCPeerings()

    if args.list_peerings:
        vpc_map = {vpc['id']: vpc for vpc in DiscoVPC.list_vpcs()}
        peerings = sorted(
            disco_peerings.list_peerings(vpc_id, include_failed=True),
            key=lambda p: vpc_map.get(p['AccepterVpcInfo']['VpcId'])['tags'].get("Name"))

        for peering in peerings:

            vpc1 = vpc_map.get(peering['AccepterVpcInfo']['VpcId'])
            vpc2 = vpc_map.get(peering['RequesterVpcInfo']['VpcId'])

            line = u"{0:<14} {1:<8} {2:<20} {3:<21}".format(
                peering['VpcPeeringConnectionId'], peering['Status']['Code'], "{}<->{}".format(
                    vpc1['tags'].get("Name") if vpc1 is not None else "",
                    vpc2['tags'].get("Name") if vpc2 is not None else ""),
                "{}<->{}".format(
                    peering['AccepterVpcInfo'].get('CidrBlock'),
                    peering['RequesterVpcInfo'].get('CidrBlock')))
            print(line)
    elif args.delete_peerings:
        disco_peerings.delete_peerings(vpc_id)
    elif args.create_peerings:
        disco_peerings.update_peering_connections(vpc)
Beispiel #13
0
def proxy_peerings_command(args):
    """ handle peerings command actions"""
    if args.vpc_name and args.vpc_id:
        print("Don't use vpc_name and vpc_id at the same time.")
        sys.exit(2)

    vpc = None
    if args.vpc_name:
        vpc = DiscoVPC.fetch_environment(environment_name=args.vpc_name)
    elif args.vpc_id:
        vpc = DiscoVPC.fetch_environment(vpc_id=args.vpc_id)

    vpc_id = vpc.get_vpc_id() if vpc else None

    disco_peerings = DiscoVPCPeerings()

    if args.list_peerings:
        vpc_map = {vpc['id']: vpc for vpc in DiscoVPC.list_vpcs()}
        peerings = sorted(
            disco_peerings.list_peerings(vpc_id, include_failed=True),
            key=lambda p: vpc_map.get(p['AccepterVpcInfo']['VpcId'])['tags'].get("Name"))

        for peering in peerings:

            vpc1 = vpc_map.get(peering['AccepterVpcInfo']['VpcId'])
            vpc2 = vpc_map.get(peering['RequesterVpcInfo']['VpcId'])

            line = u"{0:<14} {1:<8} {2:<20} {3:<21}".format(
                peering['VpcPeeringConnectionId'], peering['Status']['Code'], "{}<->{}".format(
                    vpc1['tags'].get("Name") if vpc1 is not None else "",
                    vpc2['tags'].get("Name") if vpc2 is not None else ""),
                "{}<->{}".format(
                    peering['AccepterVpcInfo'].get('CidrBlock'),
                    peering['RequesterVpcInfo'].get('CidrBlock')))
            print(line)
    elif args.delete_peerings:
        disco_peerings.delete_peerings(vpc_id)
    elif args.create_peerings:
        disco_peerings.update_peering_connections(vpc)
Beispiel #14
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    if args['list']:
        for elb in sorted(DiscoELB(vpc).list()):
            print("{0:<20} {1:25}".format(elb['LoadBalancerName'], ','.join(elb['AvailabilityZones'])))
    elif args['update']:
        DiscoAWS(config, env).update_elb(args['--hostclass'])
Beispiel #15
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    if args['list']:
        for elb in sorted(DiscoELB(vpc).list()):
            print("{0:<20} {1:25}".format(elb['LoadBalancerName'],
                                          ','.join(elb['AvailabilityZones'])))
    elif args['update']:
        DiscoAWS(config, env).update_elb(args['--hostclass'])
Beispiel #16
0
def run():
    """Parses command line and dispatches the commands"""
    args = docopt(__doc__)

    configure_logging(args["--debug"])

    config = read_config()

    env = args.get("--env") or config.get("disco_aws", "default_environment")
    vpc = DiscoVPC.fetch_environment(environment_name=env)
    if not vpc:
        print("Environment does not exist: {}".format(env))
        sys.exit(1)

    if args['list']:
        format_string = "{0:<50} {1:33} {2}"
        print(format_string.format("ELB Name", "Availability Zones", "ELB Id"), file=sys.stderr)
        for elb_info in sorted(DiscoELB(vpc).list_for_display()):
            print(format_string.format(elb_info['elb_name'], elb_info['availability_zones'],
                                       elb_info["elb_id"]))
    elif args['update']:
        DiscoAWS(config, env).update_elb(args['--hostclass'])
Beispiel #17
0
def run():
    """Parses command line and dispatches the commands"""
    config = read_config()

    args = docopt(__doc__)

    configure_logging(args["--debug"])

    env = args["--environment"] or config.get("disco_aws",
                                              "default_environment")

    force_deployable = None if args["--deployable"] is None else is_truthy(
        args["--deployable"])

    pipeline_definition = []
    if args["--pipeline"]:
        with open(args["--pipeline"], "r") as f:
            reader = csv.DictReader(f)
            pipeline_definition = [line for line in reader]

    aws = DiscoAWS(config, env)

    if config.has_option('test', 'env'):
        test_env = config.get('test', 'env')
        test_aws = DiscoAWS(config, test_env)
    else:
        test_aws = aws

    bake = DiscoBake(config, aws.connection)

    if args["--ami"] and args["--hostclass"]:
        image = bake.get_image(args["--ami"])
        if args["--hostclass"] != bake.ami_hostclass(image):
            logger.error('AMI %s does not belong to hostclass %s',
                         args["--ami"], args["--hostclass"])
            sys.exit(1)

    vpc = DiscoVPC.fetch_environment(environment_name=env)

    deploy = DiscoDeploy(aws,
                         test_aws,
                         bake,
                         DiscoGroup(env),
                         DiscoELB(vpc),
                         DiscoSSM(environment_name=env),
                         pipeline_definition=pipeline_definition,
                         ami=args.get("--ami"),
                         hostclass=args.get("--hostclass"),
                         allow_any_hostclass=args["--allow-any-hostclass"])

    if args["test"]:
        try:
            deploy.test(dry_run=args["--dry-run"],
                        deployment_strategy=args["--strategy"],
                        ticket_id=args["--ticket"],
                        force_deployable=force_deployable)
        except RuntimeError as err:
            logger.error(str(err))
            sys.exit(1)
    elif args["update"]:
        try:
            deploy.update(dry_run=args["--dry-run"],
                          deployment_strategy=args["--strategy"],
                          ticket_id=args["--ticket"],
                          force_deployable=force_deployable)
        except RuntimeError as err:
            logger.error(str(err))
            sys.exit(1)
    elif args["list"]:
        missing = "-" if pipeline_definition else ""
        if args["--tested"]:
            for (_hostclass,
                 ami) in deploy.get_latest_tested_amis().iteritems():
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
        elif args["--untested"]:
            for (_hostclass,
                 ami) in deploy.get_latest_untested_amis().iteritems():
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
        elif args["--failed"]:
            for (_hostclass,
                 ami) in deploy.get_latest_failed_amis().iteritems():
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
        elif args["--testable"]:
            for ami in deploy.get_test_amis():
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
        elif args["--updatable"]:
            for ami in deploy.get_update_amis():
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
        elif args["--failures"]:
            failures = deploy.get_failed_amis()
            for ami in failures:
                print("{} {:40} {}".format(
                    ami.id,
                    ami.name.split()[0],
                    deploy.get_integration_test(ami.name.split()[0])
                    or missing))
            sys.exit(1 if failures else 0)