Exemple #1
0
    def __init__(self, task_kwargs=None, json_config_file=None):
        json_config_file = json_config_file or './deploy_settings.json'
        self.cloudservers = None
        self.settings = AttributeDict({})
        self.fabric_env_servers = []
        self.created_servers = []

        task_kwargs = task_kwargs or {}

        settings = self.read_settings_file(json_config_file)

        for key in self.SETTINGS_KEYS:
            try:
                self.settings[key] = task_kwargs[key]
            except KeyError:
                try:
                    self.settings[key] = environ[key]
                except KeyError:
                    try:
                        self.settings[key] = settings[key]
                    except KeyError:
                        pass

        self.settings.server_count = int(self.settings.server_count)
        self.settings.setdefault('ssh_user', 'root')
        self.settings.setdefault('git_branch', 'master')
        self.ensure_settings('rackspace_username', 'rackspace_apikey')

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_credentials(
            self.settings.rackspace_username,
            self.settings.rackspace_apikey)
        self.cloudservers = pyrax.connect_to_cloudservers()
        self.loadbalancers = pyrax.connect_to_cloud_loadbalancers()
Exemple #2
0
def delete_rax_clb(args):
    """Function for deleting Cloud Load Balancers"""
    print("--- Cleaning Cloud Load Balancers matching '%s'" % args.match_re)
    for region in pyrax.identity.services.load_balancer.regions:
        clb = pyrax.connect_to_cloud_loadbalancers(region=region)
        for lb in rax_list_iterator(clb):
            if re.search(args.match_re, lb.name):
                prompt_and_delete(lb, 'Delete matching %s? [y/n]: ' % lb,
                                  args.assumeyes)
Exemple #3
0
def delete_rax_clb(args):
    """Function for deleting Cloud Load Balancers"""
    print ("--- Cleaning Cloud Load Balancers matching '%s'" % args.match_re)
    for region in pyrax.identity.services.load_balancer.regions:
        clb = pyrax.connect_to_cloud_loadbalancers(region=region)
        for lb in rax_list_iterator(clb):
            if re.search(args.match_re, lb.name):
                prompt_and_delete(lb,
                                  'Delete matching %s? [y/n]: ' % lb,
                                  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 _get_client(self):
        username = self.config['username']
        api_key = self.config['api_key']

        # Needs to be extracted to per-action
        region = self.config['region'].upper()

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_default_region(region)
        pyrax.set_credentials(username, api_key)

        debug = self.config.get('debug', False)
        if debug:
            pyrax.set_http_debug(True)

        pyrax.cloudservers = pyrax.connect_to_cloudservers(region=region)
        pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers(region=region)
        pyrax.cloud_dns = pyrax.connect_to_cloud_dns(region=region)

        return pyrax
Exemple #7
0
    def _get_client(self):
        username = self.config['username']
        api_key = self.config['api_key']

        # Needs to be extracted to per-action
        region = self.config['region'].upper()

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_default_region(region)
        pyrax.set_credentials(username, api_key)

        debug = self.config.get('debug', False)
        if debug:
            pyrax.set_http_debug(True)

        pyrax.cloudservers = pyrax.connect_to_cloudservers(region=region)
        pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers(region=region)
        pyrax.cloud_dns = pyrax.connect_to_cloud_dns(region=region)

        return pyrax
Exemple #8
0
def main():
    custom_excepthook.original_excepthook = sys.excepthook
    sys.excepthook = custom_excepthook

    arguments = get_arguments()

    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_credentials(arguments.rackuser, arguments.rackpass)
    pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers()

    load_balancer = None
    for balancer in pyrax.cloud_loadbalancers.list():
        if arguments.load_balancer in (str(balancer.id), balancer.name):
            load_balancer = balancer
            break

    if not load_balancer:
        raise ValueError('Load balancer with ID/Name "{id}" not found'.format(
            id=arguments.load_balancer,
        ))

    for server in [node.get_device() for node in load_balancer.nodes]:
        run_update_script(server, arguments)
Exemple #9
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)
Exemple #10
0
try:
    errorfile = open(os.path.expanduser(args.errorfile))
    errorpage = errorfile.read()
except IOError:
    print "Could not open HTML error page %s.  Exiting" % (args.errorfile)
    exit(1)

