def createImage(id, name, notes): vsManager = VSManager(client) image = vsManager.capture(instance_id=id, name=name, additional_disks=True, notes=notes) return image
def orderServer(hostname, domain, datacenter, cpus, memory, hourly, os_code, image_id, local_disk, disks, nic_speed, post_uri, ssh_keys, private, dedicated, private_vlan, tags): vsManager = VSManager(client) instance = vsManager.create_instance( hostname=hostname, domain=domain, datacenter=datacenter, cpus=cpus, memory=memory, hourly=hourly, os_code=os_code, image_id=image_id, local_disk=local_disk, disks=disks, # [] if image nic_speed=nic_speed, post_uri=post_uri, ssh_keys=ssh_keys, private=private, dedicated=dedicated, private_vlan=private_vlan, tags=tags) #print simplejson.dumps(instance, sort_keys=True, indent=4 * ' ') return instance
def task_add_content_migration_meta_data(self, user_id, data): user = User.query.get(user_id) softlayer_clouds = user.project.softlayer_clouds.filter_by( status=VALID).all() for cloud in softlayer_clouds: client = create_client_from_env(cloud.username, decrypt_api_key(cloud.api_key)) vs_manger = VSManager(client) try: vsi_id = vs_manger.list_instances(public_ip=data["ip"])[0]["id"] break except (KeyError, IndexError): vsi_id = None if not vsi_id: LOGGER.info( f"VSI Not Found for public IP: {data['ip']} against user: {user_id}" ) return cm_object = CMModels.query.filter_by(softlayer_vsi_id=vsi_id).first() if cm_object: cm_object.cm_meta_data = data else: cm_object = CMModels(softlayer_vsi_id=vsi_id, cm_meta_data=data) doosradb.session.add(cm_object) doosradb.session.commit() cm_object = CMModels.query.filter_by(softlayer_vsi_id=vsi_id).first() if cm_object: cm_object.cm_meta_data = data else: cm_object = CMModels(softlayer_vsi_id=vsi_id, cm_meta_data=data) doosradb.session.add(cm_object) doosradb.session.commit() LOGGER.info(f"VSI: {vsi_id} meta data saved for user: {user_id}")
def execute(self, args): public = args['public'] vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') vsi.change_port_speed(vs_id, public, args['--speed'])
def orderServer(counter): uniqueHostname = '' if (args.uniqueId != ''): uniqueHostname = args.uniqueId + "-" uniqueHostname += args.hostname + "-" + str(counter) if (args.verbose): print 'Building: ' + uniqueHostname disks = [] if (args.localDisk): disks.append(args.localDisk1Size) if (args.localDisk and args.localDisk2Size != None): disks.append(args.localDisk2Size) else: disks.append(args.sanDisk1Size) if (args.sanDisk2Size != None): disks.append(args.sanDisk2Size) if (args.sanDisk3Size != None): disks.append(args.sanDisk3Size) if (args.sanDisk4Size != None): disks.append(args.sanDisk4Size) if (args.sanDisk5Size != None): disks.append(args.sanDisk5Size) osCode = '' templateGuid = '' if (args.osCode != None and args.osCode != ''): osCode = args.osCode templateGuid = '' else: osCode = '' templateGuid = args.templateGuid disks = [] # Blank out disks since it will use the template sshKeys = [] if (args.sshKey != None and args.sshKey != ''): sshKeys.append(args.sshKey) vsManager = VSManager(client) instance = vsManager.create_instance(hostname=uniqueHostname, domain=args.domain, cpus=args.cpus, memory=args.memory, hourly=args.hourly, datacenter=args.datacenter, os_code=osCode, image_id=templateGuid, local_disk=args.localDisk, disks=disks, ssh_keys=sshKeys, nic_speed=args.nicSpeed, private=args.private, private_vlan=args.privateVlan, dedicated=args.dedicated, post_uri=args.postInstallUrl, tags=args.tag) return instance
def execute(self, args): vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--really'] or no_going_back(vs_id): vsi.cancel_instance(vs_id) else: CLIAbort('Aborted')
def execute(self, args): vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--all']: additional_disks = True else: additional_disks = False capture = vsi.capture(vs_id, args.get('--name'), additional_disks, args.get('--note')) table = KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['vs_id', capture['guestId']]) table.add_row(['date', capture['createDate'][:10]]) table.add_row(['time', capture['createDate'][11:19]]) table.add_row(['transaction', transaction_status(capture)]) table.add_row(['transaction_id', capture['id']]) table.add_row(['all_disks', additional_disks]) return table
def execute(self, args): data = {} if args['--userdata'] and args['--userfile']: raise ArgumentError('[-u | --userdata] not allowed with ' '[-F | --userfile]') if args['--userfile']: if not os.path.exists(args['--userfile']): raise ArgumentError( 'File does not exist [-u | --userfile] = %s' % args['--userfile']) if args.get('--userdata'): data['userdata'] = args['--userdata'] elif args.get('--userfile'): with open(args['--userfile'], 'r') as userfile: data['userdata'] = userfile.read() data['hostname'] = args.get('--hostname') data['domain'] = args.get('--domain') vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if not vsi.edit(vs_id, **data): raise CLIAbort("Failed to update virtual server")
def getInstance(id): try: vsManager = VSManager(client) instance = vsManager.get_instance(id) return instance except: return None
def orderServer(self, counter, hostname, domain, cpus, memory, localDisk, private, hourly, datacenter, osCode, privateVlan, nicSpeed, dedicated, templateGuid, postInstallUrl, tag): uniqueHostname = hostname + "-" + str(counter) sshKeys = [] disks = [100] if (osCode != None and osCode != ''): templateGuid = '' else: osCode = '' disks = [] # Blank out disks since it will use the template vsManager = VSManager(self.Client) instance = vsManager.create_instance( hostname = uniqueHostname, domain = domain, cpus = cpus, memory = memory, hourly = hourly, datacenter = datacenter, os_code = osCode, image_id = templateGuid, local_disk = localDisk, disks = disks, ssh_keys = sshKeys, nic_speed = nicSpeed, private = private, private_vlan = privateVlan, dedicated = dedicated, post_uri = postInstallUrl, tags = tag) return instance
def execute(self, args): vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') ready = vsi.wait_for_ready(vs_id, int(args.get('--wait') or 0)) if ready: return "READY" else: raise CLIAbort("Instance %s not ready" % vs_id)
def execute(self, args): vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') keys = [] if args.get('--key'): for key in args.get('--key'): key_id = resolve_id(SshKeyManager(self.client).resolve_ids, key, 'SshKey') keys.append(key_id) if args['--really'] or no_going_back(vs_id): vsi.reload_instance(vs_id, args['--postinstall'], keys) else: CLIAbort('Aborted')
def _update_with_like_args(self, args): """ Update arguments with options taken from a currently running VS. :param VSManager args: A VSManager :param dict args: CLI arguments """ if args['--like']: vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.pop('--like'), 'VS') like_details = vsi.get_instance(vs_id) like_args = { '--hostname': like_details['hostname'], '--domain': like_details['domain'], '--cpu': like_details['maxCpu'], '--memory': like_details['maxMemory'], '--hourly': like_details['hourlyBillingFlag'], '--monthly': not like_details['hourlyBillingFlag'], '--datacenter': like_details['datacenter']['name'], '--network': like_details['networkComponents'][0]['maxSpeed'], '--user-data': like_details['userData'] or None, '--postinstall': like_details.get('postInstallScriptUri'), '--dedicated': like_details['dedicatedAccountHostOnlyFlag'], '--private': like_details['privateNetworkOnlyFlag'], } # Handle mutually exclusive options like_image = lookup(like_details, 'blockDeviceTemplateGroup', 'globalIdentifier') like_os = lookup(like_details, 'operatingSystem', 'softwareLicense', 'softwareDescription', 'referenceCode') if like_image and not args.get('--os'): like_args['--image'] = like_image elif like_os and not args.get('--image'): like_args['--os'] = like_os if args.get('--hourly'): like_args['--monthly'] = False if args.get('--monthly'): like_args['--hourly'] = False # Merge like VS options with the options passed in for key, value in like_args.items(): if args.get(key) in [None, False]: args[key] = value
def execute(self, args): vsi = VSManager(self.client) data = {} data['cpus'] = args.get('--cpu') data['memory'] = args.get('--memory') data['nic_speed'] = args.get('--network') data['public'] = True if args.get('--private'): data['public'] = False data = self.verify_upgrade_parameters(data) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--really'] or confirm( "This action will incur charges on your account. " "Continue?"): if not vsi.upgrade(vs_id, **data): raise CLIAbort('VS Upgrade Failed')
def provisionServers(self, quantity, hostname, domain, cpus, memory, localDisk, private, hourly, datacenter, osCode, privateVlan, nicSpeed, dedicated, templateGuid, postInstallUrl, tag): print 'Begin Provisioning: ' + time.strftime('%Y-%m-%d %I:%M:%S %Z') startTime = datetime.now() serverIds = [] counter = 1 completed = False if ',' in tag: tag = tag.split(',')[0] while counter <= quantity: createdInstance = self.orderServer(counter, hostname, domain, cpus, memory, localDisk, private, hourly, datacenter, osCode, privateVlan, nicSpeed, dedicated, templateGuid, postInstallUrl, tag) createdId = createdInstance['id'] print 'Built Server: ' + str(createdId) serverIds.append(createdId) counter += 1 vsManager = VSManager(self.Client) print 'Waiting for provisioning completion' while completed == False: time.sleep(10) exit = True for serverId in serverIds: time.sleep(1) instance = vsManager.get_instance(serverId) if 'activeTransaction' in instance.keys(): activeTransaction = instance['activeTransaction']['transactionStatus']['name'] if activeTransaction != 'SERVICE_SETUP': exit = False if exit == True: completed = True print 'Sleeping for 1 minute before power off' time.sleep(60) # Power Off servers for serverId in serverIds: print 'Powering off: ' + str(serverId) time.sleep(1) self.Client['Virtual_Guest'].powerOff(id=serverId) time.sleep(60) print 'Completed Provisioning: ' + time.strftime('%Y-%m-%d %I:%M:%S %Z')
def orderServer(hostname, domain, cpus, memory, disk, osCode, templateGuid, useLocalDisk, datacenter, private, dedicated, hourly, tag, privateVlan, nicSpeed, sshKey, userData, postInstallUrl): disks = [] disks.append(disk) if (osCode != None and osCode != ''): templateGuid = '' else: osCode = '' disks = [] # Blank out disks since it will use the template sshKeys = [] if (sshKey != None and sshKey != ''): sshKeys.append(sshKey) vsManager = VSManager(client) instance = vsManager.create_instance(hostname=hostname, domain=domain, cpus=cpus, memory=memory, hourly=hourly, datacenter=datacenter, os_code=osCode, image_id=templateGuid, local_disk=useLocalDisk, disks=disks, ssh_keys=sshKeys, nic_speed=nicSpeed, private=private, private_vlan=privateVlan, dedicated=dedicated, post_uri=postInstallUrl, userdata=userData, tags=tag) return instance
def execute(self, args): vsi = VSManager(self.client) tags = None if args.get('--tags'): tags = [tag.strip() for tag in args.get('--tags').split(',')] guests = vsi.list_instances(hourly=args.get('--hourly'), monthly=args.get('--monthly'), hostname=args.get('--hostname'), domain=args.get('--domain'), cpus=args.get('--cpu'), memory=args.get('--memory'), datacenter=args.get('--datacenter'), nic_speed=args.get('--network'), tags=tags) table = Table([ 'id', 'datacenter', 'host', 'cores', 'memory', 'primary_ip', 'backend_ip', 'active_transaction', ]) table.sortby = args.get('--sortby') or 'host' for guest in guests: guest = NestedDict(guest) table.add_row([ guest['id'], guest['datacenter']['name'] or blank(), guest['fullyQualifiedDomainName'], guest['maxCpu'], mb_to_gb(guest['maxMemory']), guest['primaryIpAddress'] or blank(), guest['primaryBackendIpAddress'] or blank(), active_txn(guest), ]) return table
def orderServer(hostname,domain,datacenter,cpus,memory,hourly,os_code,image_id,local_disk,disks,nic_speed,post_uri,ssh_keys,private,dedicated,private_vlan,tags): vsManager = VSManager(client) instance = vsManager.create_instance( hostname = hostname, domain = domain, datacenter = datacenter, cpus = cpus, memory = memory, hourly = hourly, os_code = os_code, image_id = image_id, local_disk = local_disk, disks = disks, # [] if image nic_speed = nic_speed, post_uri = post_uri, ssh_keys = ssh_keys, private = private, dedicated = dedicated, private_vlan = private_vlan, tags = tags) #print simplejson.dumps(instance, sort_keys=True, indent=4 * ' ') return instance
def orderServer(hostname, domain, cpus, memory, disk, osCode, templateGuid, useLocalDisk, datacenter, private, dedicated, hourly, tag, privateVlan, nicSpeed, sshKey, userData, postInstallUrl): disks = [] disks.append(disk) if (osCode != None and osCode != ''): templateGuid = '' else: osCode = '' disks = [] # Blank out disks since it will use the template sshKeys = [] if (sshKey != None and sshKey != ''): sshKeys.append(sshKey) vsManager = VSManager(client) instance = vsManager.create_instance( hostname = hostname, domain = domain, cpus = cpus, memory = memory, hourly = hourly, datacenter = datacenter, os_code = osCode, image_id = templateGuid, local_disk = useLocalDisk, disks = disks, ssh_keys = sshKeys, nic_speed = nicSpeed, private = private, private_vlan = privateVlan, dedicated = dedicated, post_uri = postInstallUrl, userdata = userData, tags = tag) return instance
def getCreateOptions(): vsManager = VSManager(client) options = vsManager.get_create_options() return options
def setUp(self): self.client = MagicMock() self.vs = VSManager(self.client) self.guestObject = self.client['Virtual_Guest'].getObject
def service_instances(): import uuid, os, yaml, json, docker, requests, traceback from SoftLayer import VSManager, Client id = request.args with open('/settings_softlayer.yml', 'r') as f: yaml_settings = yaml.load(f) json_settings = json.dumps(yaml_settings) data = json.loads(json_settings) sl_api_user = data['pattern']['api_ep'][0]['user'] sl_api_key = data['pattern']['api_ep'][0]['api_key'] client = Client(username=sl_api_user, api_key=sl_api_key) vs = VSManager(client) with open('/softlayer.json', 'r') as json_content_read: build_content_read = json.load(json_content_read) json_content_read.close() build_content_read['hostname'] = id[0] with open('/softlayer.json', 'w') as json_content_write: json_content_write.write(json.dumps(build_content_read)) json_content_write.close() with open('/softlayer.json') as json_content: build_content = json.load(json_content) if len(id) == 1: if request.env.request_method == "PUT": try: client['Virtual_Guest'].createObject(build_content) response = { "dashboard_url": id } return response except: print traceback.format_exc() if request.env.request_method == "DELETE": try: for i in vs.list_instances(): if str(i['hostname']) == str(id[0]): virtual_server_id = i['id'] vs.cancel_instance(virtual_server_id) response = {} return response except: raise HTTP(410, "Gone") response = {} return response if len(id) > 1: if request.env.request_method == "PUT": try: for i in vs.list_instances(): if str(i['hostname']) == str(id[0]): virtual_server_id = i['id'] ip_addr = vs.get_instance(virtual_server_id)['primaryIpAddress'] #username = vs.get_instance(virtual_server_id)['networkComponents']['operatingSystem']['passwords'][0]['username'] #password = vs.get_instance(virtual_server_id)['networkComponents']['operatingSystem']['passwords'][0]['password'] #response = {"credentials": [{"ip_address": ip_addr},{"username": username}, {"password": password}]} response = {"credentials": {"ip_address": ip_addr, "port": "11211"}} return response except: return traceback.format_exc() #raise HTTP(404, "Not Found") #response = {} #return response if request.env.request_method == "DELETE": response = {} return response
def cancelInstance(id): vsManager = VSManager(client) vsManager.cancel_instance(id) print 'Canceling : ' + str(id)
parser.add_option("-z", "--disks", dest="custom_disk", default=None) parser.add_option("-n", "--network", dest="network", default='1Gb') parser.add_option("-q", "--quantity", dest="quantity", default=1) parser.add_option("-i", "--image", dest="image", default='CentOS-7') parser.add_option("-r", "--region", dest="datacenter", default='sao01') parser.add_option("-l", "--local-only", dest="local_only", default=False) (opt, args) = parser.parse_args() sl_user = '******' sl_apikey = 'YOUR_SOFTLAYER_AKEY' image_regex = r'[a-zA-Z0-9]{8}(-[a-zA-Z0-9]{4}){3}-[a-zA-Z0-9]{12}' client = Client(username=sl_user,api_key=sl_apikey) vs = VSManager(client) def _str_to_bool(s): if s in ['True', 'true', 't', 1]: return True return False config = { 'domain': 'mydomain.com', 'cpu': int(opt.cpu), 'memory': str(opt.memory), 'network': str(opt.network), 'name': str(opt.server_name), 'billing': str(opt.billing), 'environment': str(opt.environment),
def captureImage(instanceId, name, additional_disks, notes): vsManager = VSManager(client) image = vsManager.capture(instanceId, name, additional_disks, notes) print 'Creating Image: ' + name return image.id # Returns just a transaction Id / Not the actual Image Id ??
class VSWaitReadyGoTests(unittest.TestCase): def setUp(self): self.client = MagicMock() self.vs = VSManager(self.client) self.guestObject = self.client['Virtual_Guest'].getObject @patch('SoftLayer.managers.vs.VSManager.wait_for_ready') def test_wait_interface(self, ready): # verify interface to wait_for_ready is intact self.vs.wait_for_transaction(1, 1) ready.assert_called_once_with(1, 1, delay=1, pending=True) def test_active_not_provisioned(self): # active transaction and no provision date should be false self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}}, ] value = self.vs.wait_for_ready(1, 1) self.assertFalse(value) def test_active_and_provisiondate(self): # active transaction and provision date should be True self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}, 'provisionDate': 'aaa'}, ] value = self.vs.wait_for_ready(1, 1) self.assertTrue(value) def test_active_provision_pending(self): # active transaction and provision date # and pending should be false self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}, 'provisionDate': 'aaa'}, ] value = self.vs.wait_for_ready(1, 1, pending=True) self.assertFalse(value) def test_active_reload(self): # actively running reload self.guestObject.side_effect = [ { 'activeTransaction': {'id': 1}, 'provisionDate': 'aaa', 'lastOperatingSystemReload': {'id': 1}, }, ] value = self.vs.wait_for_ready(1, 1) self.assertFalse(value) def test_reload_no_pending(self): # reload complete, maintance transactions self.guestObject.side_effect = [ { 'activeTransaction': {'id': 2}, 'provisionDate': 'aaa', 'lastOperatingSystemReload': {'id': 1}, }, ] value = self.vs.wait_for_ready(1, 1) self.assertTrue(value) def test_reload_pending(self): # reload complete, pending maintance transactions self.guestObject.side_effect = [ { 'activeTransaction': {'id': 2}, 'provisionDate': 'aaa', 'lastOperatingSystemReload': {'id': 1}, }, ] value = self.vs.wait_for_ready(1, 1, pending=True) self.assertFalse(value) @patch('SoftLayer.managers.vs.sleep') def test_ready_iter_once_incomplete(self, _sleep): self.guestObject = self.client['Virtual_Guest'].getObject # no iteration, false self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}}, ] value = self.vs.wait_for_ready(1, 1) self.assertFalse(value) self.assertFalse(_sleep.called) @patch('SoftLayer.managers.vs.sleep') def test_iter_once_complete(self, _sleep): # no iteration, true self.guestObject.side_effect = [ {'provisionDate': 'aaa'}, ] value = self.vs.wait_for_ready(1, 1) self.assertTrue(value) self.assertFalse(_sleep.called) @patch('SoftLayer.managers.vs.sleep') def test_iter_four_complete(self, _sleep): # test 4 iterations with positive match self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'provisionDate': 'aaa'}, ] value = self.vs.wait_for_ready(1, 4) self.assertTrue(value) _sleep.assert_has_calls([call(1), call(1), call(1)]) self.guestObject.assert_has_calls([ call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), ]) @patch('SoftLayer.managers.vs.sleep') def test_iter_two_incomplete(self, _sleep): # test 2 iterations, with no matches self.guestObject.side_effect = [ {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'provisionDate': 'aaa'} ] value = self.vs.wait_for_ready(1, 2) self.assertFalse(value) _sleep.assert_called_once_with(1) self.guestObject.assert_has_calls([ call(id=1, mask=ANY), call(id=1, mask=ANY), ]) @patch('SoftLayer.managers.vs.sleep') def test_iter_ten_incomplete(self, _sleep): # 10 iterations at 10 second sleeps with no # matching values. self.guestObject.side_effect = [ {}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, {'activeTransaction': {'id': 1}}, ] value = self.vs.wait_for_ready(1, 10, delay=10) self.assertFalse(value) self.guestObject.assert_has_calls([ call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), call(id=1, mask=ANY), ]) # should only be 9 calls to sleep, last iteration # should return a value and skip the sleep _sleep.assert_has_calls([ call(10), call(10), call(10), call(10), call(10), call(10), call(10), call(10), call(10)])
def cancelInstance(id): vsManager = VSManager(client) vsManager.cancel_instance(id) print 'Canceling: ' + str(id)
def getInstance(id): vsManager = VSManager(client) instance = vsManager.get_instance(id) return instance
def getInstances(tag): vsManager = VSManager(client) instances = vsManager.list_instances(tags=[tag]) print json.dumps(instances, sort_keys=True, indent=4) return instances
def getInstance(id): vsManager = VSManager(client) instance = vsManager.get_instance(id) print json.dumps(instance, sort_keys=True, indent=4) return instance
def dns_sync(self, args): """ Sync DNS records to match the FQDN of the virtual server """ dns = DNSManager(self.client) vsi = VSManager(self.client) vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') instance = vsi.get_instance(vs_id) zone_id = resolve_id(dns.resolve_ids, instance['domain'], name='zone') def sync_a_record(): """ Sync A record """ records = dns.get_records( zone_id, host=instance['hostname'], ) if not records: # don't have a record, lets add one to the base zone dns.create_record( zone['id'], instance['hostname'], 'a', instance['primaryIpAddress'], ttl=args['--ttl']) else: recs = [x for x in records if x['type'].lower() == 'a'] if len(recs) != 1: raise CLIAbort("Aborting A record sync, found %d " "A record exists!" % len(recs)) rec = recs[0] rec['data'] = instance['primaryIpAddress'] rec['ttl'] = args['--ttl'] dns.edit_record(rec) def sync_ptr_record(): """ Sync PTR record """ host_rec = instance['primaryIpAddress'].split('.')[-1] ptr_domains = self.client['Virtual_Guest'].\ getReverseDomainRecords(id=instance['id'])[0] edit_ptr = None for ptr in ptr_domains['resourceRecords']: if ptr['host'] == host_rec: ptr['ttl'] = args['--ttl'] edit_ptr = ptr break if edit_ptr: edit_ptr['data'] = instance['fullyQualifiedDomainName'] dns.edit_record(edit_ptr) else: dns.create_record( ptr_domains['id'], host_rec, 'ptr', instance['fullyQualifiedDomainName'], ttl=args['--ttl']) if not instance['primaryIpAddress']: raise CLIAbort('No primary IP address associated with this VS') try: zone = dns.get_zone(zone_id) except DNSZoneNotFound: raise CLIAbort("Unable to create A record, " "no zone found matching: %s" % instance['domain']) go_for_it = args['--really'] or confirm( "Attempt to update DNS records for %s" % instance['fullyQualifiedDomainName']) if not go_for_it: raise CLIAbort("Aborting DNS sync") both = False if not args['--ptr'] and not args['-a']: both = True if both or args['-a']: sync_a_record() if both or args['--ptr']: sync_ptr_record()
def orderServer(counter): uniqueHostname = '' if (args.uniqueId != ''): uniqueHostname = args.uniqueId + "-" uniqueHostname += args.hostname + "-" + str(counter) if (args.verbose): print 'Building: ' + uniqueHostname disks = [] if (args.localDisk): disks.append(args.localDisk1Size) if (args.localDisk and args.localDisk2Size != None): disks.append(args.localDisk2Size) else: disks.append(args.sanDisk1Size) if (args.sanDisk2Size != None): disks.append(args.sanDisk2Size) if (args.sanDisk3Size != None): disks.append(args.sanDisk3Size) if (args.sanDisk4Size != None): disks.append(args.sanDisk4Size) if (args.sanDisk5Size != None): disks.append(args.sanDisk5Size) osCode = '' templateGuid = '' if (args.osCode != None and args.osCode != ''): osCode = args.osCode templateGuid = '' else: osCode = '' templateGuid = args.templateGuid disks = [] # Blank out disks since it will use the template sshKeys = [] if (args.sshKey != None and args.sshKey != ''): sshKeys.append(args.sshKey) vsManager = VSManager(client) instance = vsManager.create_instance( hostname = uniqueHostname, domain = args.domain, cpus = args.cpus, memory = args.memory, hourly = args.hourly, datacenter = args.datacenter, os_code = osCode, image_id = templateGuid, local_disk = args.localDisk, disks = disks, ssh_keys = sshKeys, nic_speed = args.nicSpeed, private = args.private, private_vlan = args.privateVlan, dedicated = args.dedicated, post_uri = args.postInstallUrl, tags = args.tag) return instance
def execute(self, args): update_with_template_args(args) vsi = VSManager(self.client) self._update_with_like_args(args) # Disks will be a comma-separated list. Let's make it a real list. if isinstance(args.get('--disk'), str): args['--disk'] = args.get('--disk').split(',') # SSH keys may be a comma-separated list. Let's make it a real list. if isinstance(args.get('--key'), str): args['--key'] = args.get('--key').split(',') self._validate_args(args) # Do not create a virtual server with --test or --export do_create = not (args['--export'] or args['--test']) table = Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' data = self._parse_create_args(args) output = [] if args.get('--test'): result = vsi.verify_create_instance(**data) total_monthly = 0.0 total_hourly = 0.0 table = Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' for price in result['prices']: total_monthly += float(price.get('recurringFee', 0.0)) total_hourly += float(price.get('hourlyRecurringFee', 0.0)) if args.get('--hourly'): rate = "%.2f" % float(price['hourlyRecurringFee']) else: rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) if args.get('--hourly'): total = total_hourly else: total = total_monthly billing_rate = 'monthly' if args.get('--hourly'): billing_rate = 'hourly' table.add_row(['Total %s cost' % billing_rate, "%.2f" % total]) output.append(table) output.append(FormattedItem( None, ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.') ) if args['--export']: export_file = args.pop('--export') export_to_template(export_file, args, exclude=['--wait', '--test']) return 'Successfully exported options to a template file.' if do_create: if args['--really'] or confirm( "This action will incur charges on your account. " "Continue?"): result = vsi.create_instance(**data) table = KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['id']]) table.add_row(['created', result['createDate']]) table.add_row(['guid', result['globalIdentifier']]) output.append(table) if args.get('--wait'): ready = vsi.wait_for_ready( result['id'], int(args.get('--wait') or 1)) table.add_row(['ready', ready]) else: raise CLIAbort('Aborting virtual server order.') return output
def createImage(id, name, notes): vsManager = VSManager(client) image = vsManager.capture(instance_id=id,name=name,additional_disks=True,notes=notes) return image
def setUp(self): self.client = FixtureClient() self.vs = VSManager(self.client)
def getInstances(): vsManager = VSManager(client) instances = vsManager.list_instances(tags=tags,datacenter=datacenter) return instances
class VSTests(unittest.TestCase): def setUp(self): self.client = FixtureClient() self.vs = VSManager(self.client) def test_list_instances(self): mcall = call(mask=ANY, filter={}) service = self.client['Account'] list_expected_ids = [100, 104] hourly_expected_ids = [104] monthly_expected_ids = [100] results = self.vs.list_instances(hourly=True, monthly=True) service.getVirtualGuests.assert_has_calls(mcall) for result in results: self.assertIn(result['id'], list_expected_ids) result = self.vs.list_instances(hourly=False, monthly=False) service.getVirtualGuests.assert_has_calls(mcall) for result in results: self.assertIn(result['id'], list_expected_ids) results = self.vs.list_instances(hourly=False, monthly=True) service.getMonthlyVirtualGuests.assert_has_calls(mcall) for result in results: self.assertIn(result['id'], monthly_expected_ids) results = self.vs.list_instances(hourly=True, monthly=False) service.getHourlyVirtualGuests.assert_has_calls(mcall) for result in results: self.assertIn(result['id'], hourly_expected_ids) def test_list_instances_with_filters(self): self.vs.list_instances( hourly=True, monthly=True, tags=['tag1', 'tag2'], cpus=2, memory=1024, hostname='hostname', domain='example.com', local_disk=True, datacenter='dal05', nic_speed=100, public_ip='1.2.3.4', private_ip='4.3.2.1', ) service = self.client['Account'] service.getVirtualGuests.assert_has_calls(call( filter={ 'virtualGuests': { 'datacenter': { 'name': {'operation': '_= dal05'}}, 'domain': {'operation': '_= example.com'}, 'tagReferences': { 'tag': {'name': { 'operation': 'in', 'options': [{ 'name': 'data', 'value': ['tag1', 'tag2']}]}}}, 'maxCpu': {'operation': 2}, 'localDiskFlag': {'operation': True}, 'maxMemory': {'operation': 1024}, 'hostname': {'operation': '_= hostname'}, 'networkComponents': {'maxSpeed': {'operation': 100}}, 'primaryIpAddress': {'operation': '_= 1.2.3.4'}, 'primaryBackendIpAddress': {'operation': '_= 4.3.2.1'} }}, mask=ANY, )) def test_resolve_ids_ip(self): service = self.client['Account'] _id = self.vs._get_ids_from_ip('172.16.240.2') self.assertEqual(_id, [100, 104]) _id = self.vs._get_ids_from_ip('nope') self.assertEqual(_id, []) # Now simulate a private IP test service.getVirtualGuests.side_effect = [[], [{'id': 99}]] _id = self.vs._get_ids_from_ip('10.0.1.87') self.assertEqual(_id, [99]) def test_resolve_ids_hostname(self): _id = self.vs._get_ids_from_hostname('vs-test1') self.assertEqual(_id, [100, 104]) def test_get_instance(self): result = self.vs.get_instance(100) self.client['Virtual_Guest'].getObject.assert_called_once_with( id=100, mask=ANY) self.assertEqual(Virtual_Guest.getObject, result) def test_get_create_options(self): results = self.vs.get_create_options() self.assertEqual(Virtual_Guest.getCreateObjectOptions, results) def test_cancel_instance(self): self.vs.cancel_instance(1) self.client['Virtual_Guest'].deleteObject.assert_called_once_with(id=1) def test_reload_instance(self): post_uri = 'http://test.sftlyr.ws/test.sh' self.vs.reload_instance(1, post_uri=post_uri, ssh_keys=[1701]) service = self.client['Virtual_Guest'] f = service.reloadOperatingSystem f.assert_called_once_with('FORCE', {'customProvisionScriptUri': post_uri, 'sshKeyIds': [1701]}, id=1) @patch('SoftLayer.managers.vs.VSManager._generate_create_dict') def test_create_verify(self, create_dict): create_dict.return_value = {'test': 1, 'verify': 1} self.vs.verify_create_instance(test=1, verify=1) create_dict.assert_called_once_with(test=1, verify=1) f = self.client['Virtual_Guest'].generateOrderTemplate f.assert_called_once_with({'test': 1, 'verify': 1}) @patch('SoftLayer.managers.vs.VSManager._generate_create_dict') def test_create_instance(self, create_dict): create_dict.return_value = {'test': 1, 'verify': 1} self.vs.create_instance(test=1, verify=1) create_dict.assert_called_once_with(test=1, verify=1) self.client['Virtual_Guest'].createObject.assert_called_once_with( {'test': 1, 'verify': 1}) def test_generate_os_and_image(self): self.assertRaises( ValueError, self.vs._generate_create_dict, cpus=1, memory=1, hostname='test', domain='example.com', os_code=1, image_id=1, ) def test_generate_missing(self): self.assertRaises(ValueError, self.vs._generate_create_dict) self.assertRaises(ValueError, self.vs._generate_create_dict, cpus=1) def test_generate_basic(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, } self.assertEqual(data, assert_data) def test_generate_monthly(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", hourly=False, ) assert_data = { 'hourlyBillingFlag': False, 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", } self.assertEqual(data, assert_data) def test_generate_image_id(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', image_id="45", ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'blockDeviceTemplateGroup': {"globalIdentifier": "45"}, 'hourlyBillingFlag': True, } self.assertEqual(data, assert_data) def test_generate_dedicated(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", dedicated=True, ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'dedicatedAccountHostOnlyFlag': True, } self.assertEqual(data, assert_data) def test_generate_datacenter(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", datacenter="sng01", ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'datacenter': {"name": 'sng01'}, } self.assertEqual(data, assert_data) def test_generate_public_vlan(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", public_vlan=1, ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'primaryNetworkComponent': {"networkVlan": {"id": 1}}, } self.assertEqual(data, assert_data) def test_generate_private_vlan(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", private_vlan=1, ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'primaryBackendNetworkComponent': {"networkVlan": {"id": 1}}, } self.assertEqual(data, assert_data) def test_generate_userdata(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", userdata="ICANHAZVSI", ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'userData': [{'value': "ICANHAZVSI"}], } self.assertEqual(data, assert_data) def test_generate_network(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", nic_speed=9001, ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'networkComponents': [{'maxSpeed': 9001}], } self.assertEqual(data, assert_data) def test_generate_private_network_only(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", nic_speed=9001, private=True ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'privateNetworkOnlyFlag': True, 'hourlyBillingFlag': True, 'networkComponents': [{'maxSpeed': 9001}], } self.assertEqual(data, assert_data) def test_generate_post_uri(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", post_uri='https://example.com/boostrap.sh', ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'postInstallScriptUri': 'https://example.com/boostrap.sh', } self.assertEqual(data, assert_data) def test_generate_sshkey(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", ssh_keys=[543], ) assert_data = { 'startCpus': 1, 'maxMemory': 1, 'hostname': 'test', 'domain': 'example.com', 'localDiskFlag': True, 'operatingSystemReferenceCode': "STRING", 'hourlyBillingFlag': True, 'sshKeys': [{'id': 543}], } self.assertEqual(data, assert_data) def test_generate_no_disks(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING" ) self.assertEqual(data.get('blockDevices'), None) def test_generate_single_disk(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", disks=[50] ) assert_data = { 'blockDevices': [ {"device": "0", "diskImage": {"capacity": 50}}] } self.assertTrue(data.get('blockDevices')) self.assertEqual(data['blockDevices'], assert_data['blockDevices']) def test_generate_multi_disk(self): data = self.vs._generate_create_dict( cpus=1, memory=1, hostname='test', domain='example.com', os_code="STRING", disks=[50, 70, 100] ) assert_data = { 'blockDevices': [ {"device": "0", "diskImage": {"capacity": 50}}, {"device": "2", "diskImage": {"capacity": 70}}, {"device": "3", "diskImage": {"capacity": 100}}] } self.assertTrue(data.get('blockDevices')) self.assertEqual(data['blockDevices'], assert_data['blockDevices']) def test_change_port_speed_public(self): vs_id = 1 speed = 100 self.vs.change_port_speed(vs_id, True, speed) service = self.client['Virtual_Guest'] f = service.setPublicNetworkInterfaceSpeed f.assert_called_once_with(speed, id=vs_id) def test_change_port_speed_private(self): vs_id = 2 speed = 10 self.vs.change_port_speed(vs_id, False, speed) service = self.client['Virtual_Guest'] f = service.setPrivateNetworkInterfaceSpeed f.assert_called_once_with(speed, id=vs_id) def test_edit(self): # Test editing user data service = self.client['Virtual_Guest'] self.vs.edit(100, userdata='my data') service.setUserMetadata.assert_called_once_with(['my data'], id=100) # Now test a blank edit self.assertTrue(self.vs.edit, 100) # Finally, test a full edit args = { 'hostname': 'new-host', 'domain': 'new.sftlyr.ws', 'notes': 'random notes', } self.vs.edit(100, **args) service.editObject.assert_called_once_with(args, id=100) def test_captures(self): archive = self.client['Virtual_Guest'].createArchiveTransaction # capture only the OS disk self.vs.capture(1, 'a') archive.called_once_with('a', [{"device": 0}], "", id=1) archive.reset() # capture all the disks, minus the swap # make sure the data is carried along with it self.vs.capture(1, 'a', additional_disks=True) archive.called_once_with('a', [{"device": 0, "uuid": 1}, {"device": 2, "uuid": 2}], "", id=1) def test_upgrade(self): # Testing Upgrade orderClient = self.client['Product_Order'] # test single upgrade self.vs.upgrade(1, cpus=4, public=False) orderClient.placeOrder.called_once_with(1, cpus=4, public=False) # Now test a blank upgrade self.vs.upgrade(1) self.assertTrue(self.vs.upgrade, 1) # Testing all parameters Upgrade self.vs.upgrade(1, cpus=4, memory=2, nic_speed=1000, public=True) args = {'cpus': 4, 'memory': 2, 'nic_speed': 1000, 'public': 1000} orderClient.placeOrder.called_once_with(1, **args) def test_get_item_id_for_upgrade(self): item_id = 0 package_items = self.client['Product_Package'].getItems(id=46) for item in package_items: if ((item['categories'][0]['id'] == 3) and (item.get('capacity') == '2')): item_id = item['prices'][0]['id'] break self.assertEqual(1133, item_id)
def getInstances(tag): vsManager = VSManager(client) instances = vsManager.list_instances(tags = [tag]) return instances
def getInstances(): vsManager = VSManager(client) instances = vsManager.list_instances(tags=tags, datacenter=datacenter) return instances
def getInstances(tag): vsManager = VSManager(client) instances = vsManager.list_instances(tags=[tag]) return instances
def execute(self, args): vsi = VSManager(self.client) table = KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') result = vsi.get_instance(vs_id) result = NestedDict(result) table.add_row(['id', result['id']]) table.add_row(['hostname', result['fullyQualifiedDomainName']]) table.add_row(['status', FormattedItem( result['status']['keyName'] or blank(), result['status']['name'] or blank() )]) table.add_row(['active_transaction', active_txn(result)]) table.add_row(['state', FormattedItem( lookup(result, 'powerState', 'keyName'), lookup(result, 'powerState', 'name'), )]) table.add_row(['datacenter', result['datacenter']['name'] or blank()]) operating_system = lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {} table.add_row([ 'os', FormattedItem( operating_system.get('version') or blank(), operating_system.get('name') or blank() )]) table.add_row(['os_version', operating_system.get('version') or blank()]) table.add_row(['cores', result['maxCpu']]) table.add_row(['memory', mb_to_gb(result['maxMemory'])]) table.add_row(['public_ip', result['primaryIpAddress'] or blank()]) table.add_row(['private_ip', result['primaryBackendIpAddress'] or blank()]) table.add_row(['private_only', result['privateNetworkOnlyFlag']]) table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']]) table.add_row(['created', result['createDate']]) table.add_row(['modified', result['modifyDate']]) vlan_table = Table(['type', 'number', 'id']) for vlan in result['networkVlans']: vlan_table.add_row([ vlan['networkSpace'], vlan['vlanNumber'], vlan['id']]) table.add_row(['vlans', vlan_table]) if result.get('notes'): table.add_row(['notes', result['notes']]) if args.get('--price'): table.add_row(['price rate', result['billingItem']['recurringFee']]) if args.get('--passwords'): pass_table = Table(['username', 'password']) for item in result['operatingSystem']['passwords']: pass_table.add_row([item['username'], item['password']]) table.add_row(['users', pass_table]) tag_row = [] for tag in result['tagReferences']: tag_row.append(tag['tag']['name']) if tag_row: table.add_row(['tags', listing(tag_row, separator=',')]) if not result['privateNetworkOnlyFlag']: ptr_domains = self.client['Virtual_Guest'].\ getReverseDomainRecords(id=vs_id) for ptr_domain in ptr_domains: for ptr in ptr_domain['resourceRecords']: table.add_row(['ptr', ptr['data']]) return table
def execute(self, args): vsi = VSManager(self.client) result = vsi.get_create_options() show_all = True for opt_name in self.options: if args.get("--" + opt_name): show_all = False break if args['--all']: show_all = True table = KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' if args['--datacenter'] or show_all: datacenters = [dc['template']['datacenter']['name'] for dc in result['datacenters']] table.add_row(['datacenter', listing(datacenters, separator=',')]) if args['--cpu'] or show_all: standard_cpu = [x for x in result['processors'] if not x['template'].get( 'dedicatedAccountHostOnlyFlag', False)] ded_cpu = [x for x in result['processors'] if x['template'].get('dedicatedAccountHostOnlyFlag', False)] def add_cpus_row(cpu_options, name): """ Add CPU rows to the table """ cpus = [] for cpu_option in cpu_options: cpus.append(str(cpu_option['template']['startCpus'])) table.add_row(['cpus (%s)' % name, listing(cpus, separator=',')]) add_cpus_row(ded_cpu, 'private') add_cpus_row(standard_cpu, 'standard') if args['--memory'] or show_all: memory = [ str(m['template']['maxMemory']) for m in result['memory']] table.add_row(['memory', listing(memory, separator=',')]) if args['--os'] or show_all: op_sys = [ o['template']['operatingSystemReferenceCode'] for o in result['operatingSystems']] op_sys = sorted(op_sys) os_summary = set() for operating_system in op_sys: os_summary.add(operating_system[0:operating_system.find('_')]) for summary in sorted(os_summary): table.add_row([ 'os (%s)' % summary, linesep.join(sorted([x for x in op_sys if x[0:len(summary)] == summary])) ]) if args['--disk'] or show_all: local_disks = [x for x in result['blockDevices'] if x['template'].get('localDiskFlag', False)] san_disks = [x for x in result['blockDevices'] if not x['template'].get('localDiskFlag', False)] def add_block_rows(disks, name): """ Add block rows to the table """ simple = {} for disk in disks: block = disk['template']['blockDevices'][0] bid = block['device'] if bid not in simple: simple[bid] = [] simple[bid].append(str(block['diskImage']['capacity'])) for label in sorted(simple.keys()): table.add_row(['%s disk(%s)' % (name, label), listing(simple[label], separator=',')]) add_block_rows(local_disks, 'local') add_block_rows(san_disks, 'san') if args['--nic'] or show_all: speeds = [] for comp in result['networkComponents']: speed = comp['template']['networkComponents'][0]['maxSpeed'] speeds.append(str(speed)) speeds = sorted(speeds) table.add_row(['nic', listing(speeds, separator=',')]) return table
247808 ] INITIALDISK_SIZES = [25, 100] LOCALDISK_SIZES = [25, 100, 150, 200, 300] SANDISK_SIZES = [ 10, 20, 25, 30, 40, 50, 75, 100, 125, 150, 175, 200, 250, 300, 350, 400, 500, 750, 1000, 1500, 2000 ] NIC_SPEEDS = [10, 100, 1000] try: import SoftLayer from SoftLayer import VSManager HAS_SL = True vsManager = VSManager(SoftLayer.create_client_from_env()) except ImportError: HAS_SL = False def create_virtual_instance(module): instances = vsManager.list_instances( hostname=module.params.get('hostname'), domain=module.params.get('domain'), datacenter=module.params.get('datacenter')) if instances: return False, None # Check if OS or Image Template is provided (Can't be both, defaults to OS)
def getInstances(tag): vsManager = VSManager(client) instances = vsManager.list_instances(tags = [tag]) print json.dumps(instances, sort_keys=True, indent=4) return instances