Beispiel #1
0
def delete_rax_cbs(args):
    """Function for deleting Cloud Networks"""
    print("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re)
    for region in pyrax.identity.services.network.regions:
        cbs = pyrax.connect_to_cloud_blockstorage(region=region)
        for volume in cbs.list():
            if re.search(args.match_re, volume.name):
                prompt_and_delete(volume,
                                  'Delete matching %s? [y/n]: ' % volume,
                                  args.assumeyes)
Beispiel #2
0
def delete_rax_cbs(args):
    """Function for deleting Cloud Networks"""
    print ("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re)
    for region in pyrax.identity.services.network.regions:
        cbs = pyrax.connect_to_cloud_blockstorage(region=region)
        for volume in cbs.list():
            if re.search(args.match_re, volume.name):
                prompt_and_delete(volume,
                                  'Delete matching %s? [y/n]: ' % volume,
                                  args.assumeyes)
def _get_driver(driver_type, region='ORD'):
    """
    Returns the appropriate diver for the specified rackspace product.

    Available options include::
        lb: Cloud Load Balancers
        db: Cloud Databases
        dns: Cloud DNS
        bs: Cloud Block Storage
        mon: Cloud Monitoring
        net: Cloud Networks
        cf: Cloud Files
        cs: Cloud Servers

    :param driver_type: A str or unicode object for the appropriate type of
    driver above.
    :param region: A str or unicode object specify which region the driver
    should be initialized for.
    :return: A driver object initialized to the specified region
    :raise TypeError:
    :raise KeyError: If no valid drivers are found
    """
    _auth()
    if not isinstance(driver_type, six.string_types):
        raise TypeError("driver_type must be str or unicode object")
    if not isinstance(region, six.string_types):
        raise TypeError("region must be str or unicode object")
    region = region.upper()

    if driver_type == "lb":
        return pyrax.connect_to_cloud_loadbalancers(region)

    if driver_type == "db":
        return pyrax.connect_to_cloud_databases(region)

    if driver_type == "dns":
        return pyrax.connect_to_cloud_dns()

    if driver_type == "bs":
        return pyrax.connect_to_cloud_blockstorage(region)

    if driver_type == "mon":
        return pyrax.connect_to_cloud_monitoring(region)

    if driver_type == "net":
        return pyrax.connect_to_cloud_networks(region)

    if driver_type == 'cf':
        return pyrax.connect_to_cloudfiles(region)

    if driver_type == 'cs':
        return pyrax.connect_to_cloudservers(region)

    raise KeyError(u"No Driver found by: {}".format(driver_type))
def _get_driver(driver_type, region='ORD'):
    """
    Returns the appropriate diver for the specified rackspace product.

    Available options include::
        lb: Cloud Load Balancers
        db: Cloud Databases
        dns: Cloud DNS
        bs: Cloud Block Storage
        mon: Cloud Monitoring
        net: Cloud Networks
        cf: Cloud Files
        cs: Cloud Servers

    :param driver_type: A str or unicode object for the appropriate type of
    driver above.
    :param region: A str or unicode object specify which region the driver
    should be initialized for.
    :return: A driver object initialized to the specified region
    :raise TypeError:
    :raise KeyError: If no valid drivers are found
    """
    _auth()
    if not isinstance(driver_type, six.string_types):
        raise TypeError("driver_type must be str or unicode object")
    if not isinstance(region, six.string_types):
        raise TypeError("region must be str or unicode object")
    region = region.upper()

    if driver_type == "lb":
        return pyrax.connect_to_cloud_loadbalancers(region)

    if driver_type == "db":
        return pyrax.connect_to_cloud_databases(region)

    if driver_type == "dns":
        return pyrax.connect_to_cloud_dns()

    if driver_type == "bs":
        return pyrax.connect_to_cloud_blockstorage(region)

    if driver_type == "mon":
        return pyrax.connect_to_cloud_monitoring(region)

    if driver_type == "net":
        return pyrax.connect_to_cloud_networks(region)

    if driver_type == 'cf':
        return pyrax.connect_to_cloudfiles(region)

    if driver_type == 'cs':
        return pyrax.connect_to_cloudservers(region)

    raise KeyError(u"No Driver found by: {}".format(driver_type))
def _list_into_cache(regions):
    groups = collections.defaultdict(list)
    hostvars = collections.defaultdict(dict)
    images = {}
    cbs_attachments = collections.defaultdict(dict)

    prefix = get_config(p, 'rax', 'meta_prefix', 'RAX_META_PREFIX', 'meta')

    try:
        # Ansible 2.3+
        networks = get_config(p,
                              'rax',
                              'access_network',
                              'RAX_ACCESS_NETWORK',
                              'public',
                              value_type='list')
    except TypeError:
        # Ansible 2.2.x and below
        # pylint: disable=unexpected-keyword-arg
        networks = get_config(p,
                              'rax',
                              'access_network',
                              'RAX_ACCESS_NETWORK',
                              'public',
                              islist=True)
    try:
        try:
            # Ansible 2.3+
            ip_versions = map(
                int,
                get_config(p,
                           'rax',
                           'access_ip_version',
                           'RAX_ACCESS_IP_VERSION',
                           4,
                           value_type='list'))
        except TypeError:
            # Ansible 2.2.x and below
            # pylint: disable=unexpected-keyword-arg
            ip_versions = map(
                int,
                get_config(p,
                           'rax',
                           'access_ip_version',
                           'RAX_ACCESS_IP_VERSION',
                           4,
                           islist=True))
    except:
        ip_versions = [4]
    else:
        ip_versions = [v for v in ip_versions if v in [4, 6]]
        if not ip_versions:
            ip_versions = [4]

    # Go through all the regions looking for servers
    for region in regions:
        # Connect to the region
        cs = pyrax.connect_to_cloudservers(region=region)
        if cs is None:
            warnings.warn(
                'Connecting to Rackspace region "%s" has caused Pyrax to '
                'return None. Is this a valid region?' % region,
                RuntimeWarning)
            continue
        for server in cs.servers.list():
            # Create a group on region
            groups[region].append(server.name)

            # Check if group metadata key in servers' metadata
            group = server.metadata.get('group')
            if group:
                groups[group].append(server.name)

            for extra_group in server.metadata.get('groups', '').split(','):
                if extra_group:
                    groups[extra_group].append(server.name)

            # Add host metadata
            for key, value in to_dict(server).items():
                hostvars[server.name][key] = value

            hostvars[server.name]['rax_region'] = region

            for key, value in iteritems(server.metadata):
                groups['%s_%s_%s' % (prefix, key, value)].append(server.name)

            groups['instance-%s' % server.id].append(server.name)
            groups['flavor-%s' % server.flavor['id']].append(server.name)

            # Handle boot from volume
            if not server.image:
                if not cbs_attachments[region]:
                    cbs = pyrax.connect_to_cloud_blockstorage(region)
                    for vol in cbs.list():
                        if boolean(vol.bootable, strict=False):
                            for attachment in vol.attachments:
                                metadata = vol.volume_image_metadata
                                server_id = attachment['server_id']
                                cbs_attachments[region][server_id] = {
                                    'id': metadata['image_id'],
                                    'name': slugify(metadata['image_name'])
                                }
                image = cbs_attachments[region].get(server.id)
                if image:
                    server.image = {'id': image['id']}
                    hostvars[server.name]['rax_image'] = server.image
                    hostvars[server.name]['rax_boot_source'] = 'volume'
                    images[image['id']] = image['name']
            else:
                hostvars[server.name]['rax_boot_source'] = 'local'

            try:
                imagegroup = 'image-%s' % images[server.image['id']]
                groups[imagegroup].append(server.name)
                groups['image-%s' % server.image['id']].append(server.name)
            except KeyError:
                try:
                    image = cs.images.get(server.image['id'])
                except cs.exceptions.NotFound:
                    groups['image-%s' % server.image['id']].append(server.name)
                else:
                    images[image.id] = image.human_id
                    groups['image-%s' % image.human_id].append(server.name)
                    groups['image-%s' % server.image['id']].append(server.name)

            # And finally, add an IP address
            ansible_ssh_host = None
            # use accessIPv[46] instead of looping address for 'public'
            for network_name in networks:
                if ansible_ssh_host:
                    break
                if network_name == 'public':
                    for version_name in ip_versions:
                        if ansible_ssh_host:
                            break
                        if version_name == 6 and server.accessIPv6:
                            ansible_ssh_host = server.accessIPv6
                        elif server.accessIPv4:
                            ansible_ssh_host = server.accessIPv4
                if not ansible_ssh_host:
                    addresses = server.addresses.get(network_name, [])
                    for address in addresses:
                        for version_name in ip_versions:
                            if ansible_ssh_host:
                                break
                            if address.get('version') == version_name:
                                ansible_ssh_host = address.get('addr')
                                break
            if ansible_ssh_host:
                hostvars[server.name]['ansible_ssh_host'] = ansible_ssh_host

    if hostvars:
        groups['_meta'] = {'hostvars': hostvars}

    with open(get_cache_file_path(regions), 'w') as cache_file:
        json.dump(groups, cache_file)
Beispiel #6
0
def main():

    default_creds_file = os.path.join(os.path.expanduser("~"), 
        ".rackspace_cloud_credentials")

    parser = argparse.ArgumentParser(description = "Deletes all objects in "
        "various cloud resource categories.", 
        epilog = "Ex: {} -r ORD --servers --images --load_balancers - delete "
        "all cloud servers, custom images, and load balancers in ORD "
        "region".format(__file__))
    parser.add_argument('-r', '--region', required = True, 
        choices = ['DFW', 'ORD', 'LON'], 
        help = "Cloud Servers region to delete from")
    parser.add_argument('-a', '--all', action = 'store_true', 
        help = "Delete all items in region; equiv to setting all option args")
    parser.add_argument('-s', '--servers', action = 'store_true', 
        help = "Delete all Cloud Servers")
    parser.add_argument('-i', '--images', action = 'store_true', 
        help = "Delete all custom Cloud Server images")
    parser.add_argument('-l', '--load_balancers', action = 'store_true', 
        help = "Delete all Cloud Load Balancers")
    parser.add_argument('-f', '--files', action = 'store_true', 
        help = "Delete all Cloud Files containers and objects")
    parser.add_argument('-d', '--databases', action = 'store_true', 
        help = "Delete all Cloud Database databases and instances")
    parser.add_argument('-n', '--networks', action = 'store_true', 
        help = "Delete all custom Cloud Networks")
    parser.add_argument('-b', '--block_storage', action = 'store_true', 
        help = "Delete all Cloud Block Storage volumes")
    parser.add_argument('-c', '--creds_file', default = default_creds_file, 
        help = "Location of credentials file; defaults to {}".format(default_creds_file))

    args = parser.parse_args()

    pyrax.set_setting("identity_type", "rackspace")
    creds_file = os.path.abspath(os.path.expanduser(args.creds_file)) 
    pyrax.set_credential_file(creds_file)

    if(args.all):
        args.servers = True
        args.images = True
        args.load_balancers = True
        args.files = True
        args.databases = True
        args.networks = True
        args.block_storage = True

    if(args.servers):
        cs = pyrax.connect_to_cloudservers(region = args.region)
        servers = cs.servers.list()
        print "Deleting {} Cloud Servers...".format(len(servers))
        delete_resources(servers)

    if(args.images):
        custom_images = []
        cs = pyrax.connect_to_cloudservers(region = args.region)
        images = cs.images.list()
        for image in images:
            if not image.metadata['image_type'] == 'base':
                custom_images.append(image)
        print "Deleting {} custom server images...".format(len(custom_images))
        delete_resources(custom_images)

    if(args.load_balancers):
        clb = pyrax.connect_to_cloud_loadbalancers(region = args.region)
        lbs = clb.list()
        print "Deleting {} Cloud Load Balancers...".format(len(lbs))
        delete_resources(lbs)

    if(args.files):
        cf = pyrax.connect_to_cloudfiles(region = args.region)
        for container in cf.get_all_containers():
            print "Emptying Cloud Files container '{}'...".format(container.name)
            delete_resources(container.get_objects(full_listing = True))
            while len(container.get_objects(limit = 1)) > 0:
                time.sleep(5)
            print "Deleting container '{}'...".format(container.name)
            container.delete()

    if(args.databases):
        cdb = pyrax.connect_to_cloud_databases(region = args.region)
        instances = cdb.list()
        print "Deleting {} Cloud Database instances...".format(len(instances))
        delete_resources(instances)

    if(args.networks):
        custom_networks = []
        cnw = pyrax.connect_to_cloud_networks(region = args.region)
        networks = cnw.list()
        for network in networks:
            if not network.label == 'public' and not network.label == 'private':
                custom_networks.append(network)
        print "Deleting {} custom Cloud Networks...".format(len(custom_networks))
        delete_resources(custom_networks)

    if(args.block_storage):
        cbs = pyrax.connect_to_cloud_blockstorage(region = args.region)
        volumes = cbs.list()
        print "Deleting {} Cloud Block Storage volumes...".format(len(volumes))
        delete_resources(volumes)
Beispiel #7
0
def _list(regions):
    groups = collections.defaultdict(list)
    hostvars = collections.defaultdict(dict)
    images = {}
    cbs_attachments = collections.defaultdict(dict)

    prefix = get_config(p, 'rax', 'meta_prefix', 'RAX_META_PREFIX', 'meta')

    networks = get_config(p, 'rax', 'access_network', 'RAX_ACCESS_NETWORK',
                          'public', islist=True)
    try:
        ip_versions = map(int, get_config(p, 'rax', 'access_ip_version',
                                          'RAX_ACCESS_IP_VERSION', 4,
                                          islist=True))
    except:
        ip_versions = [4]
    else:
        ip_versions = [v for v in ip_versions if v in [4, 6]]
        if not ip_versions:
            ip_versions = [4]

    # Go through all the regions looking for servers
    for region in regions:
        # Connect to the region
        cs = pyrax.connect_to_cloudservers(region=region)
        if cs is None:
            warnings.warn(
                'Connecting to Rackspace region "%s" has caused Pyrax to '
                'return a NoneType. Is this a valid region?' % region,
                RuntimeWarning)
            continue
        for server in cs.servers.list():
            # Create a group on region
            groups[region].append(server.name)

            # Check if group metadata key in servers' metadata
            group = server.metadata.get('group')
            if group:
                groups[group].append(server.name)

            for extra_group in server.metadata.get('groups', '').split(','):
                if extra_group:
                    groups[extra_group].append(server.name)

            # Add host metadata
            for key, value in to_dict(server).items():
                hostvars[server.name][key] = value

            hostvars[server.name]['rax_region'] = region

            for key, value in server.metadata.iteritems():
                groups['%s_%s_%s' % (prefix, key, value)].append(server.name)

            groups['instance-%s' % server.id].append(server.name)
            groups['flavor-%s' % server.flavor['id']].append(server.name)

            # Handle boot from volume
            if not server.image:
                if not cbs_attachments[region]:
                    cbs = pyrax.connect_to_cloud_blockstorage(region)
                    for vol in cbs.list():
                        if mk_boolean(vol.bootable):
                            for attachment in vol.attachments:
                                metadata = vol.volume_image_metadata
                                server_id = attachment['server_id']
                                cbs_attachments[region][server_id] = {
                                    'id': metadata['image_id'],
                                    'name': slugify(metadata['image_name'])
                                }
                image = cbs_attachments[region].get(server.id)
                if image:
                    server.image = {'id': image['id']}
                    hostvars[server.name]['rax_image'] = server.image
                    hostvars[server.name]['rax_boot_source'] = 'volume'
                    images[image['id']] = image['name']
            else:
                hostvars[server.name]['rax_boot_source'] = 'local'

            try:
                imagegroup = 'image-%s' % images[server.image['id']]
                groups[imagegroup].append(server.name)
                groups['image-%s' % server.image['id']].append(server.name)
            except KeyError:
                try:
                    image = cs.images.get(server.image['id'])
                except cs.exceptions.NotFound:
                    groups['image-%s' % server.image['id']].append(server.name)
                else:
                    images[image.id] = image.human_id
                    groups['image-%s' % image.human_id].append(server.name)
                    groups['image-%s' % server.image['id']].append(server.name)

            # And finally, add an IP address
            ansible_ssh_host = None
            # use accessIPv[46] instead of looping address for 'public'
            for network_name in networks:
                if ansible_ssh_host:
                    break
                if network_name == 'public':
                    for version_name in ip_versions:
                        if ansible_ssh_host:
                            break
                        if version_name == 6 and server.accessIPv6:
                            ansible_ssh_host = server.accessIPv6
                        elif server.accessIPv4:
                            ansible_ssh_host = server.accessIPv4
                if not ansible_ssh_host:
                    addresses = server.addresses.get(network_name, [])
                    for address in addresses:
                        for version_name in ip_versions:
                            if ansible_ssh_host:
                                break
                            if address.get('version') == version_name:
                                ansible_ssh_host = address.get('addr')
                                break
            if ansible_ssh_host:
                hostvars[server.name]['ansible_ssh_host'] = ansible_ssh_host

    if hostvars:
        groups['_meta'] = {'hostvars': hostvars}
    print(json.dumps(groups, sort_keys=True, indent=4))
Beispiel #8
0
def main():

    default_creds_file = os.path.join(os.path.expanduser("~"), 
        ".rackspace_cloud_credentials")

    parser = argparse.ArgumentParser(description = "Creates multiple Cloud "
        "Servers and places them behind a new Cloud Load Balancer.", 
        epilog = "Ex: {} challenge11.py -r DFW -b test -n 3 -i 'Ubuntu 11.10' -f "
        "512 -e test_network_3 -g '192.168.8.0/24' -s 120 -u SATA -x "
        "blockstore -l testlb -d chal11.derekremund.com -y server.crt -k "
        "server.key".format(__file__))

    parser.add_argument("-r", "--region", required = True, 
        choices = ['DFW', 'ORD', 'LON'], 
        help = "Cloud Servers region to connect to.")
    parser.add_argument("-b", "--base", required = True, 
        help = "Base name for servers.")
    parser.add_argument("-n", "--number", type = int, default = 2, 
        help = "Number of servers to build; default is 2.")
    parser.add_argument("-i", "--image_name", 
        help = "Image name to use to build server.  Menu provided if absent.")
    parser.add_argument("-f", "--flavor_ram", type = int, 
        help = "RAM of flavor to use in MB.  Menu provided if absent.")
    parser.add_argument("-e", "--network_name", required = True, 
        help = "Name of Cloud Network to create.")
    parser.add_argument("-g", "--network_cidr", required = True, 
        help = "CIDR block for new network, e.g. '192.168.0.0/24'.")
    parser.add_argument("-s", "--volume_size", type = int, default = 100, 
        help = "Size of block storage volume to add to servers in GB; "
        "defaults to 100.")
    parser.add_argument("-u", "--volume_type", default = "SATA", 
        choices = ["SATA", "SSD"], 
        help = "Type of cloud block storage volume to add to servers; "
        "defaults to SATA.")
    parser.add_argument("-x", "--volume_name", 
        help = "Volume name for CBS servers.  Will be appended to server "
        "names; randomly generated if not supplied.")
    parser.add_argument("-z", "--mount_point", default = "/dev/xvdb", 
        help = "Mount point for CBS volume; defaults to /dev/xvdb.")
    parser.add_argument("-l", "--lb_name", required = True, 
        help = "Name of load balancer to create")
    parser.add_argument("-y", "--ssl_cert", required = True, 
        help = "File containing SSL certificate for load balancer.")
    parser.add_argument("-k", "--ssl_key", required = True, 
        help = "File containing SSL key for load balancer.")
    parser.add_argument("-d", "--dns_fqdn", required = True, 
        help = "FQDN for DNS A record pointing to LB VIP.")
    parser.add_argument("-t", "--ttl", type = int, default = 300, 
        help = "TTL for DNS A record; defaults to 300.")
    parser.add_argument("-p", "--port", type = int, default = 80, 
        help = "Port to load balance; defaults to 80.")
    parser.add_argument("-q", "--protocol", default = "HTTP", 
        help = "Protocol to load balance; defaults to HTTP")
    parser.add_argument("-v", "--vip_type", default = "PUBLIC",
        choices = ["PUBLIC", "PRIVATE"], help = "VIP type; defaults to PUBLIC.")
    parser.add_argument('-c', '--creds_file', default = default_creds_file, 
        help = "Location of credentials file; defaults to {}".format(default_creds_file))

    args = parser.parse_args()

    pyrax.set_setting("identity_type", "rackspace")
    creds_file = os.path.abspath(os.path.expanduser(args.creds_file)) 
    pyrax.set_credential_file(creds_file)

    cs = pyrax.connect_to_cloudservers(region = args.region)
    cnw = pyrax.connect_to_cloud_networks(region = args.region)
    clb = pyrax.connect_to_cloud_loadbalancers(region = args.region)
    cbs = pyrax.connect_to_cloud_blockstorage(region = args.region)
    dns = pyrax.cloud_dns

    if args.flavor_ram is None:
        flavor = choose_flavor(cs, "Choose a flavor ID: ")
    else:
        flavor = [flavor for flavor in cs.flavors.list() 
            if flavor.ram == args.flavor_ram]
        if flavor is None or len(flavor) < 1:
            flavor = choose_flavor(cs, 
                "Specified flavor not found.  Choose a flavor ID: ")
        else:
            flavor = flavor[0]

    if args.image_name is None:
        image = choose_image(cs, "Choose an image: ")
    else:
        image = [img for img in cs.images.list() if args.image_name in img.name]
        if image is None or len(image) < 1:
            image = choose_image(cs, "Image matching '{}' not found.  Select image: ".format(args.image_name))
        else:
            image = image[0]
    
    try:
        new_net = cnw.create(args.network_name, cidr=args.network_cidr)
        print "\nNetwork created:", new_net
    except Exception, e:
        print "Error creating cloud network:", e
        sys.exit(1)
  parser.add_argument("--lbname", default=False,
                      help="Name of Loadbalancer to create")
  parser.add_argument("--region", default='DFW',
                      help="Region in which to create devices (DFW or ORD)")
  args = parser.parse_args()

  credential_file=os.path.expanduser("~/.rackspace_cloud_credentials")
  pyrax.set_credential_file(credential_file)
  if (c1.is_valid_region(args.region, 'compute') and
      c1.is_valid_region(args.region, 'load_balancer') and
      c1.is_valid_region(args.region, 'volume')):
    cs = pyrax.connect_to_cloudservers(region=args.region)
    dns = pyrax.connect_to_cloud_dns(region=args.region)
    clb = pyrax.connect_to_cloud_loadbalancers(region=args.region)
    cn = pyrax.connect_to_cloud_networks(region=args.region)
    cbs = pyrax.connect_to_cloud_blockstorage(region=args.region)
  else:
    print "The region you requested is not valid: %s" % args.region
    sys.exit(2)

  if not args.sslcertfile or not args.sslkeyfile:
    print "You didn't supply an SSL certificate and key.",
    print "No worries! We'll create one for you...\n"
    (cert, key) = create_self_signed_cert(args.FQDN) 
  else:
    sslCertFile = os.path.expanduser(args.sslcertfile)
    if not os.path.isfile(sslCertFile):
      print 'The specified SSL Cert file "%s" does not exist' % sslCertFile
      sys.exit(3)
  
    sslKeyFile = os.path.expanduser(args.sslkeyfile)
                        required=True,
                        help='Set\'s the account API key')
    parser.add_argument('--region',
                        '-r',
                        required=True,
                        help='Set\'s the account region')
    args = parser.parse_args()

    pyrax.set_credentials(username=args.user,
                          api_key=args.apikey,
                          region=args.region)
    if args.region == 'ORD':
        cs = pyrax.connect_to_cloudservers("ORD")
        cdb = pyrax.connect_to_cloud_databases("ORD")
        cnw = pyrax.connect_to_cloud_networks("ORD")
        cbs = pyrax.connect_to_cloud_blockstorage("ORD")
        dns = pyrax.connect_to_cloud_dns("ORD")
        lbs = pyrax.connect_to_cloud_loadbalancers("ORD")
    elif args.region == 'DFW':
        cs = pyrax.connect_to_cloudservers("DFW")
        cdb = pyrax.connect_to_cloud_databases("DFW")
        cnw = pyrax.connect_to_cloud_networks("DFW")
        cbs = pyrax.connect_to_cloud_blockstorage("DFW")
        dns = pyrax.connect_to_cloud_dns("DFW")
        lbs = pyrax.connect_to_cloud_loadbalancers("DFW")
    elif args.region == 'LON':
        cs = pyrax.connect_to_cloudservers("LON")
        cdb = pyrax.connect_to_cloud_databases("LON")
        cnw = pyrax.connect_to_cloud_networks("LON")
        cbs = pyrax.connect_to_cloud_blockstorage("LON")
        dns = pyrax.connect_to_cloud_dns("LON")
    parser = argparse.ArgumentParser(description='Builds servers')
    parser.add_argument(
        '--user', '-u', required=True, help='Set\'s the account user')
    parser.add_argument(
        '--apikey', '-k', required=True, help='Set\'s the account API key')
    parser.add_argument(
        '--region', '-r', required=True, help='Set\'s the account region')
    args = parser.parse_args()

    pyrax.set_credentials(
        username=args.user, api_key=args.apikey, region=args.region)
    if args.region == 'ORD':
        cs = pyrax.connect_to_cloudservers("ORD")
        cdb = pyrax.connect_to_cloud_databases("ORD")
        cnw = pyrax.connect_to_cloud_networks("ORD")
        cbs = pyrax.connect_to_cloud_blockstorage("ORD")
        dns = pyrax.connect_to_cloud_dns("ORD")
        lbs = pyrax.connect_to_cloud_loadbalancers("ORD")
    elif args.region == 'DFW':
        cs = pyrax.connect_to_cloudservers("DFW")
        cdb = pyrax.connect_to_cloud_databases("DFW")
        cnw = pyrax.connect_to_cloud_networks("DFW")
        cbs = pyrax.connect_to_cloud_blockstorage("DFW")
        dns = pyrax.connect_to_cloud_dns("DFW")
        lbs = pyrax.connect_to_cloud_loadbalancers("DFW")
    elif args.region == 'LON':
        cs = pyrax.connect_to_cloudservers("LON")
        cdb = pyrax.connect_to_cloud_databases("LON")
        cnw = pyrax.connect_to_cloud_networks("LON")
        cbs = pyrax.connect_to_cloud_blockstorage("LON")
        dns = pyrax.connect_to_cloud_dns("LON")
import pyrax
import time
import string
'''
Build Servers with attached CBS and CloudNetworks
'''

pyrax.set_setting("identity_type", "rackspace")
cred_file = os.path.expanduser(
    '~/.ipython/profile_cbdteam/conf/.rackspace_cloud_credentials')
pyrax.set_credential_file(cred_file)

my_region = 'IAD'

cs = pyrax.connect_to_cloudservers(region=my_region)
cbs = pyrax.connect_to_cloud_blockstorage(region=my_region)
cnw = pyrax.connect_to_cloud_networks(region=my_region)

#| onmetal-compute1 | OnMetal Compute v1      | 32768     | 32   | 0         |         | 20    | 10000.0     | N/A       |
#| onmetal-io1      | OnMetal I/O v1          | 131072    | 32   | 3200      |         | 40    | 10000.0     | N/A       |
#| onmetal-memory1  | OnMetal Memory v1       | 524288    | 32   | 0         |         | 24    | 10000.0     | N/A       |
#| performance1-1   | 1 GB Performance        | 1024      | 20   | 0         |         | 1     | 200.0       | N/A       |
#| performance1-2   | 2 GB Performance        | 2048      | 40   | 20        |         | 2     | 400.0       | N/A       |
#| performance1-4   | 4 GB Performance        | 4096      | 40   | 40        |         | 4     | 800.0       | N/A       |
#| performance1-8   | 8 GB Performance        | 8192      | 40   | 80        |         | 8     | 1600.0      | N/A       |
#| performance2-120 | 120 GB Performance      | 122880    | 40   | 1200      |         | 32    | 10000.0     | N/A       |
#| performance2-15  | 15 GB Performance       | 15360     | 40   | 150       |         | 4     | 1250.0      | N/A       |
#| performance2-30  | 30 GB Performance       | 30720     | 40   | 300       |         | 8     | 2500.0      | N/A       |
#| performance2-60  | 60 GB Performance       | 61440     | 40   | 600       |         | 16    | 5000.0      | N/A       |
#| performance2-90  | 90 GB Performance
#OnMental i- Cent 6.5: a4a07273-6e5c-4092-a4bd-b3a2fc669a5f
    sys.exit(1)

print "\n%(header)sWelcome to the %(progname)s! %(endc)s" % {
    "header": bcolors.HEADER,
    "progname": progName,
    "endc": bcolors.ENDC,
}

try:
    myLogin = raxLogin(raxArgs.configFile)
    myLogin.authenticate()
except:
    print bcolors.FAIL + "Couldn't login" + bcolors.ENDC
    sys.exit(2)

raxCbs = pyrax.connect_to_cloud_blockstorage(region=dc)
raxCldSvr = pyrax.connect_to_cloudservers(region=dc)
raxDns = pyrax.cloud_dns
raxCldLB = pyrax.connect_to_cloud_loadbalancers(region=dc)
raxNet = pyrax.connect_to_cloud_networks(region=dc)

print "\n%(header)sCreating Private Cloud Network... %(endc)s" % {"header": bcolors.HEADER, "endc": bcolors.ENDC}
try:
    privNet = raxNet.create(privNetName, cidr=privNetCidr)
    print ("%(hdr)sSuccessfully created %(pnetName)s: %(cidr)s" "%(endc)s") % {
        "hdr": bcolors.HEADER,
        "pnetName": privNet.label,
        "cidr": privNet.cidr,
        "endc": bcolors.ENDC,
    }
except Exception as e:
import pyrax
import time
import string

'''
Build Servers with attached CBS and CloudNetworks
'''

pyrax.set_setting("identity_type", "rackspace")
cred_file = os.path.expanduser('~/.ipython/profile_cbdteam/conf/.rackspace_cloud_credentials')
pyrax.set_credential_file(cred_file)

my_region = 'IAD'

cs = pyrax.connect_to_cloudservers(region=my_region)
cbs = pyrax.connect_to_cloud_blockstorage(region=my_region)
cnw = pyrax.connect_to_cloud_networks(region=my_region)

#| onmetal-compute1 | OnMetal Compute v1      | 32768     | 32   | 0         |         | 20    | 10000.0     | N/A       |
#| onmetal-io1      | OnMetal I/O v1          | 131072    | 32   | 3200      |         | 40    | 10000.0     | N/A       |
#| onmetal-memory1  | OnMetal Memory v1       | 524288    | 32   | 0         |         | 24    | 10000.0     | N/A       |
#| performance1-1   | 1 GB Performance        | 1024      | 20   | 0         |         | 1     | 200.0       | N/A       |
#| performance1-2   | 2 GB Performance        | 2048      | 40   | 20        |         | 2     | 400.0       | N/A       |
#| performance1-4   | 4 GB Performance        | 4096      | 40   | 40        |         | 4     | 800.0       | N/A       |
#| performance1-8   | 8 GB Performance        | 8192      | 40   | 80        |         | 8     | 1600.0      | N/A       |
#| performance2-120 | 120 GB Performance      | 122880    | 40   | 1200      |         | 32    | 10000.0     | N/A       |
#| performance2-15  | 15 GB Performance       | 15360     | 40   | 150       |         | 4     | 1250.0      | N/A       |
#| performance2-30  | 30 GB Performance       | 30720     | 40   | 300       |         | 8     | 2500.0      | N/A       |
#| performance2-60  | 60 GB Performance       | 61440     | 40   | 600       |         | 16    | 5000.0      | N/A       |
#| performance2-90  | 90 GB Performance
#OnMental i- Cent 6.5: a4a07273-6e5c-4092-a4bd-b3a2fc669a5f
import pyrax
from os.path import expanduser
from time import sleep


if __name__ == "__main__":
    pyrax.set_credential_file(expanduser("~/.rackspace_cloud_credentials"))
    cs_ord = pyrax.connect_to_cloudservers("ORD")
    cs_dfw = pyrax.connect_to_cloudservers("DFW")
    cf_ord = pyrax.connect_to_cloudfiles("ORD")
    cf_dfw = pyrax.connect_to_cloudfiles("DFW")
    cdb_ord = pyrax.connect_to_cloud_databases("ORD")
    cdb_dfw = pyrax.connect_to_cloud_databases("DFW")
    cnw_ord = pyrax.connect_to_cloud_networks("ORD")
    cnw_dfw = pyrax.connect_to_cloud_networks("DFW")
    cbs_ord = pyrax.connect_to_cloud_blockstorage("ORD")
    cbs_dfw = pyrax.connect_to_cloud_blockstorage("DFW")
    dns_ord = pyrax.connect_to_cloud_dns("ORD")
    dns_dfw = pyrax.connect_to_cloud_dns("DFW")
    lbs_ord = pyrax.connect_to_cloud_loadbalancers("ORD")
    lbs_dfw = pyrax.connect_to_cloud_loadbalancers("DFW")

    print("deleting servers")
    for server in cs_ord.servers.list():
        server.delete()
    for server in cs_dfw.servers.list():
        server.delete()

    print("deleting server images")
    for image in cs_ord.images.list():
        if hasattr(image, "server"):