本文整理汇总了Python中pyrax.set_credential_file函数的典型用法代码示例。如果您正苦于以下问题:Python set_credential_file函数的具体用法?Python set_credential_file怎么用?Python set_credential_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了set_credential_file函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: push_rackspace
def push_rackspace(fname, cred_file="rs.cred"):
creds_file = os.path.expanduser(cred_file)
pyrax.set_credential_file(cred_file)
cf = pyrax.cloudfiles
with open(fname, "rb") as f:
fdata = f.read()
obj = cf.store_object("cyclus", fname, fdata)
开发者ID:russellnibbelink,项目名称:cycamore,代码行数:7,代码来源:ref.py
示例17: provision
def provision():
# Set the credentials for pyrax
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file(".pyrax.cfg")
# Provision the server with Rackspace
server = pyrax.cloudservers.servers.create(
"warehouse-repository",
IMAGE_ID,
FLAVOR_ID,
)
# Store the password
fabric.state.env.password = server.adminPass
# Wait until the server is built
server = pyrax.utils.wait_for_build(server)
fabric.state.env.host_string = "[email protected]{}".format(
filter(lambda x: "." in x, server.networks["public"])[0],
)
# Bootstrap our environment
_bootstrap_environment()
# Write out our config
with open(".rackspace.json", "w") as rs:
json.dump(
{
"host_string": fabric.state.env.host_string,
"password": fabric.state.env.password,
},
rs,
)
开发者ID:Ivoz,项目名称:warehouse,代码行数:34,代码来源:deploy.py
示例18: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('base', help='The base hostname to use, 3x512MB'
' servers will be built using this base hostname')
parser.add_argument('--dc', required=False, help='The region to '
'build the servers in', choices=['DFW', 'ORD', 'LON'],
default=pyrax.default_region)
parser.add_argument('--image', required=False, help='The image ID to build'
' the servers with',
default='5cebb13a-f783-4f8c-8058-c4182c724ccd')
parser.add_argument('--count', required=False, help='Number of servers to '
'build. Default 2', default=2, type=int)
args = parser.parse_args()
credentials_file = os.path.expanduser('~/.rackspace_cloud_credentials')
pyrax.set_credential_file(credentials_file, region=args.dc)
cs = pyrax.cloudservers
clb = pyrax.cloud_loadbalancers
print 'Building servers in: %s' % args.dc
servers = {}
for i in xrange(0, args.count):
host = '%s%d' % (args.base, i)
print 'Creating server: %s' % host
servers[host] = cs.servers.create(host, args.image, 2)
print '%s: %s' % (host, servers[host].id)
statuses = ['ACTIVE', 'ERROR', 'UNKNOWN']
while filter(lambda server: server.status not in statuses,
servers.values()):
print 'Sleeping 30 seconds before checking for server readiness...'
time.sleep(30)
for host in servers:
if servers[host].status in statuses:
continue
servers[host].get()
nodes = []
for host, server in server_details.iteritems():
nodes.append(clb.Node(address=server.networks['private'][0], port=80,
condition='ENABLED'))
vip = clb.VirtualIP(type='PUBLIC')
lb = clb.create('%s-lb' % args.base, port=80, protocol='HTTP', nodes=nodes,
virtual_ips=[vip])
public_addresses = [vip.address for vip in lb.virtual_ips]
t = prettytable.PrettyTable(['ID', 'Host', 'Status', 'IP',
'Admin Password'])
for host, server in servers.iteritems():
t.add_row([server.id, host, server.status,
', '.join(server.networks['public']), server.adminPass])
print 'Servers and loadbalancer online and ready...'
print t
t = prettytable.PrettyTable(['ID', 'Name', 'IP Address'])
t.add_row([lb.id, lb.name, ', '.join(public_addresses)])
print
print t
开发者ID:DerRooster,项目名称:rax-api-challenge,代码行数:60,代码来源:challenge7.py
示例19: cloud_connect
def cloud_connect():
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
try:
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file(creds_file)
except exc.AuthenticationFailed:
print "Problem with credential file ~/.rackspace_cloud_credentials"
开发者ID:chris-mendoza,项目名称:cloud-examples,代码行数:7,代码来源:cloud_lb.py
示例20: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--region', metavar='region', default='ORD', choices=['ORD','DFW','LON'], help="Cloud region (default: ORD)")
parser.add_argument('--ttl', metavar='ttl', default=259200, type=int, help="CDN container TTL in seconds (default: 259200)")
parser.add_argument('--enable-log', action='store_true', help="Enable CDN log retention")
parser.add_argument('container', metavar='container', help="Cloud Files container name. Container will be created if it does not exist")
args = parser.parse_args()
pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"),region=args.region)
cf = pyrax.cloudfiles
if args.container not in cf.list_containers():
print "Container does not exist and will be created."
# if container already exists, create_container will still return existing container.
cont = cf.create_container(args.container)
cf.make_container_public(args.container, ttl=args.ttl)
cf.set_cdn_log_retention(cont, args.enable_log)
cont = cf.get_container(args.container)
print "Container CDN Enabled."
print "name:", cont.name
print "ttl:", cont.cdn_ttl
print "uri:", cont.cdn_uri
print "ssl uri:", cont.cdn_ssl_uri
print "streaming uri:", cont.cdn_streaming_uri
print "ios uri:", cont.cdn_ios_uri
print "log retention:", cont.cdn_log_retention
return
开发者ID:nonamed108,项目名称:apichallenges,代码行数:32,代码来源:challenge6.py
注:本文中的pyrax.set_credential_file函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论