def initializeSoftLayerAPI(): ## READ CommandLine Arguments and load configuration file parser = argparse.ArgumentParser( description= "This script is used to untrunk existing VLANs from a host. This is often used to associate VLANs to a hypervisor host." ) parser.add_argument("-u", "--username", help="SoftLayer API Username") parser.add_argument("-k", "--apikey", help="SoftLayer APIKEY") parser.add_argument("-c", "--config", help="config.ini file to load") args = parser.parse_args() if args.config != None: filename = args.config else: filename = "config.ini" if (os.path.isfile(filename) is True) and (args.username == None and args.apikey == None): ## Read APIKEY from configuration file config = configparser.ConfigParser() config.read(filename) client = SoftLayer.Client(username=config['api']['username'], api_key=config['api']['apikey']) else: ## Read APIKEY from commandline arguments if args.username == None and args.apikey == None: print("You must specify a username and APIkey to use.") quit() if args.username == None: print("You must specify a username with your APIKEY.") quit() if args.apikey == None: print("You must specify a APIKEY with the username.") quit() client = SoftLayer.Client(username=args.username, api_key=args.apikey) return client
def initializeSoftLayerAPI(): ## READ CommandLine Arguments and load configuration file parser = argparse.ArgumentParser( description= "Configuration Report prints details of BareMetal Servers such as Network, VLAN, and hardware configuration" ) parser.add_argument("-u", "--username", help="SoftLayer API Username") parser.add_argument("-k", "--apikey", help="SoftLayer APIKEY") parser.add_argument("-c", "--config", help="config.ini file to load") args = parser.parse_args() if args.config != None: filename = args.config else: filename = "config.ini" if (os.path.isfile(filename) is True) and (args.username == None and args.apikey == None): ## Read APIKEY from configuration file config = configparser.ConfigParser() config.read(filename) client = SoftLayer.Client(username=config['api']['username'], api_key=config['api']['apikey']) else: ## Read APIKEY from commandline arguments if args.username == None and args.apikey == None: print("You must specify a username and APIkey to use.") quit() if args.username == None: print("You must specify a username with your APIKEY.") quit() if args.apikey == None: print("You must specify a APIKEY with the username.") quit() client = SoftLayer.Client(username=args.username, api_key=args.apikey) return client
def setUp(self): # NOQA super(TestCase, self).setUp() self.env = environment.Environment() # Create a crazy mockable, fixture client auth = SoftLayer.BasicAuthentication('default-user', 'default-key') self.mocks = MockableTransport(SoftLayer.FixtureTransport()) self.transport = SoftLayer.TimingTransport(self.mocks) self.client = SoftLayer.Client(transport=self.transport, auth=auth, timeout=10, endpoint_url='default-endpoint-url') self.env.client = self.client return self.set_up()
def get_conn(service='SoftLayer_Virtual_Guest'): ''' Return a conn object for the passed VM data ''' client = SoftLayer.Client( username=config.get_cloud_config_value('user', get_configured_provider(), __opts__, search_global=False), api_key=config.get_cloud_config_value('apikey', get_configured_provider(), __opts__, search_global=False), ) return client[service]
def get_conn(service="SoftLayer_Hardware"): """ Return a conn object for the passed VM data """ client = SoftLayer.Client( username=config.get_cloud_config_value("user", get_configured_provider(), __opts__, search_global=False), api_key=config.get_cloud_config_value("apikey", get_configured_provider(), __opts__, search_global=False), ) return client[service]
def test_service_does_not_exist(self): creds = self._get_creds() client = SoftLayer.Client(username=creds['username'], api_key=creds['api_key'], endpoint_url=creds['endpoint'], timeout=20) try: client["SoftLayer_DOESNOTEXIST"].getObject() except SoftLayer.SoftLayerAPIError as e: self.assertEqual(e.faultCode, '-32601') self.assertEqual(e.faultString, 'Service does not exist') self.assertEqual(e.reason, 'Service does not exist') else: self.fail('No Exception Raised')
def ConnecttoDevice(request): username = '******' key = '8aad3f6cf9a4a7f189bd1019aea3bf725a425a9bfae4a06309896dcbfcdb8c05' client = SoftLayer.Client(username=username, api_key=key) try: # Getting all virtual guest that the account has: virtualGuests = client['SoftLayer_Account'].getVirtualGuests() except SoftLayer.SoftLayerAPIError as e: """ If there was an error returned from the SoftLayer API then bomb out with the error message. """ print("Unable to retrieve hardware. " % (e.faultCode, e.faultString)) return HttpResponse(virtualGuests)
def main(): module_helper = AnsibleModule( argument_spec=dict(SLClientConfig.arg_spec().items() + VSInstanceConfigBasic.arg_spec().items())) sl_client_config = SLClientConfig(module_helper.params) sl_client = SoftLayer.Client(username=sl_client_config.sl_username, api_key=sl_client_config.api_key) vs = CredentialsReader( sl_client, VSInstanceConfigBasic(ansible_config=module_helper.params)) try: module_helper.exit_json(changed=False, result=vs.read_credentials()) except Exception as se: module_helper.fail_json(changed=False, msg=str(se))
def api_login(): global account apikey() client = SoftLayer.Client(username=account["username"], api_key=account["api_key"]) try: object_mask = 'id,username,firstName,lastName' ret = client['Account'].getCurrentUser(mask=object_mask) print "Current User = %s " % ret['username'] except SoftLayer.SoftLayerAPIError as e: print("faultCode=%s, faultString=%s" % (e.faultCode, e.faultString)) return False return client
def __init__(self): self.inventory = {} # Ansible Inventory self.inventory['_meta'] = {} self.inventory['_meta']['hostvars'] = {} self.username = None self.apikey = None self.credsfile = None self.setup_creds() self.client = SoftLayer.Client(username=self.username, api_key=self.apikey) self.get_inventory() print json.dumps(self.inventory)
def validate_image(ibm_username, ibm_api_key, swift_username, swift_api_key, swift_cluster, container, name): client = SoftLayer.Client(username=ibm_username, api_key=ibm_api_key) vs_mgr = SoftLayer.managers.VSManager(client) image_mgr = SoftLayer.managers.ImageManager(client) image_tmpl = client['SoftLayer_Virtual_Guest_Block_Device_Template_Group'] locs = client['SoftLayer_Location_Datacenter'] images = image_mgr.list_private_images(name=name) image_changed = False image = None if len(images) == 1: image = images[0] else: (storage_url, auth_token) = \ authenticate_swift(swift_username, swift_api_key, swift_cluster) obj_uri = "swift://%s@%s/%s/%s" % ( swift_username[0:swift_username.find(':')], swift_cluster[0:swift_cluster.find('.')], container, name) image = image_tmpl.createFromExternalSource({ 'name': name, 'note': "F5 TMOS Image %s" % name, 'operatingSystemReferenceCode': 'CENTOS_7_64', 'cloudInit': True, 'uri': obj_uri }) time.sleep(10) image_changed = True available_dcs = \ locs.getDatacentersWithVirtualImageStoreServiceResourceRecord() image_dcs = image_tmpl.getObject(id=image['id'], mask='datacenters')['datacenters'] for dc in image_dcs: if dc in available_dcs: available_dcs.remove(dc) dcids = [] for dc in available_dcs: dcids.append({'id': dc['id']}) if len(dcids) > 0: print("adding image %s to %s" % (image['name'], available_dcs)) image_tmpl.addLocations(dcids, id=image['id']) image_changed = True return image_changed
def cli(env): """Setup the ~/.softlayer file with username and apikey. Set the username to 'apikey' for cloud.ibm.com accounts. """ username, secret, endpoint_url, timeout = get_user_input(env) new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout) api_key = get_api_key(new_client, username, secret) path = '~/.softlayer' if env.config_file: path = env.config_file config_path = os.path.expanduser(path) env.out(env.fmt(config.config_table({'username': username, 'api_key': api_key, 'endpoint_url': endpoint_url, 'timeout': timeout}))) if not formatting.confirm('Are you sure you want to write settings ' 'to "%s"?' % config_path, default=True): raise exceptions.CLIAbort('Aborted.') # Persist the config file. Read the target config file in before # setting the values to avoid clobbering settings parsed_config = utils.configparser.RawConfigParser() parsed_config.read(config_path) try: parsed_config.add_section('softlayer') except utils.configparser.DuplicateSectionError: pass parsed_config.set('softlayer', 'username', username) parsed_config.set('softlayer', 'api_key', api_key) parsed_config.set('softlayer', 'endpoint_url', endpoint_url) parsed_config.set('softlayer', 'timeout', timeout) config_fd = os.fdopen(os.open(config_path, (os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 0o600), 'w') try: parsed_config.write(config_fd) finally: config_fd.close() env.fout("Configuration Updated Successfully")
def main(): module_helper = AnsibleModule( argument_spec=dict(SLClientConfig.arg_spec().items() + SshKeysConfig.arg_spec().items())) sl_client_config = SLClientConfig(module_helper.params) sl_client = SoftLayer.Client(username=sl_client_config.sl_username, api_key=sl_client_config.api_key) try: ssh_keys = SshKeys(sl_client, SshKeysConfig(ansible_config=module_helper.params)) module_helper.exit_json(changed=ssh_keys.sync_config()) except Exception as se: module_helper.fail_json(msg=str(se))
def getCpuUsage(): # サービスに接続 client = SoftLayer.Client(username=user_id, api_key=api_key) cci = client['Virtual_Guest'].getCpuMetricDataByDate(id=server_id) size = len(cci) # 最近の1時間のCPU稼動状況 sum_sample = 0 num_sample = 0 for i in range(size - 3, size - 1): num_sample = num_sample + 1 sum_sample = sum_sample + int(cci[i]['counter']) ave_sample = sum_sample / num_sample ave_usage = ave_sample / 30.0 print "Last 1 hour CPU usage = ", ave_usage, "%" return ave_usage
def get_sl_servers(): # username, api_key, endpoint_url come from the .softlayer file client = SoftLayer.Client() mask = "hostname, fullyQualifiedDomainName, manufacturerSerialNumber, \ operatingSystem.id, operatingSystem.passwords.username, operatingSystem.passwords.password, \ remoteManagementAccounts.username, remoteManagementAccounts.password, remoteManagementComponent.ipmiIpAddress, \ primaryBackendNetworkComponent.primaryIpAddress, primaryBackendNetworkComponent.macAddress" # # If they specified hnmatch, it would be faster to have softlayer filter the response with something like: # filter={'hardware': {'hostname': {'operation': '*= '+hostname}, 'domain': {'operation': '*= '+domain}}} # But those 2 operations are ANDed together, so it will not work. And currently, filtering does not work on fullyQualifiedDomainName. # servers = client['Account'].getHardware(mask=mask) return servers
def hook_get_client(req, resp, kwargs): endpoint = config.PARSER.get('softlayer', 'endpoint') client = SoftLayer.Client(endpoint_url=endpoint) client.auth = None req.env['tenant_id'] = None if req.headers.get('X-AUTH-TOKEN'): if 'X-AUTH-TOKEN' in req.headers: tenant_id = kwargs.get('tenant_id', req.headers.get('X-AUTH-PROJECT-ID')) token_details = auth.get_token_details(req.headers['X-AUTH-TOKEN'], tenant_id=tenant_id) client.auth = auth.get_auth(token_details) req.env['tenant_id'] = token_details['tenant_id'] req.sl_client = client
def __init__(self): self.client = SoftLayer.Client() outputname = 'product_packages-oct2017.csv' fieldnames = [ 'Package ID', 'Package Name', 'Item ID', 'Description', 'KeyName', 'Price ID', 'PriceType', 'Hourly Fee', 'One Time Fee', 'Recurring Fee', 'Setup Fee', 'Usage Fee', 'Location Group', 'Locations' ] self.outfile = open(outputname, 'w') #self.csvwriter = csv.writer(self.outfile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) self.csvwriter = csv.DictWriter(self.outfile, delimiter=',', fieldnames=fieldnames, quoting=csv.QUOTE_MINIMAL) #self.csvwriter.writerow(dict((fn, fn) for fn in fieldnames)) self.csvwriter.writeheader()
def get_power_on(id,user,key): client = SoftLayer.Client(username=user, api_key=key) events = client['Event_Log'].getAllObjects(filter={'objectId': {'operation':id},'eventName': {'operation': 'Power On'}}) eventdate = datetime.now(pytz.UTC) powerOnDate = datetime.now(pytz.UTC) found=0 for event in events: if event['eventName']=="Power On": eventdate = event["eventCreateDate"] eventdate = eventdate[0:29]+eventdate[-2:] eventdate = datetime.strptime(eventdate, "%Y-%m-%dT%H:%M:%S.%f%z") if eventdate<powerOnDate: powerOnDate = eventdate found=1 if found==1: return jsonify({'powerOn':powerOnDate}) else: return jsonify({'powerOn':'notAvailable'})
def main(): module_helper = AnsibleModule( argument_spec=dict(SLClientConfig.arg_spec().items() + VSInstanceConfig.arg_spec().items())) sl_client_config = SLClientConfig(module_helper.params) sl_client = SoftLayer.Client(username=sl_client_config.sl_username, api_key=sl_client_config.api_key) vs = SoftlayerVirtualServer( sl_client, VSInstanceConfig(ansible_config=module_helper.params), module_helper.params.get("wait")) try: change_log = ChangeLog() result = vs.sync_config(change_log) result['change_log'] = change_log.to_dict() module_helper.exit_json(**result) except VSException as se: module_helper.fail_json(changed=se.changed(), msg=str(se))
def _fetch_softlayer_instances(): ''' Returns list of all DevEnv VMs running at SoftLayer. ''' client = SoftLayer.Client() manager = SoftLayer.VSManager(client) mask = "mask[id,operatingSystem[passwords],fullyQualifiedDomainName,primaryBackendIpAddress,maxCpu,maxMemory,datacenter,createDate,billingItem[id,nextInvoiceTotalRecurringAmount,currentHourlyCharge,hoursUsed]]" results = [] now = datetime.datetime.now() for vm in manager.list_instances(mask=mask): result = {"provider": "softlayer"} result["hostname"] = vm.get("fullyQualifiedDomainName") result["ip"] = vm.get("primaryBackendIpAddress") result["specs"] = "%s CPU, %s MB RAM" % (vm.get("maxCpu"), vm.get("maxMemory")) result[ "state"] = "running" # TODO, if we ever support stop/start for SL total = float(vm.get("billingItem", {}).get("currentHourlyCharge", 0)) hours_used = float(vm.get("billingItem", {}).get("hoursUsed", 1)) result["cost_hr"] = total / hours_used create_date = datetime.datetime.strptime(vm.get("createDate"), "%Y-%m-%dT%H:%M:%S+00:00") age = now.replace(tzinfo=None) - create_date.replace(tzinfo=None) age_hours = (24 * age.days) + (age.seconds / 3600) result["cost_total"] = age_hours * result["cost_hr"] try: result["password"] = vm.get("operatingSystem").get( "passwords")[0].get('password') except: result["password"] = "******" if DOMAIN in result["hostname"]: results.append(result) return results
class Command(BaseCommand): help = "This command Load the All Customers" redington_client = SoftLayer.Client( username=settings.SOFTLAYER_MASTER_USERNAME, api_key=settings.SOFTLAYER_MASTER_APIKEY) vendor_object = object master_brand_id = 0 def handle(self, *args, **options): brand_details = self.redington_client['Account'].getOwnedBrands() self.master_brand_id = brand_details[0]['id'] accounts = self.redington_client['Brand'].getAllOwnedAccounts( id=self.master_brand_id) for account in accounts: print(account['companyName'] + '-' + str(account['id'])) self.stdout.write( self.style.SUCCESS('Successfully SoftLayer Customers Loaded')) def create_customer_portal(self): return True
def getPublicBandwidth(THRESHHOLD): client = SoftLayer.Client() theMask = "mask[outboundPublicBandwidthUsage]" result = client['SoftLayer_Account'].getHardware() f = open('public_outbound.csv', 'w') for server in result: serverInfo = client['SoftLayer_Hardware_Server'].getObject( id=server['id'], mask=theMask) pubout = float(serverInfo.get('outboundPublicBandwidthUsage', 0.0)) name = serverInfo['fullyQualifiedDomainName'] if pubout > THRESHHOLD: total_out.append(pubout) print(name + "," + str(pubout)) s = name + "," + str(pubout) + "\n" f.write(s) f.close()
def CreateInstanceFromTemplate(): # テンプレートイメージからの仮想サーバーの注文 # 環境にあわせて修正してね client = SoftLayer.Client(username=user_id, api_key=api_key) client['Virtual_Guest'].createObject({ 'hostname': 'reinforce', 'domain': 'mydomain.com', 'startCpus': 1, 'maxMemory': 1024, 'hourlyBillingFlag': 'true', "datacenter": { 'name': 'sjc01' }, 'blockDeviceTemplateGroup': { 'globalIdentifier': tmp_img }, 'sshKeys': [{ 'id': ssh_key }], 'localDiskFlag': 'true' })
def get_array_power_on(user,key): client = SoftLayer.Client(username=user, api_key=key) serverlist = request.get_json() responseArray={} for server in serverlist: events = client['Event_Log'].getAllObjects(filter={'objectId': {'operation':server['id']},'eventName': {'operation': 'Power On'}}) eventdate = datetime.now(pytz.UTC) powerOnDate = datetime.now(pytz.UTC) found=0 for event in events: if event['eventName']=="Power On": eventdate = event["eventCreateDate"] eventdate = eventdate[0:29]+eventdate[-2:] eventdate = datetime.strptime(eventdate, "%Y-%m-%dT%H:%M:%S.%f%z") if eventdate<powerOnDate: powerOnDate = eventdate found=1 if found==1: responseArray[server['id']]=powerOnDate else: responseArray[server['id']]='notAvailable' return jsonify(responseArray)
def authenticate(self, creds): """Performs faux authentication :param creds: The credentials in dict form as passed to the API in a request to authenticate and obtain a new token. Not used, but present for parent-class compatibility. """ endpoint = config.PARSER.get('softlayer', 'endpoint') proxy = config.PARSER.get('softlayer', 'proxy') default_user = config.PARSER.get('softlayer', 'noauth_user') default_api_key = config.PARSER.get('softlayer', 'noauth_api_key') client = SoftLayer.Client(username=default_user, api_key=default_api_key, endpoint_url=endpoint, proxy=proxy) user = client['Account'].getCurrentUser(mask=USER_MASK) return { 'user': user, 'credential': default_api_key, 'auth_type': 'api_key' }
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: transport = SoftLayer.FixtureTransport() else: # Create SL Client transport = SoftLayer.XmlRpcTransport() wrapped_transport = SoftLayer.TimingTransport(transport) env.client = SoftLayer.Client(proxy=proxy, config_file=config, transport=wrapped_transport)
#!/usr/bin/env python # coding:utf-8 """ ベアメタルのインストール・パッケージのリストを表示します。 環境変数を事前にセットしてください。 export SOFTLAYER_API_KEY=<API KEYをセット> export SOFTLAYER_USERNAME=<USER NAMEをセット> 環境変数は、IBM Cloud Infrastructure (旧SoftLayer カスタマーポータル) のメニューバーから Accout -> Users -> API KEY で参照できます。 """ import os import pprint import SoftLayer client = SoftLayer.Client() mask = 'id, name, description, type.keyName, items.id, items.description, items.categories.categoryCode' pkgs = client['Product_Package'].getAllObjects(mask=mask) for p in pkgs: for i in p['items']: for c in i['categories']: if c['categoryCode'] == 'server': if not 'server' in p: p['server'] = [] p['server'].append(i['description']) del p['items'] pprint.pprint(pkgs)
def __init__(self, path, fw): self.client = SoftLayer.Client() self.fw = SoftLayer.FirewallManager(self.client) self.path = path self.fw_type, self.fw_id = firewall.parse_id(fw)
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/findByIpAddress http://sldn.softlayer.com/article/object-masks License: http://sldn.softlayer.com/article/License Author: SoftLayer Technologies, Inc. <*****@*****.**> """ import SoftLayer import json vsiIp = "169.45.98.148" USERNAME = '******' API_KEY = 'set me' client = SoftLayer.Client(username=USERNAME, api_key=API_KEY) vsiService = client['SoftLayer_Virtual_Guest'] try: objectMask = "mask[monitoringRobot[id, robotStatus[name]], monitoringAgents[statusName, name, id], monitoringServiceEligibilityFlag, datacenter]" vsi = vsiService.findByIpAddress(vsiIp, mask=objectMask) if not vsi: print("There is no a vsi with the IP address: " + vsiIp) exit(1) status = {} status['monitoringRobotStatus'] = vsi['monitoringRobot'] status['agents'] = vsi['monitoringAgents'] print(json.dumps(status, sort_keys=True, indent=2, separators=(',', ': '))) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve the status: faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))
def get_all_servers(self): self.client = SoftLayer.Client() self.get_virtual_servers() self.get_physical_servers()