def connect(self, access, authentication_data, region): ''' TBD ''' try: _status = 100 _fmsg = "An error has occurred, but no error message was captured" _username, _api_key, _api_type = authentication_data.split('-') if access.lower().count("private"): self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT) else: self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT) _resp = self.slconn.call('Account', 'getObject') _datacenters = SoftLayer.VSManager( self.slconn).get_create_options()['datacenters'] for _dcitem in _datacenters: if region == _dcitem['template']['datacenter']['name']: _region = _dcitem['template']['datacenter']['name'] _msg = "Selected region is " + str(region) + " (" + _region + ")" if _api_type.lower().count("baremetal"): self.nodeman = SoftLayer.HardwareManager(self.slconn) else: self.nodeman = SoftLayer.VSManager(self.slconn) self.sshman = SoftLayer.SshKeyManager(self.slconn) self.imageman = SoftLayer.ImageManager(self.slconn) _status = 0 except Exception as msg: _fmsg = str(msg) _status = 23 finally: if _status: _msg = self.get_description() + " connection failure: " + _fmsg cberr(_msg) raise CldOpsException(_msg, _status) else: _msg = self.get_description() + " connection successful." cbdebug(_msg) return _status, _msg, _region
def getSoftLayerClient(userid=None, apikey=None): if userid is None: if 'SL_USER' in os.environ: userid = os.environ['SL_USER'] if apikey is None: if 'SL_APIKEY' in os.environ: userid = os.environ['SL_APIKEY'] if userid is None and apikey is None: client = SoftLayer.create_client_from_env() else: client = SoftLayer.create_client_from_env(userid, apikey) return client
def main(dict): API_USERNAME = dict['user'] API_KEY = dict['apikey'] VSI = dict['vsi'] client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY) mgr = SoftLayer.VSManager(client) imageName = VSI + '_' + datetime.datetime.today().isoformat() try: virtualGuests = client['SoftLayer_Account'].getVirtualGuests() except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve virtual guest. " % (e.faultCode, e.faultString)) vsiFound = False res = "ERROR" virtualMachines = 'None' for virtualGuest in virtualGuests: if virtualGuest['hostname'] == VSI: vsiFound = True try: res = mgr.capture(instance_id=virtualGuest['id'], name=imageName, notes=API_USERNAME) print ("VSI", VSI, "is found. Now capturing an image template:", imageName) except SoftLayer.SoftLayerAPIError as e: vsiFound = e return { 'VSI' : VSI, 'ImageName' : imageName, 'Action_Performed' : vsiFound, 'result' : res }
def cli(ctx, format="table", config=None, debug=0, verbose=0, proxy=None, really=False, fixtures=False, **kwargs): """Main click CLI entry-point.""" # Set logging level debug_int = int(debug) if debug_int: verbose = debug_int if verbose: logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG)) # Populate environement with client and set it as the context object env = ctx.ensure_object(environment.Environment) env.skip_confirmations = really env.config_file = config env.format = format if env.client is None: # Environment can be passed in explicitly. This is used for testing if fixtures: client = SoftLayer.BaseClient(transport=SoftLayer.FixtureTransport(), auth=None) else: # Create SL Client client = SoftLayer.create_client_from_env(proxy=proxy, config_file=config) client.transport = SoftLayer.TimingTransport(client.transport) env.client = client
def __init__(self, **kwargs): self.updated_contents = dict() self.sl_events = dict() self.sl_tickets = dict() self.sl_client = SoftLayer.create_client_from_env(username=kwargs.get('sl_user'), api_key=kwargs.get('sl_apikey')) self.data_filename_prefix = kwargs.get('sl_user') self._deserialize_data() self.customer_name = self._get_customer_name() self.interval = kwargs.get('interval') self.notifier = None if kwargs.get('notifier') == 'slack': slack_token = kwargs.get('additonal_args').slack_token slack_channel = kwargs.get('additonal_args').slack_channel if slack_token is None: slack_token = os.environ.get('SLACK_TOKEN') if slack_channel is None: slack_channel = os.environ.get('SLACK_CHANNEL') logging.debug('Initiate a SlackNotifier with parameters: slack_channel=%s' % (slack_channel)) self.notifier = SlackNotifier(slack_token, slack_channel) self.start()
def __init__(self, **kwargs): self.updated_contents = dict() self.sl_events = dict() self.sl_tickets = dict() self.sl_client = SoftLayer.create_client_from_env( username=kwargs.get('sl_user'), api_key=kwargs.get('sl_apikey')) self.data_filename_prefix = kwargs.get('sl_user') self._deserialize_data() self.customer_name = self._get_customer_name() self.interval = kwargs.get('interval') self.notifier = None if kwargs.get('notifier') == 'slack': slack_token = kwargs.get('additonal_args').slack_token slack_channel = kwargs.get('additonal_args').slack_channel if slack_token is None: slack_token = os.environ.get('SLACK_TOKEN') if slack_channel is None: slack_channel = os.environ.get('SLACK_CHANNEL') logging.debug( 'Initiate a SlackNotifier with parameters: slack_channel=%s' % (slack_channel)) self.notifier = SlackNotifier(slack_token, slack_channel) self.start()
def main(params): try: if len(params) < 4: print("insufficient parameters!") else: sl_user = str(params[0]) sl_apikey = str(params[1]) instance_id = int(params[2]) image_name = str(params[3]) client = SoftLayer.create_client_from_env(username=sl_user, api_key=sl_apikey) # check if image with image_name exist or not # if exist, remove it imageManager = SoftLayer.ImageManager(client) image_list = imageManager.list_private_images(name=image_name) for image in image_list: info = imageManager.get_image(image['id']) print("found image with " + image_name + ", delete it") print(info) info = imageManager.delete_image(image['id']) # create transaction to capture the image vsManager = SoftLayer.VSManager(client) image_info = vsManager.capture(instance_id, image_name) print(image_info) except Exception: print(traceback.format_exc())
def main(dict): API_USERNAME = dict['user'] API_KEY = dict['apikey'] VSI = dict['vsi'] client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY) mgr = SoftLayer.VSManager(client) mgr_image = SoftLayer.ImageManager(client) vsiname = VSI image_list = mgr_image.list_private_images(name=vsiname + '_*') image_list.sort(key=lambda x: x['createDate']) number_of_snapshots = len(image_list) # print('*** Before deleting old image templates') # for i in range(0, number_of_snapshots): # print(image_list[i]['id'], image_list[i]['createDate'], image_list[i]['name'] ) deleted_image = [] if number_of_snapshots > 2: for i in range(0, number_of_snapshots - 2): # print(i, image_list[i]['id'], image_list[i]['createDate'], image_list[i]['name'] ) deleted_image.append(image_list[i]['name']) mgr_image.delete_image(image_list[i]['id']) return {'VSI': VSI, 'deleted_image': deleted_image}
def main(): parser = argparse.ArgumentParser() parser.add_argument('--username', default=os.environ.get('SL_USERNAME', None), required='SL_USERNAME' not in os.environ, help='SoftLayer username (default $SL_USERNAME)') parser.add_argument('--api-key', default=os.environ.get('SL_API_KEY', None), required='SL_API_KEY' not in os.environ, help='SoftLayer API key (default $SL_API_KEY)') parser.add_argument('-A', '--account-file', default='account.properties', type=argparse.FileType('w'), help='Path to write account.properties file to') parser.add_argument('-I', '--ipmiview-file', default='IPMIView.properties', type=argparse.FileType('w'), help='Path to write IPMIView.properties file to') args = parser.parse_args() client = SoftLayer.create_client_from_env(args.username, args.api_key) hardware = SoftLayer.managers.hardware.HardwareManager(client) for host in sorted(hardware.list_hardware(), key=lambda d: hostname_frags(d.get('hostname', None))): if 'globalIdentifier' not in host: continue hwinfo = hardware.get_hardware(host['globalIdentifier']) args.ipmiview_file.write('{hostname}={mgmt_ip}:{hostname}.{domain}\n'.format( hostname=hwinfo['hostname'], mgmt_ip=hwinfo['networkManagementIpAddress'], domain=hwinfo['domain'] )) if len(hwinfo['remoteManagementAccounts']) > 0: acct = hwinfo['remoteManagementAccounts'][0] args.account_file.write('{hostname}={username},{password}\n'.format( hostname=hwinfo['hostname'], username=acct['username'], password=encrypt_password(hwinfo['hostname'], acct['password']) ))
def get_client(environment): resource_handler = environment.resource_handler api_kwargs = { "username": resource_handler.serviceaccount, "api_key": str(resource_handler.servicepasswd), } client = SoftLayer.create_client_from_env(**api_kwargs) return client
def __init__(self, swift_username, swift_auth_url=default_swift_url): self.conf = config.get_client_settings_config_file() self.swift_username = swift_username self.sl_client = sl.create_client_from_env() self.images = sl.ImageManager(self.sl_client) self.servers = sl.VSManager(self.sl_client) self.swift = client.Connection(authurl=swift_auth_url, user=swift_username, key=self.conf['api_key'])
def __init__(self, username: str, api_key: str): assert (username and api_key), "'SoftLayerManager' must have username and api_key" self.username = username self.api_key = decrypt_api_key(api_key) self.client = SoftLayer.create_client_from_env(self.username, self.api_key) self.fetch_ops = FetchOperations(self.client, self.username) self.create_ops = CreateOperations(self.client, self.username)
def connect(self, access, authentication_data, region) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" _username, _api_key, _api_type = authentication_data.split('-') if access.lower().count("private") : self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT) else : self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT) _resp = self.slconn.call('Account', 'getObject') _regions = SoftLayer.MessagingManager(self.slconn).get_endpoints() _region = region if region in _regions : if access.lower() in _regions[region] : _region = _regions[region][access.lower()] _msg = "Selected region is " + str(region) + " (" + _region + ")" if _api_type.lower().count("baremetal") : self.nodeman = SoftLayer.HardwareManager(self.slconn) else : self.nodeman = SoftLayer.VSManager(self.slconn) self.sshman = SoftLayer.SshKeyManager(self.slconn) self.imageman = SoftLayer.ImageManager(self.slconn) _status = 0 except Exception, msg : _fmsg = str(msg) _status = 23
def connect(self, access, authentication_data, region): ''' TBD ''' try: _status = 100 _fmsg = "An error has occurred, but no error message was captured" _username, _api_key, _api_type = authentication_data.split('-') if access.lower().count("private"): self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT) else: self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \ api_key= _api_key.strip(), \ endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT) _resp = self.slconn.call('Account', 'getObject') _regions = SoftLayer.MessagingManager(self.slconn).get_endpoints() _region = region if region in _regions: if access.lower() in _regions[region]: _region = _regions[region][access.lower()] _msg = "Selected region is " + str(region) + " (" + _region + ")" if _api_type.lower().count("baremetal"): self.nodeman = SoftLayer.HardwareManager(self.slconn) else: self.nodeman = SoftLayer.VSManager(self.slconn) self.sshman = SoftLayer.SshKeyManager(self.slconn) self.imageman = SoftLayer.ImageManager(self.slconn) _status = 0 except Exception, msg: _fmsg = str(msg) _status = 23
def login(sl_username, sl_api_key): """ Logs into SoftLayer, instantiating the long-lived client objects. This can either be called directly or you can rely on the ensure_clients decorator if the credentials are passed via environment variables or files. """ global client, dns_manager, network_manager logger.info('Creating SoftLayer client objects') client = SoftLayer.create_client_from_env(username=sl_username, api_key=sl_api_key) dns_manager = SoftLayer.managers.dns.DNSManager(client) network_manager = SoftLayer.managers.network.NetworkManager(client)
def _connect(dry_run=False): """Connect to SoftLayer service :param dry_run: don't do anything """ log.msg("Connecting to SoftLayer service ...") _sl_client = None if not dry_run: _sl_client = SoftLayer.create_client_from_env() log.msg("Connection to SoftLayer succesful!", bold=True) return _sl_client
def account_list(request): loginname = None if request.user.is_authenticated(): loginname = request.user.username username = CustomUser.objects.get(username=loginname) # pk = username.softlayer_id user = softlayer_api.objects.get(pk=username.softlayer_id) client = SoftLayer.create_client_from_env(username=user.username, api_key=user.api_key) acct = client['Account'].getUsers() # return HttpResponse(acct) return render_to_response('account_list.html', {'accounts': acct}, context_instance=RequestContext(request))
def __init__(self, config): super(Provider, self).__init__(config) self.domain_id = None username = self._get_provider_option('auth_username') api_key = self._get_provider_option('auth_api_key') if not username or not api_key: raise Exception("No username and/or api key was specified") sl_client = SoftLayer.create_client_from_env(username=username, api_key=api_key) self.sl_dns = SoftLayer.managers.dns.DNSManager(sl_client)
def __init__(self, options, engine_overrides=None): super(Provider, self).__init__(options, engine_overrides) self.domain_id = None username = self.options.get('auth_username') api_key = self.options.get('auth_api_key') if not username or not api_key: raise Exception("No username and/or api key was specified") sl_client = SoftLayer.create_client_from_env(username=username, api_key=api_key) self.sl_dns = SoftLayer.managers.dns.DNSManager(sl_client)
def main(): client = SoftLayer.create_client_from_env() vsmgr = SoftLayer.VSManager(client) insts = vsmgr.list_instances() hosts = {} for inst in insts: pbip = inst['primaryBackendIpAddress'].ljust(24) fqdn = inst['fullyQualifiedDomainName'].rjust(32) host = inst['hostname'].rjust(16) print(' ' + pbip + ' ' + fqdn + ' ' + host)
def __init__(self): self.parse_options() self.set_column() if self.args.sort not in self.Titles: print( 'The SORT value is invalid. It must exactly match the item title.' ) return client = SoftLayer.create_client_from_env() self.accountClient = client['SoftLayer_Account'] self.list_servers()
def run(self, search): """Entry point for the search. Iterate over VM's records.""" import SoftLayer client = SoftLayer.create_client_from_env( username=self.softalyer_username, api_key=self.softalyer_api_key) mgr = SoftLayer.VSManager(client) vsi = mgr.list_instances() for vs in vsi: if re.search(search, vs['hostname']): yield { 'Name': vs['hostname'], 'Data Center': vs['datacenter']['longName'] }
def main(): # Create a dummy AnsibleModule instance for the sole purpose of returning fail_json pre_pre_mod = AnsibleModule( argument_spec={}, bypass_checks=True, supports_check_mode=True, check_invalid_arguments=False ) if not HAS_SL: pre_pre_mod.fail_json(msg='softlayer python library required for this module') try: client = SoftLayer.create_client_from_env() sld = SL_data(client) except SoftLayer.exceptions.SoftLayerAPIError, e: # First use of the SoftLayer client should expose authenticaion and other connection issues pre_pre_mod.fail_json(msg=str(e))
def main(): '''fetch the primary ip addresses''' client = SoftLayer.create_client_from_env() vsmgr = SoftLayer.VSManager(client) insts = vsmgr.list_instances() print('[all]') for inst in insts: print(inst['primaryIpAddress']) print('') for inst in insts: host = inst['hostname'].replace('.', '') print('[' host + ']') print(inst['primaryIpAddress']) print('')
def client(): """Create SoftLayer client :return: The SoftLayer client """ cfg = params() endpoint_url = "https://{}/rest/v3.1/".format(constants.SL_URL) try: client = SoftLayer.create_client_from_env( username=cfg['cis_username'], api_key=cfg['cis_apikey'], endpoint_url=endpoint_url, ) return client except SoftLayer.SoftLayerError as error: print("Error creating SoftLayer client. {}".format(error)) raise
def main(wf): # Get args from Workflow as normalized Unicode args = wf.args # Do stuff here ... account_alias = args[0].split(' ')[0] username = wf.settings.get(account_alias) apikey = wf.get_password(username) command = ' '.join(args[0].split(' ')[1:]) if command == 'list': sl_client = SoftLayer.create_client_from_env(username=username, api_key=apikey) hw_mgr = SoftLayer.HardwareManager(sl_client) for hw in hw_mgr.list_hardware(): wf.add_item(title='%s' % hw['fullyQualifiedDomainName'], subtitle='IP: %s/%s, CPU: %s cores, Mem: %s GB, ' % (hw['primaryIpAddress'], hw['primaryBackendIpAddress'], hw['processorPhysicalCoreAmount'], hw['memoryCapacity']), valid=True) wf.send_feedback()
def main(): client = SoftLayer.create_client_from_env() vsmgr = SoftLayer.VSManager(client) insts = vsmgr.list_instances() hosts = {} for i in insts: ip = i['primaryIpAddress'] host = i['hostname'].upper().replace('.', '').replace('-', '') print('export ' + host + '=' + ip) print('clear') print('') print('') for i in insts: host = i['hostname'].upper().replace('.', '').replace('-', '') print('ssh -i ~/.ssh/fabric fabric@$' + host)
def main(wf): # Get args from Workflow as normalized Unicode args = wf.args # Do stuff here ... account_alias = args[0].split(' ')[0] username = wf.settings.get(account_alias) apikey = wf.get_password(username) sl_client = SoftLayer.create_client_from_env(username=username, api_key=apikey) ticket_id = ' '.join(args[0].split(' ')[1:]) updates = sl_client['Ticket'].getUpdates(id=ticket_id) updates.reverse() for update in updates: wf.add_item(title=update['entry'], subtitle='%s: %s (%s)%s' % (update['createDate'], update['ticketId'], update['editorType'], update['editorId']), arg="Update on %s:\n %s" % (update['createDate'], update['entry']), valid=True) wf.send_feedback()
def main(): args = docopt(__doc__, version='kleiber cluster director 0.1') try: configuration = yaml.load( open(os.environ['HOME'] + '/.kleiber', 'r').read()) except IOError: error('kleiber configuration file {} not found'.format( os.environ['HOME'] + '/.kleiber')) client = SoftLayer.create_client_from_env( username=configuration['username'], api_key=configuration['api_key']) if 'obj_store' not in configuration: if 'local_store' in configuration: directory = configuration['local_store'] else: directory = os.path.expanduser("~/.kleiber-data") sl_storage = { 'type': 'local', 'directory': os.path.expanduser(directory + "/containers/") } else: sl_storage = { 'type': 'swift', 'client': object_storage.get_client( configuration['obj_store']['name'] + ':' + configuration['username'], configuration['api_key'], datacenter=configuration['obj_store']['datacenter']) } if args['create']: do_create(args, client, sl_storage, configuration) elif args['status']: do_status(args, client, sl_storage, configuration) elif args['delete']: do_delete(args, client, sl_storage, configuration) elif args['list']: print clusters(sl_storage)
def cli(env, format='table', config=None, debug=0, verbose=0, proxy=None, really=False, fixtures=False, **kwargs): """Main click CLI entry-point.""" # Set logging level if debug is not None: verbose = int(debug) if verbose: logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG)) # Populate environement with client and set it as the context object env.skip_confirmations = really env.config_file = config env.format = format if env.client is None: # Environment can be passed in explicitly. This is used for testing if fixtures: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config, ) env.client = client env.vars['timings'] = SoftLayer.TimingTransport(env.client.transport) env.client.transport = env.vars['timings']
def ensure_client(self, config_file=None, is_demo=False, proxy=None): """Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment. """ if self.client is not None: return # Environment can be passed in explicitly. This is used for testing if is_demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config_file, ) self.client = client
def get_ibmcloud_client( username: str, password: str, ): """ Return the client that can interact with the OpenStack cloud. Args: username: The name of the user to be set for the session. password: The password of the provided user. auth_url: The endpoint that can authenticate the user. auth_version: The API version to be used for authentication. tenant_name: The name of the user's project. tenant_domain_id: The ID of the user's project. service_region: The realm to be used. domain_name: The authentication domain to be used. api_version: The API Version to be used for communication. """ ibm_client = SoftLayer.create_client_from_env(username=username, api_key=password) return ibm_client
def main(dict): API_USERNAME = dict['user'] API_KEY = dict['apikey'] POWER = dict['power'] VSI = dict['vsi'] client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY) try: virtualGuests = client['SoftLayer_Account'].getVirtualGuests() except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve virtual guest. " % (e.faultCode, e.faultString)) vsiFound = False for virtualGuest in virtualGuests: if virtualGuest['hostname'] == VSI: vsiFound = True try: if POWER == 'OFF': virtualMachines = client[ 'SoftLayer_Virtual_Guest'].powerOff( id=virtualGuest['id']) else: virtualMachines = client[ 'SoftLayer_Virtual_Guest'].powerOn( id=virtualGuest['id']) except SoftLayer.SoftLayerAPIError as e: vsiFound = e return { 'VSI': VSI, 'Action': POWER, 'Action_Performed': vsiFound, 'result': virtualMachines }
def main(): args = docopt(__doc__, version='kleiber cluster director 0.1') try: configuration = yaml.load( open(os.environ['HOME']+'/.kleiber', 'r').read()) except IOError: error('kleiber configuration file {} not found'.format( os.environ['HOME']+'/.kleiber')) client = SoftLayer.create_client_from_env( username=configuration['username'], api_key=configuration['api_key']) if 'obj_store' not in configuration: if 'local_store' in configuration: directory = configuration['local_store'] else: directory = os.path.expanduser("~/.kleiber-data") sl_storage = { 'type': 'local', 'directory': os.path.expanduser(directory+"/containers/") } else: sl_storage = { 'type': 'swift', 'client': object_storage.get_client( configuration['obj_store']['name']+':'+configuration['username'], configuration['api_key'], datacenter=configuration['obj_store']['datacenter']) } if args['create']: do_create(args, client, sl_storage, configuration) elif args['status']: do_status(args, client, sl_storage, configuration) elif args['delete']: do_delete(args, client, sl_storage, configuration) elif args['list']: print clusters(sl_storage)
def main(wf): # Get args from Workflow as normalized Unicode args = wf.args # Do stuff here ... account_alias = args[0].split(' ')[0] username = wf.settings.get(account_alias) apikey = wf.get_password(username) command = ' '.join(args[0].split(' ')[1:]) if command == 'list': sl_client = SoftLayer.create_client_from_env(username=username, api_key=apikey) hw_mgr = SoftLayer.HardwareManager(sl_client) for hw in hw_mgr.list_hardware(): wf.add_item( title='%s' % hw['fullyQualifiedDomainName'], subtitle='IP: %s/%s, CPU: %s cores, Mem: %s GB, ' % (hw['primaryIpAddress'], hw['primaryBackendIpAddress'], hw['processorPhysicalCoreAmount'], hw['memoryCapacity']), valid=True) wf.send_feedback()
def cli(env, format='table', config=None, verbose=0, proxy=None, really=False, demo=False, **kwargs): """Main click CLI entry-point.""" if verbose > 0: logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG)) # Populate environement with client and set it as the context object env.skip_confirmations = really env.config_file = config env.format = format if env.client is None: # Environment can be passed in explicitly. This is used for testing if demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config, ) env.client = client env.vars['_start'] = time.time() env.vars['_timings'] = SoftLayer.TimingTransport(env.client.transport) env.client.transport = env.vars['_timings']
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 __init__(self): self.client = SoftLayer.create_client_from_env()
#!/usr/bin/python import SoftLayer #increase default timeout to reduce false failure #on slow or conjested connections client = SoftLayer.create_client_from_env(timeout=240) import pprint pp = pprint.PrettyPrinter(indent=4) out = client['Product_Package'].getLocations(id=*) pp.pprint(out) #client['Account'].getActivePackages( #client = SoftLayer.Client(username=myuser, api_key=mykey, endpoint_url=SoftLayer.API_PUBLIC_ENDPOINT) import pprint #https://forums.softlayer.com/forum/softlayer-developer-network/general-discussion/80475-provision-bare-metal-instance-via-rest-api #We have a "generic" order container, which is the SoftLayer_Container_Product_Order; #by specifying the correct package ID and prices on it, it can be used to place orders for CCIs (virtual guests), #Bare Metals and/or regular dedicated servers (even mixed on the same order!). #http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder #define a valid order "container?" order = { 'orderContainers': [ {
License: http://sldn.softlayer.com/article/License Author: SoftLayer Technologies, Inc. <*****@*****.**> """ # So we can talk to the SoftLayer API: import SoftLayer # For nice debug output: from pprint import pprint as pp # Your SoftLayer API username and key. API_USERNAME = '******' # Generate one at https://control.softlayer.com/account/users API_KEY = 'set me' # Set the server id in order to activate the network port.. serverId = 35747489 # Set up your API client client = SoftLayer.create_client_from_env( username=API_USERNAME, api_key=API_KEY ) try: # The expected result after executing the script is: true result = client['Virtual_Guest'].activatePrivatePort(id=serverId) pp(result) except SoftLayer.SoftLayerAPIError as e: pp('Unable to activate the private port faultCode=%s, faultString=%s' % (e.faultCode, e.faultString))
def __init__(self): self.cfg = params() self.client = SoftLayer.create_client_from_env( username=self.cfg['cis_username'], api_key=self.cfg['cis_apikey']) self.dns = SoftLayer.DNSManager(self.client)
SL_USERNAME = '' SL_API_KEY = '' USER = '' SSH_KEY = '' DATACENTER = 'ams01' hosts = ['host1', 'host2', 'host3'] class PrettyLog(): def __init__(self, obj): self.obj = obj def __repr__(self): return pprint.pformat(self.obj) client = SoftLayer.create_client_from_env(username=SL_USERNAME, api_key=SL_API_KEY) vs = SoftLayer.VSManager(client) km = SoftLayer.SshKeyManager(client) def add_key(sshkey, user): logging.info('Adding sshkey for user {}'.format(user)) try: key = km.add_key(key=sshkey, label=user) logging.info(key) return key except SoftLayer.SoftLayerAPIError as e: logging.warning(e) keys = km.list_keys(label=user) if len(keys) > 0: return keys[0] return None
parser.add_argument('--filter-username', action='store_true', dest='usernameFilter', help='Filter by username [default: false]') parser.add_argument('--filter-kube-node', action='store_true', dest='kubenodeFilter', help='Filter kube nodes [default: false]') parser.add_argument('--filter-cpi', action='store_true', dest='cpiFilter', help='Filter CPI provisioned [default: false]') parser.add_argument('--filter-staging', action='store_true', dest='stagingFilter', help='filter staging deployments [default: false]') args = parser.parse_args() client = SoftLayer.create_client_from_env(username=args.username, api_key=args.apikey) mask = ['accountId', 'createDate', 'domain', 'hostname', 'id', 'modifyDate', 'billingItem.orderItem.order.userRecord.username', # like 'billingItem.orderItem.order.userRecord.email', 'tagReferences.tag.name', ] whitelist = ['accountmanagement', 'app-autoscaler', 'bssqradar', 'concourse-softlayer', 'logstash-forwarder-test', 'marmot-agents', 'mccp', 'provisioning-broker', 'whisk-yz-stage0', 'whisk-yz-stage0-two',
def conn_obj(): client = SoftLayer.create_client_from_env(timeout=240) return client
for subnet in vlan_nfo["subnets"]: if (subnet["subnetType"] == "PRIMARY" and subnet["addressSpace"] == "PRIVATE"): return subnet #Adds a number to the last octet of an IP def add_num_to_ip(ip, num): ip_split = ip.split('.') ip_split[-1] = str(int(ip_split[-1]) + num) return '.'.join(ip_split) hardware_mask = "id, hostname, primaryBackendIpAddress, operatingSystem, networkVlans, networkComponents" machine_add_constant = 10 client = SoftLayer.create_client_from_env(username=userinfo.user, api_key=userinfo.api_key) hardware_mgr = SoftLayer.HardwareManager(client) net_mgr = SoftLayer.NetworkManager(client) machines = init_machines_with_ids(hardware_mgr) output = open('output.txt', 'w+') num_machines_identified = 0 for machine_id in machines: machine_info = hardware_mgr.get_hardware(hardware_id=machine_id, mask=hardware_mask) private_vlan_id = get_private_vlan_id(machine_info) vlan_info = net_mgr.get_vlan(vlan_id=private_vlan_id) private_portable_subnet_info = get_private_portable_subnet(vlan_info) private_primary_subnet_info = get_private_primary_subnet(vlan_info) private_portable = private_portable_subnet_info["networkIdentifier"]
#!/usr/bin/python import argparse import string import SoftLayer import json USER = '******' KEY = 'your_apiKey' if __name__ == '__main__': client = SoftLayer.create_client_from_env(username=USER, api_key=KEY) mask = ['id,fullyQualifiedDomainName,billingItem[id,orderItem[id,order[userRecord[id,username]]]]', ] fil = { 'virtualGuests': { 'hostname': { 'operation': '*= hostname_contains' }, 'billingItem': { 'orderItem': { 'order': { 'userRecord': { 'username': { 'operation': 'who_is_you' }, }, }, }, },
#TODO: get this info from API STATES = ['present', 'absent'] DATACENTERS = ['ams01','ams03','che01','dal01','dal05','dal06','dal09','dal10','fra02','hkg02','hou02','lon02','mel01','mex01','mil01','mon01','osl01','par01','sjc01','sjc03','sao01','sea01','sng01','syd01','tok02','tor01','wdc01','wdc04'] CPU_SIZES = [1,2,4,8,16,32,56] MEMORY_SIZES = [1024,2048,4096,6144,8192,12288,16384,32768,49152,65536,131072,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
# Values "AMS01", "AMS03", "CHE01", "DAL05", "DAL06" "FRA02", "HKG02", "LON02", etc. location = "AMS01" # Values "20", "40", "80", "100", etc. storageSize = "40" # Values between "100" and "6000" by intervals of 100. iops = "100" # Values "Hyper-V", "Linux", "VMWare", "Windows 2008+", "Windows GPT", "Windows 2003", "Xen" os = "Linux" PACKAGE_ID = 222 client = SoftLayer.create_client_from_env() productOrderService = client['SoftLayer_Product_Order'] packageService = client['SoftLayer_Product_Package'] locationService = client['SoftLayer_Location'] osService = client['SoftLayer_Network_Storage_Iscsi_OS_Type'] objectFilterDatacenter = {"name": {"operation": location.lower()}} objectFilterStorageNfs = {"items": {"categories": {"categoryCode": {"operation": "performance_storage_iscsi"}}}} objectFilterOsType = {"name": {"operation": os}} try: # Getting the datacenter. datacenter = locationService.getDatacenters(filter=objectFilterDatacenter) # Getting the performance storage NFS prices. itemsStorageNfs = packageService.getItems(id=PACKAGE_ID, filter=objectFilterStorageNfs) # Getting the storage space prices
import os import sys import SoftLayer import click import requests import json import string import random from prettytable import PrettyTable from requests import ConnectionError, Timeout SOFTLAYER_USER = os.getenv('SOFTLAYER_USER') SOFTLAYER_API_KEY = os.getenv('SOFTLAYER_API_KEY') _client = SoftLayer.create_client_from_env( username=SOFTLAYER_USER, api_key=SOFTLAYER_API_KEY) # Default virtual machine settings VM_SETTINGS = { 'cpus': 1, 'memory': 4096, 'hourly': True, 'os_code': 'UBUNTU_LATEST_64', 'nic_speed': 100, 'datacenter': 'wdc01', 'post_uri': 'https://raw.githubusercontent.com/jupyter-resources/tutorial-dashboards-declarativewidgets/master/setup/post-install.sh', } @click.group() @click.option('--tags', default='pydata2016',