# make sure FQDN provided is a good hostname
hostwords = args.fqdn.split('.')
if len(hostwords) < 3:
    print "%s is not a valid hostname.  Exiting" % (args.fqdn)
    exit(1)
domain = ".".join(hostwords[-2:])

cs = pyrax.connect_to_cloudservers(region=args.dc)
clb = pyrax.connect_to_cloud_loadbalancers(region=args.dc)
cf = pyrax.connect_to_cloudfiles(region=args.dc)
cdns = pyrax.connect_to_cloud_dns(region=args.dc)

# check if container name exists
containers = cf.get_all_containers()
container = None
for c in containers:
    if c.name == args.container:
        container = c
if container is not None:
    print "Container %s already exists.  Please specify non-existent container" \
        % (args.container)
    exit(1)
container = cf.create_container(args.container)
Exemple #11
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: {} -r DFW -b web -n 3 -i 'Ubuntu 11.10' -f 512"
        " -l LB1 - create web1, web2, and web3 and place them behind a new "
        "CLB called LB1.".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("-l", "--lb_name", 
        help = "Name of load balancer to create")
    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)
    clb = pyrax.connect_to_cloud_loadbalancers(region = args.region)

    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 == None or len(image) < 1:
            image = choose_image(cs, "Image matching '{}' not found.  Select image: ".format(args.image_name))
        else:
            image = image[0]

    servers = []
    for i in range(1, args.number + 1):
        servers.append({'name': "{}{}".format(args.base, i),
                        'image_name': image.name,
                        'image_id': image.id,
                        'flavor': flavor})
    created_servers = create_servers(cs, servers)

    nodes = [clb.Node(address = server.networks[u'private'][0], port = args.port, 
        condition = 'ENABLED') for server, admin_pass in created_servers]
    vip = clb.VirtualIP(type = args.vip_type)

    lb = create_load_balancer(clb, args.lb_name, args.port, args.protocol, nodes, [vip])

    if lb is None or lb.status == 'ERROR':
        print "Load balancer creation failed."
        sys.exit(1)
    print "\nLoad balancer created:"    
    print_load_balancer(lb)
Exemple #12
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: {} -r DFW -b web -n 3 -k ~/ssh.key -i 'Ubuntu 11.10'"
        " -f 512 -l lb1 -d site1.site.com -t 600 -e 'Error!'"
        " -s tuesday - create web1, web2, and web3 and place them behind a new "
        "CLB called lb1.".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("-k", "--keyfile", required = True, 
        help = "SSH Key to be installed at /root/.ssh/authorized_keys.")
    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("-l", "--lb_name", required = True, 
        help = "Name of load balancer to create")
    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("-g", "--error_file", 
        help = "File to upload as custom error page.  Overrides --error_content")
    parser.add_argument("-e", "--error_content", default = "<html><head><title>"
        "Custom Error</title><body>Error loading page.</body></html>", 
        help="Custom error page content.  Basic default is set if not supplied.")
    parser.add_argument("-s", "--backup_container", default = "", 
        help = "Container to place error page backup in.  Randomly generated "
        "if not supplied.")
    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)
    clb = pyrax.connect_to_cloud_loadbalancers(region = args.region)
    cf = pyrax.connect_to_cloudfiles(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 == None or len(image) < 1:
            image = choose_image(cs, "Image matching '{}' not found.  Select image: ".format(args.image_name))
        else:
            image = image[0]

    servers = []
    for i in range(1, args.number + 1):
        servers.append({'name': "{}{}".format(args.base, i),
                        'image_name': image.name,
                        'image_id': image.id,
                        'flavor': flavor})

    try:
        with open(os.path.abspath(args.keyfile)) as f:
            key = f.read()
    except Exception, e:
        print "Error opening SSH key file:", e
        sys.exit(1)
Exemple #13
0
                    dest="private",
                    default=False,
                    action="store_true",
                    help="create private VIP on servicenet")
parser.add_argument("-d",
                    dest="dc",
                    default="DFW",
                    help="use data center DC (DFW or ORD)",
                    metavar="DC")

args = parser.parse_args()

pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))

