当前位置: 首页>>代码示例>>Python>>正文


Python pyrax.set_credential_file函数代码示例

本文整理汇总了Python中pyrax.set_credential_file函数的典型用法代码示例。如果您正苦于以下问题:Python set_credential_file函数的具体用法?Python set_credential_file怎么用?Python set_credential_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了set_credential_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--region', default="ORD", choices=['ORD','DFW','LON'], help="Cloud region (default: ORD)")
    parser.add_argument('--flavor', type=int, default=1, choices=range(1,7), help="Flavor ID (default: 1)")
    parser.add_argument('--volume', default=1, help="Size of disk in GB (default:1, Max:150)")
    parser.add_argument('user', help="Database User")
    parser.add_argument('password', help="Database Password")
    parser.add_argument('database', metavar='database-name', help="Database Name")
    parser.add_argument('instance', metavar='instance-name', help="Instance name")
    args = parser.parse_args()

    pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"),region=args.region)
    cdb = pyrax.cloud_databases

    db_dict = [{"name": args.database}]
    user_dict = [
                    {
                        "name": args.user,
                        "password": args.password,
                        "databases": db_dict
                    }
                ]
    print "Building database instance. This may take a few minutes..."
    instance = cdb.create(args.instance, flavor=args.flavor, volume=args.volume, users=user_dict, databases=db_dict)
    instance = pyrax.utils.wait_until(instance,'status',['ACTIVE','ERROR'], interval=15)
    if instance.status == 'ACTIVE':
        print "Instance built successfully."
    else:
        raise SystemExit("ERROR: Instance build was unsuccessful")

    return
开发者ID:nonamed108,项目名称:apichallenges,代码行数:32,代码来源:challenge5.py

示例2: main

def main():
    pyrax.set_credential_file(os.path.expanduser('~/.rackspace_cloud_credentials'))
    cs = pyrax.cloudservers
    # Ubuntu 12.04 Image
    image_id = '5cebb13a-f783-4f8c-8058-c4182c724ccd'
    # 512M Server
    flavor_id = 2
    # Server name prefix
    prefix = 'web'
    password_dict = {}

    def print_server_details(server):
        print "\nid: %s" % server.id
        print "name: %s" % server.name
        print "adminPass: %s" % password_dict.get(server.id)
        print "networks: %s" % server.networks
        return

    def build_check_callback(server):
        if not server:
            print 'ERROR: One of your servers does not appear to be building properly'
        elif server.status == "ACTIVE":
            print_server_details(server)
        else:
            print "ERROR: Server %s (%s) is in ERROR" % (server.id, server.name)
            print_server_details(server)
        return

    for i in xrange(0,3):
        server = cs.servers.create('%s%s' % (prefix,str(i+ 1)), image_id, flavor_id)
        password_dict[server.id] = server.adminPass
        pyrax.utils.wait_until(server,'status',['ACTIVE','ERROR'],build_check_callback, interval=15, attempts=30)
    print "Your Ubuntu 12.04 512M 3-pack is now building! Server details provided upon build completion. This may take a minute or so..."

    return
开发者ID:nonamed108,项目名称:apichallenges,代码行数:35,代码来源:challenge1.py

示例3: setup

def setup():
    username = os.environ.get('OS_USERNAME')
    api_key = os.environ.get('OS_PASSWORD')
    credentials = os.environ.get('RAX_CREDENTIALS') or os.environ.get('RAX_CREDS_FILE')
    region = os.environ.get('OS_REGION_NAME')

    if credentials is None:
        credentails = os.path.expanduser('~/.rackspace_cloud_credentials')

    try:
        pyrax.set_setting('identity_type', 'rackspace')

        if api_key and username:
            pyrax.set_credentials(username, api_key=api_key)
        elif credentials:
            credentials = os.path.expanduser(credentials)
            pyrax.set_credential_file(credentials)
        else:
            sys.stderr.write('No value in environment variable %s and/or no '
                             'credentials file at %s\n'
                             % (e.message, default_creds_file))
            sys.exit(1)
    except Exception, e:
        sys.stderr.write("%s: %s\n" % (e, e.message))
        sys.exit(1)
开发者ID:chalupaul,项目名称:ansible-zwift,代码行数:25,代码来源:rax.py

示例4: master_up