cs = pyrax.connect_to_cloudservers(region=args.dc)
clb = pyrax.connect_to_cloud_loadbalancers(region=args.dc)

# check if image is valid
images = cs.images.list()
image = None
for i in images:
    if i.id == args.image:
        image = i
if image is None:
    print "Image %s not found.  Please specify an existing image ID:" % (
        args.image)
    for i in images:
        print "ID: %s  Name: %s" % (i.id, i.name)
    exit(1)

# insure flavor is valid
Exemple #14
0
 def test_connect_to_cloud_loadbalancers(self):
     pyrax.cloud_loadbalancers = None
     octclb = self.orig_connect_to_cloud_loadbalancers
     pyrax.connect_to_cloud_loadbalancers = octclb
     pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers()
     self.assertIsNotNone(pyrax.cloud_loadbalancers)
                    '-k',
                    dest="api_key",
                    required=True,
                    help='Rackspace API Key.')
parser.add_argument('--remove',
                    '-d',
                    dest="remove",
                    action='store_true',
                    help='remove the specified node from the loadbalancer.')
args = parser.parse_args()

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(args.region)
pyrax.set_credentials(args.username, args.api_key)

clb = pyrax.connect_to_cloud_loadbalancers(args.region.upper())

lb = clb.get(args.loadbalancer)
if args.remove:
    try:
        node = [node for node in lb.nodes if node.address == args.ip]
        node.delete()
    except Exception as e:
        msg = "Failed to remove instance {0} from LB {1}: {2}"
        print(msg.format(args.instance, args.loadbalancer, e))
        sys.exit(1)
else:
    try:
        lb.add_nodes(
            [clb.Node(address=args.ip, port=443, condition="ENABLED")])
    except Exception as e:
Exemple #16
0
    my_servers = []

    num_servers = int(sys.argv[1])
    print("Building {} servers".format(num_servers))

    # Build each of the servers
    for server_id in range(num_servers):
        server_name = server_namer.format(server_id=server_id)
        print(u"Bringing {server_name} online".format(server_name=server_name))
        server = cs.servers.create(name=server_name, image=image.id,
                flavor=flav_512.id)
        my_servers.append(server)


    nodes = []
    clb = pyrax.connect_to_cloud_loadbalancers()

    # It takes a little while to come online, so we need to wait until they're
    # available
    for server in my_servers:
        # Done if ACTIVE or ERRORed
        server = pyrax.utils.wait_until(server, "status", ["ACTIVE", "ERROR"],
                attempts=0)

        server_ip = server.networks["private"][0]
        print("IP {} ready".format(server_ip))
        node = clb.Node(address=server_ip, port=80, condition="ENABLED")
        nodes.append(node)

    vip = clb.VirtualIP(type="PUBLIC")
    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)

raxCf = pyrax.connect_to_cloudfiles(region=dc)
raxCldSvr = pyrax.connect_to_cloudservers(region=dc)
raxDns = pyrax.cloud_dns
raxCldLB = pyrax.connect_to_cloud_loadbalancers(region=dc)

print "\n%(header)sCreating Cloud Servers... %(endc)s" % {
    "header": bcolors.HEADER, "endc": bcolors.ENDC}
try:
    lbNodes = raxCreateServer(raxCldSvr, numServers, svrBaseName,
                              raxArgs.imgID, raxArgs.flvrID)
    print("%(hdr)sSuccessfully created %(numServers)s servers"
          "%(endc)s") % {"hdr": bcolors.HEADER, "numServers": numServers,
                         "endc": bcolors.ENDC}
except Exception as e:
    print("%(fail)sCan't create server: "
          "%(e)s%(endc)s") % {"fail": bcolors.FAIL,
                              "e": e, "endc": bcolors.ENDC}
    sys.exit(2)
parser.add_argument('--username', '-u', dest="username", required=True,
                    help='Rackspace Username.')
parser.add_argument('--api-key', '-k', dest="api_key", required=True,
                    help='Rackspace API Key.')
parser.add_argument('--remove', '-d', dest="remove", action='store_true',
                    help='remove the specified node from the loadbalancer.')
args = parser.parse_args()

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(args.region)
pyrax.set_credentials(
    args.username,
    args.api_key
)

clb = pyrax.connect_to_cloud_loadbalancers(args.region.upper())