def master_up(key_name, credential_file="~/.rackspace_cloud_credentials"):
    '''
    Create a salt-master on Rackspace

    Alternatively create the master using nova
    '''

    # Authenticate with Rackspace, use credential file
    pyrax.set_setting("identity_type", "rackspace")
    pyrax.set_credential_file(os.path.expanduser(credential_file))

    # Shorthand
    cs = pyrax.cloudservers

    # Building Ubuntu 12.04 boxes with 512 MB RAM
    iter_flavors = ifilter(lambda flavor: flavor.ram == 512, cs.flavors.list())
    flavor_512 = iter_flavors.next()
    iter_os = ifilter(lambda img: "Ubuntu 12.04" in img.name, cs.images.list())
    ubu_image = iter_os.next()

    master = cs.servers.create("master.ipython.org", ubu_image.id, flavor_512,
                               key_name=key_name)

    master = pyrax.utils.wait_for_build(master, verbose=True)

    env.hosts = [master.accessIPv4]

    print("Master IP: {}".format(master.accessIPv4))
    return master.accessIPv4
开发者ID:minrk,项目名称:bootstrap-salt-nbviewer,代码行数:29,代码来源:fabfile.py

示例5: load

def load(context, path, callback):
    key = (
            context.config.RACKSPACE_PYRAX_REGION, 
            context.config.get('RACKSPACE_PYRAX_IDENTITY_TYPE','rackspace'),
            context.config.RACKSPACE_PYRAX_CFG,
            context.config.RACKSPACE_PYRAX_PUBLIC,
            context.config.RACKSPACE_LOADER_CONTAINER
        )

    if key not in CONNECTIONS:
        if(context.config.RACKSPACE_PYRAX_REGION):
            pyrax.set_default_region(context.config.RACKSPACE_PYRAX_REGION)
        pyrax.set_setting('identity_type', context.config.get('RACKSPACE_PYRAX_IDENTITY_TYPE','rackspace'))
        pyrax.set_credential_file(expanduser(context.config.RACKSPACE_PYRAX_CFG))
        cf = pyrax.connect_to_cloudfiles(public=context.config.RACKSPACE_PYRAX_PUBLIC)
        CONNECTIONS[key] = cf.get_container(context.config.RACKSPACE_LOADER_CONTAINER)

    cont = CONNECTIONS[key]
    file_abspath = normalize_path(context, path)
    logger.debug("[LOADER] getting from %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath))
    try:
        obj = cont.get_object(file_abspath)
        if obj:
            logger.debug("[LOADER] Found object at %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath))
        else:
            logger.warning("[LOADER] Unable to find object %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath ))
    except:
        callback(None)
    else:
        callback(obj.get())
开发者ID:Superbalist,项目名称:thumbor_rackspace,代码行数:30,代码来源:cloudfiles_loader.py

示例6: main

def main():

	credz = os.path.expanduser("~/.rackspace_cloud_credentials")

	try:
		pyrax.set_credential_file(credz)
	except exceptions.AuthenticationFailed:
		print "\n\nAuth failed, possibly wrong info in .rackspace_cloud_credentials"
	if pyrax.identity.authenticated:
		print '-'*15, '\n', "Auth successful as %s" % pyrax.identity.username, '\n', '-'*15
	else:
		print "Authentication failed."
		sys.exit(1)

        cf = pyrax.cloudfiles
        dns = pyrax.cloud_dns
        indexfile = "index.html"
        index_data = "<html>\n<body>\n<h1>Welcome to the internet</h1>\n"

        cont = cf.create_container("index")
        cont.make_public(ttl=900)
        uppit = cont.store_object(indexfile, index_data)
        print "Uploaded %s" % uppit, '\n', '-'*15
        cont.set_web_index_page(indexfile)
        dom_n = "superc00lwebsite.com"
        dom_e = "[email protected]"
        domain = dns.create(name=dom_n, emailAddress=dom_e)
        name = "cdn." + dom_n
        recadd = {"type": "CNAME", "name": name, "data": cont.cdn_uri, "ttl":900}
        fin = domain.add_records(recadd)
        print fin
开发者ID:mattmartinez,项目名称:RS_API_Challenge,代码行数:31,代码来源:challenge8.py

示例7: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument ('-n', '--name', help='Name of database to be created', required=True)
    parser.add_argument ('-u', '--username', help='Username of database to be created', required=True)
    parser.add_argument ('-p', '--password', help='Password of database to be created', required=True)


    args = parser.parse_args()

    pyrax.set_credential_file(".PathToCreds")
    cdb = pyrax.cloud_databases
 
    # Creates the instance
    instance_name = "Default Instance"
    inst = cdb.create(instance_name, flavor="1GB Instance", volume=2)
    print "Instance: %s" % (inst)

    completed_instance = []
    while len(completed_instance) < 1:    
        for instance in cdb.list():
            if str(instance_name) in instance.name and instance.status == 'ACTIVE':
                completed_instance.append(instance_name)
        print "Waiting for instance to be ready. Trying again in 30 seconds."
        time.sleep(30)
    
    print "Instance is ready. Creating database."
    
    # Creates the database   
    db = inst.create_database(args.name)
    print "DB: %s" % (db)    

    # Creates the user    
    user = inst.create_user(name=args.username, password=args.password, database_names=[db])
    print "User: %s" % (user)
开发者ID:drizzlelabs,项目名称:cloud_calls,代码行数:34,代码来源:challenge5.py

示例8: check_usage

def check_usage(instance_id, threshold, region):
    pyrax.set_credential_file(
        os.path.expanduser("~/.rackspace_cloud_credentials"))
    cdb = pyrax.connect_to_cloud_databases(region=region)

    matched_instance = None
    for instance in cdb.list():
        if instance.id == instance_id:
            matched_instance = instance
    if not matched_instance:
        print 'status error Unable to find instance', instance_id
        sys.exit(1)

    # Force usage lookup
    matched_instance.get()
    database_size = matched_instance.volume['size']
    database_usage = matched_instance.volume['used']
    percentage_used = database_usage / database_size

    if percentage_used >= threshold:
        print 'status error usage over threshold'
    else:
        print 'status ok usage within threshold'

    print "metric database_GB_container_size float", database_size
    print "metric database_GB_used float", database_usage
    print "metric percentage_used float", percentage_used
开发者ID:calebgroom,项目名称:rackspace-monitoring-agent-plugins-contrib,代码行数:27,代码来源:clouddatabases_volume.py

示例9: main

def main():

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

	available_regions = pyrax.regions

	print "Regions Available:", " ".join(list(available_regions))
	region = ""
	while region not in available_regions:
		region = raw_input("Select Region: ")

	cs = pyrax.connect_to_cloudservers(region)
	available_images = cs.images.list()
	available_flavors = cs.flavors.list()

	image = make_choice(images, "Select an image: ")
	flavor = make_choice(flavors, "Select a flavor: ")

	base_name = raw_input('Base server name': )
	server_count = int(raw_input('Number of servers to build: '))

	print "Building {} servers with base name '{}', flavor '{}', and image " 
		"'{}'.".format(server_count, base_name, flavor.name, image.name)
开发者ID:ddremund,项目名称:rs-devops,代码行数:25,代码来源:server_build.py

示例10: main

def main():

    pyrax.set_credential_file("./CredsFile")

    cs = pyrax.cloudservers
    servers = cs.servers.list()
    image_list = cs.images.list()

    srv_dict = {}


    print "Select a server from which an image will be created."
    for pos, srv in enumerate(servers):
        print "%s: %s" % (pos, srv.name)
        srv_dict[str(pos)] = srv.id
    selection = None
    while selection not in srv_dict:
        if selection is not None:
            print " -- Invalid choice"
        selection = raw_input("Enter the number for your choice: ")

    server_id = srv_dict[selection]
    print
    img_name = raw_input("Enter a name for the image: ")

    images = {}
    images[img_name] = cs.servers.create_image(server_id, img_name)
    
    completed_images = []
    while len(completed_images) < 1:    
        for img in cs.images.list():
            if str(img_name) in img.name and img.status == 'ACTIVE':
                completed_images.append(images[img_name])
        print "Waiting for image to be saved. Trying again in 30 seconds."
        time.sleep(30)

    print "\nImage is ready. Creating server."

    servers = {}
    servers[img_name] = cs.servers.create(img_name, images[img_name], 2)
    print "Building server: %s" % img_name
    
    print 
    
    completed_details = []
    while len(completed_details) < 1:
        for img_name in servers:
            servers[img_name].get()
            if len(servers[img_name].networks) > 0:
                completed_details.append(servers[img_name])        
        print "Waiting for details to be ready. Trying again in 30 seconds."
        time.sleep(30)
        
    for img_name in servers:
        servers[img_name].get()
        print "Name: %s" % servers[img_name].name
        print "ID: %s" % servers[img_name].id
        print "Status: %s" % servers[img_name].status
        print "Admin Password: %s" % servers[img_name].adminPass
        print "Networks: %s \n" % servers[img_name].networks
开发者ID:drizzlelabs,项目名称:cloud_calls,代码行数:60,代码来源:challenge2.py

示例11: main

def main():

    # Parse the command line arguments
    parser = argparse.ArgumentParser(description="Add a dns A record",
                                     prog='cdns_add_dns_record.py')
    parser.add_argument('--fqdn', help='fully qualified domain name',
                        required=True)
    parser.add_argument('--ip', help='ip address', required=True)
    args = parser.parse_args()

    # Authenticate using a credentials file: "~/.rackspace_cloud_credentials"
    cred_file = "%s/.rackspace_cloud_credentials" % (os.environ['HOME'])
    print "Setting authentication file to %s" % (cred_file)
    pyrax.set_credential_file(cred_file)

    # Instantiate a clouddns object
    print "Instantiating cloud_dns object"
    cdnsobj = pyrax.cloud_dns

    # Add the domain record
    domains = cdnsobj.list()
    for domain in domains:
        if args.fqdn.endswith(domain.name):
            print "Found a matching domain: " + domain.name + \
                  " for fqdn: " + args.fqdn
            recs = [{'type': 'A', 'name': args.fqdn, 'data': args.ip,
                     'ttl': 6000}]
            print "Adding record: \n\t" + args.fqdn + "   IN  A  " + args.ip
            cdnsobj.add_records(domain, recs)
开发者ID:javiergayala,项目名称:cloud_code_samples,代码行数:29,代码来源:cdns_add_dns_record.py

示例12: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument ('-c', '--container', help='Name of container to be created.', required=True)
    parser.add_argument ('-f', '--fqdn', help='FQDN of record to add', required=True)
    parser.add_argument ('-i', '--ip', help='IP Address of FQDN record')
    parser.add_argument ('-e', '--email', help='IP Address of FQDN record', required=True)
    
    args = parser.parse_args()

    pyrax.set_credential_file(".PathtoCreds")
    cf = pyrax.cloudfiles
    dns = pyrax.cloud_dns

    cont = cf.create_container(args.container)
    print "Creating container named: %s" % (cont.name)
    cf.make_container_public(args.container, ttl=900)
    print "CDN Enabled."
    
    content = "Hello World"
    obj = cf.store_object(cont.name, "index.html", content, content_type="text/html")
    print "Stored Object: %s" % (obj)
    print "CDN URI: %s" % (cont.cdn_uri)
    
    dom = dns.create(name=args.fqdn, emailAddress=args.email)
            
    recs = [{
            "type": "CNAME",
            "name": "test." + str(args.fqdn),
            "data": cont.cdn_uri,
            "ttl": 6000,
            }]
                    
    print dom.add_records(recs)
开发者ID:drizzlelabs,项目名称:cloud_calls,代码行数:33,代码来源:challenge8.py

示例13: main

def main():
    creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
    pyrax.set_credential_file(creds_file)
    servers = create_chal10_servers()
    lb = create_chal10_lb(servers)
    lb_vip = lb.virtual_ips[0].address
    dns = create_dns(lb_vip)
开发者ID:censhin,项目名称:challenges,代码行数:7,代码来源:challenge10.py

示例14: main

def main():

	pyrax.set_setting("identity_type", "rackspace")
	creds_file = os.path.expanduser('~/.rackspace_cloud_credentials')
	pyrax.set_credential_file(creds_file)
	available_regions = pyrax.regions

	print "Regions Available:", " ".join(list(available_regions))
	region = ""
	while region not in pyrax.regions:
		region = raw_input("Select region: ")
	cs = pyrax.connect_to_cloudservers(region)
	servers = cs.servers.list()
	srv_dict = {}

	print "Select a server from which an image will be created."
	for pos, srv in enumerate(servers):
	    print "%s: %s" % (pos, srv.name)
	    srv_dict[str(pos)] = srv.id
	selection = None
	while selection not in srv_dict:
	    if selection is not None:
	        print " -- Invalid choice"
	    selection = raw_input("Enter the number for your choice: ")

	server_id = srv_dict[selection]
	print
	nm = raw_input("Enter a name for the image: ")

	img_id = cs.servers.create_image(server_id, nm)

	print "Image '%s' is being created. Its ID is: %s" % (nm, img_id)
开发者ID:r3d91ll,项目名称:RAX-CloudAPI,代码行数:32,代码来源:test.py

示例15: __init__

    def __init__(self, quiet=False, credfile=None):
        self.quiet = quiet

        # Handle authentication
        if credfile is None:
            # No credentials passed
            try:
                if pyrax.identity.authenticated is False:
                    raise ValueError(
                        "ERROR: FLUFFY_BASE(): PyRAX is not authenticated and no authentication tokens passed."
                    )
            except AttributeError:
                raise ValueError("ERROR: FLUFFY_BASE(): PyRAX is not initialized and no authentication tokens passed.")

        else:
            # If we were passed tokens, just reauth.
            # TODO: Come up with some solution to see if reauth is required
            # (I don't think pyrax.identity gives us enough hooks right now.)

            if credfile is None:
                raise ValueError("ERROR: FLUFFY_BASE(): Either credfile is required")

            norm_conf_path = os.path.expanduser(os.path.normpath(credfile))
            pyrax.settings.read_config(norm_conf_path)  # Not sure if hack, emailed support
            pyrax.set_credential_file(norm_conf_path)
开发者ID:TJNII,项目名称:CloudTools,代码行数:25,代码来源:fluffyWrappers.py


注:本文中的pyrax.set_credential_file函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。