lb = clb.get(args.loadbalancer)
if args.remove:
    try:
        node = [node for node in lb.nodes
                if node.address == args.ip]
        node.delete()
    except Exception as e:
        msg = "Failed to remove instance {0} from LB {1}: {2}"
        print(msg.format(args.instance, args.loadbalancer, e))
        sys.exit(1)
else:
    try:
        lb.add_nodes(
            [
Exemple #19
0
 def test_connect_to_cloud_loadbalancers(self):
     pyrax.cloud_loadbalancers = None
     octclb = self.orig_connect_to_cloud_loadbalancers
     pyrax.connect_to_cloud_loadbalancers = octclb
     pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers()
     self.assertIsNotNone(pyrax.cloud_loadbalancers)
    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")
        lbs = pyrax.connect_to_cloud_loadbalancers("LON")
        '--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")
        lbs = pyrax.connect_to_cloud_loadbalancers("LON")
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"):
            cs_ord.images.delete(image.id)
    for image in cs_dfw.images.list():
        if hasattr(image, "server"):
            cs_dfw.images.delete(image.id)
Exemple #23
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)
Exemple #24
0
pyrax.set_setting("identity_type", "rackspace")

if (len(sys.argv) == 3):
    pyrax.set_credentials(sys.argv[1], sys.argv[2])
else:
    print "Usage: cloudlb.py <username> <api key>"
    sys.exit(0)

print "=" * 24
print "  Cloud Load Balancers  "
print "=" * 24

regions = ['dfw', 'iad', 'ord', 'syd']

x = PrettyTable([
    "Region", "Name", "ID", "Status", "Public IP", "ServiceNet IP", "Cluster"
])
x.padding_width = 1
for n in regions:
    clb = pyrax.connect_to_cloud_loadbalancers(n.upper())
    lb = clb.list()
    for i in lb:
        x.add_row([
            n.upper(), i.name, i.id, i.status,
            clb.get(i.id).sourceAddresses["ipv4Public"],
            clb.get(i.id).sourceAddresses["ipv4Servicenet"],
            clb.get(i.id).cluster
        ])
print x
Exemple #25
0
import os
import pyrax

# Creds
pyrax.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)


# Get region and name
isRegion = raw_input("What region would you like to create this load balancer in? (DFW/ORD): ")
print

# Set the region for your LB object
if isRegion == "DFW":
        lb = pyrax.connect_to_cloud_loadbalancers(region="DFW")
if isRegion == "ORD":
        lb = pyrax.connecto_to_cloud_loadbalancers(region="ORD")
lbName = raw_input("What would you like to name the load balancer?: ")
print

#Set the region for your CS object
if isRegion == "DFW":
	cs = pyrax.connect_to_cloudservers(region="DFW")
if isRegion == "ORD":
	cs = pyrax.connecto_to_cloudservers(region="ORD")
for srv in cs.servers.list():
	print "Name:",srv.name
	print "   ID:",srv.id
print
Exemple #26
0
import pyrax
import sys
from prettytable import PrettyTable

pyrax.set_setting("identity_type", "rackspace")

if (len(sys.argv) == 3):
    pyrax.set_credentials(sys.argv[1], sys.argv[2])
else:
    print "Usage: cloudlb.py <username> <api key>"
    sys.exit(0)

print "=" * 24
print "  Cloud Load Balancers  "
print "=" * 24

regions = ['dfw', 'iad', 'ord', 'syd']

x = PrettyTable(["Region", "Name", "ID", "Status",
                "Public IP", "ServiceNet IP", "Cluster"])
x.padding_width = 1
for n in regions:
    clb = pyrax.connect_to_cloud_loadbalancers(n.upper())
    lb = clb.list()
    for i in lb:
        x.add_row([n.upper(), i.name, i.id, i.status,
                  clb.get(i.id).sourceAddresses["ipv4Public"],
                  clb.get(i.id).sourceAddresses["ipv4Servicenet"],
                  clb.get(i.id).cluster])
print x
Exemple #27
0
 def __init__(self, region, **kwargs):
     super(FLUFFY_LB, self).__init__(**kwargs)
     self.clb = pyrax.connect_to_cloud_loadbalancers(region=region)