Example #1
0
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()
Example #3
0
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'])
            ))
Example #4
0
    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
Example #5
0
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
Example #6
0
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))
Example #7
0
    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(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(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()
Example #10
0
    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
Example #11
0
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)
Example #12
0
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']
 def set_up(self):
     self.object_storage = SoftLayer.ObjectStorageManager(self.client)
Example #14
0
 def execute(self, args):
     mgr = SoftLayer.NetworkManager(self.client)
     global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids,
                                       args.get('<identifier>'),
                                       name='global ip')
     mgr.assign_global_ip(global_ip_id, args['<target>'])
Example #15
0
 def set_up(self):
     self.metadata = SoftLayer.MetadataManager()
     self.url = '/'.join([
         consts.API_PRIVATE_ENDPOINT_REST.rstrip('/'),
         'SoftLayer_Resource_Metadata',
         'something.json'])
Example #16
0
 def test_raise_404_error(self, make_api_call):
     make_api_call.side_effect = SoftLayer.SoftLayerAPIError(404,
                                                             'faultString')
     r = self.metadata.make_request('something.json')
     self.assertEqual(r, None)
Example #17
0
env = ''
svc = ''
clu = ''
name = ''
extip = ''
region = ''

sfl_username = None
sfl_apikey = None
if 'SFL_USERNAME' in os.environ:
    sfl_username = os.environ['SFL_USERNAME']
if 'SFL_APIKEY' in os.environ:
    sfl_apikey = os.environ['SFL_APIKEY']

client = SoftLayer.Client(username=sfl_username,
                          api_key=sfl_apikey,
                          endpoint_url=SoftLayer.API_PRIVATE_ENDPOINT)

instid = client['Resource_Metadata'].getId()
tags = client['Resource_Metadata'].getTags()
region = client['Resource_Metadata'].getDatacenter()
extip = client['Resource_Metadata'].getPrimaryIpAddress()
name = client['Resource_Metadata'].getHostname()
fqdn = client['Resource_Metadata'].getFullyQualifiedDomainName()

for t in tags:
    if t.startswith(envtag + '_'):
        env = t
    elif t.startswith(svctag + '_'):
        svc = t
    elif t.startswith(clutag + '_'):
Example #18
0
#!/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': [
    {
Example #19
0
def cli(env, identifier, passwords=False, price=False):
    """Get details for a virtual server."""

    vsi = SoftLayer.VSManager(env.client)
    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    result = vsi.get_instance(vs_id)
    result = utils.NestedDict(result)
    local_disks = vsi.get_local_disks(vs_id)

    table_local_disks = get_local_storage_table(local_disks)

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier']])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row([
        'status',
        formatting.FormattedItem(result['status']['keyName'],
                                 result['status']['name'])
    ])
    table.add_row([
        'state',
        formatting.FormattedItem(
            utils.lookup(result, 'powerState', 'keyName'),
            utils.lookup(result, 'powerState', 'name'),
        )
    ])
    table.add_row(['active_transaction', formatting.active_txn(result)])
    table.add_row(
        ['datacenter', result['datacenter']['name'] or formatting.blank()])
    _cli_helper_dedicated_host(env, result, table)
    operating_system = utils.lookup(result, 'operatingSystem',
                                    'softwareLicense',
                                    'softwareDescription') or {}
    table.add_row(['os', operating_system.get('name', '-')])
    table.add_row(['os_version', operating_system.get('version', '-')])
    table.add_row(['cores', result['maxCpu']])
    table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])])
    table.add_row(['drives', table_local_disks])
    table.add_row(['public_ip', result.get('primaryIpAddress', '-')])
    table.add_row(['private_ip', result.get('primaryBackendIpAddress', '-')])
    table.add_row(['private_only', result['privateNetworkOnlyFlag']])
    table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
    table.add_row(['transient', result.get('transientGuestFlag', False)])
    table.add_row(['created', result['createDate']])
    table.add_row(['modified', result['modifyDate']])
    last_transaction = "{} ({})".format(
        utils.lookup(result, 'lastTransaction', 'transactionGroup', 'name'),
        utils.clean_time(utils.lookup(result, 'lastTransaction',
                                      'modifyDate')))

    table.add_row(['last_transaction', last_transaction])
    table.add_row(
        ['billing', 'Hourly' if result['hourlyBillingFlag'] else 'Monthly'])
    table.add_row([
        'preset',
        utils.lookup(result, 'billingItem', 'orderItem', 'preset', 'keyName')
        or '-'
    ])

    table.add_row(_get_owner_row(result))
    table.add_row(_get_vlan_table(result))

    bandwidth = vsi.get_bandwidth_allocation(vs_id)
    table.add_row(['Bandwidth', _bw_table(bandwidth)])

    security_table = _get_security_table(result)
    if security_table is not None:
        table.add_row(['security_groups', security_table])

    table.add_row(['notes', result.get('notes', '-')])

    if price:
        total_price = utils.lookup(result, 'billingItem',
                                   'nextInvoiceTotalRecurringAmount') or 0
        total_price += sum(
            p['nextInvoiceTotalRecurringAmount']
            for p in utils.lookup(result, 'billingItem', 'children') or [])
        table.add_row(['price_rate', total_price])

    if passwords:
        pass_table = formatting.Table(['software', 'username', 'password'])

        for component in result['softwareComponents']:
            for item in component['passwords']:
                pass_table.add_row([
                    utils.lookup(component, 'softwareLicense',
                                 'softwareDescription', 'name'),
                    item['username'],
                    item['password'],
                ])

        table.add_row(['users', pass_table])

    table.add_row(['tags', formatting.tags(result['tagReferences'])])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = env.client.call(
                'Virtual_Guest',
                'getReverseDomainRecords',
                id=vs_id,
            )

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    env.fout(table)
Example #20
0
 def set_up(self):
     self.client = mock.MagicMock()
     self.vs = SoftLayer.VSManager(self.client)
     self.guestObject = self.client['Virtual_Guest'].getObject
Example #21
0
 def set_up(self):
     self.ticket = SoftLayer.TicketManager(self.client)
#!/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'
                            },
                        },
                    },
                },
            },
Example #23
0
def set_SL_client(req, operation=OP_CODE['GOOD_PATH']['SIMPLE']):
    if operation == OP_CODE['GOOD_PATH']['SIMPLE']:
        # simple good path testing, use default sl_client
        return
    elif operation == OP_CODE['BAD_PATH']['VIRT_DISK_IMG_OBJ_INVALID']:
        # Virtual_Disk_Image.getObject failure.
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(
                side_effect=SoftLayer.SoftLayerAPIError(400,
                                                        "MockFault",
                                                        None))
    elif operation == OP_CODE['BAD_PATH']['GET_VIRT_DISK_IMGS_API']:
        # getVirtualDiskImages() SLAPI failure
        setattr(
            req.sl_client['Account'], 'getVirtualDiskImages',
            mock.MagicMock(side_effect=SoftLayer.SoftLayerAPIError(
                400, "MockFault", None)))
    elif operation == OP_CODE['GOOD_PATH']['RET_VIRT_DISK_IMGS']:

        def _return_disk_imgs(*args, **kwargs):
            return [
                # This will not be returned because it's a local disk.
                {
                    'typeId': volumes.VIRTUAL_DISK_IMAGE_TYPE['SYSTEM'],
                    'blockDevices': [mock.MagicMock()],
                    'localDiskFlag': True,
                },
                # This will not be returned because it's not a system disk
                # image.
                {
                    'typeId': volumes.VIRTUAL_DISK_IMAGE_TYPE['SWAP'],
                    'blockDevices': [mock.MagicMock()],
                    'localDiskFlag': False,
                },
                # This will be the single volume returned since it's a
                # non-local system disk image.
                {
                    'typeId':
                    volumes.VIRTUAL_DISK_IMAGE_TYPE['SYSTEM'],
                    'localDiskFlag':
                    False,
                    'blockDevices': [{
                        'guestId': GUEST_ID,
                        'diskImageId': DISK_IMG_ID,
                        'device': BLKDEV_MOUNT_ID,
                    }],
                },
            ]

        setattr(req.sl_client['Account'], 'getVirtualDiskImages',
                mock.MagicMock(side_effect=_return_disk_imgs))
    elif operation == OP_CODE['GOOD_PATH']['RET_VIRT_DISK_IMG']:

        def _return_disk_img(*args, **kwargs):
            return {
                'typeId': volumes.VIRTUAL_DISK_IMAGE_TYPE['SYSTEM'],
                'blockDevices': [mock.MagicMock()],
                'localDiskFlag': False,
            }
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(side_effect=_return_disk_img)
    elif operation == OP_CODE['BAD_PATH']['RET_BAD_VIRT_GUEST']:

        def _return_disk_img_1(*args, **kwargs):
            return {
                'typeId':
                volumes.VIRTUAL_DISK_IMAGE_TYPE['SYSTEM'],
                'blockDevices': [{
                    'guestId': GUEST_ID,
                    'diskImageId': DISK_IMG_ID,
                    'device': BLKDEV_MOUNT_ID,
                }],
            }
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(side_effect=_return_disk_img_1)
        req.sl_client['Virtual_Guest'].getObject = \
            mock.MagicMock(
                side_effect=SoftLayer.SoftLayerAPIError(400,
                                                        "MockFault",
                                                        None))
    elif operation == OP_CODE['GOOD_PATH']['RET_VIRT_DISK_BILL']:

        def _return_billing_item(*args, **kwargs):
            return {'billingItem': mock.MagicMock()}
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(side_effect=_return_billing_item)
    elif operation == OP_CODE['BAD_PATH']['RET_VIRT_DISK_EXCP']:
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(
                side_effect=SoftLayer.SoftLayerAPIError(400,
                                                        "MockFault",
                                                        None))
    elif operation == OP_CODE['GOOD_PATH']['CREATE_VOLUME']:

        def _return_all_objects(*args, **kwargs):
            return [{
                'name': 'Portable Storage',
                'isActive': 1,
                'id': PROD_PKG_ID
            }]

        def _return_prices(*args, **kwargs):
            return [{
                'id': PROD_PKG_ID,
                'capacity': DISK_CAPACITY,
                'prices': [{
                    'id': PRICE_ID
                }]
            }]

        def _return_disk_img_2(*args, **kwargs):
            return {
                'typeId':
                volumes.VIRTUAL_DISK_IMAGE_TYPE['SYSTEM'],
                'blockDevices': [{
                    'guestId': GUEST_ID,
                    'diskImageId': DISK_IMG_ID,
                    'device': BLKDEV_MOUNT_ID,
                }],
            }

        req.sl_client['Product_Package'].getAllObjects = \
            mock.MagicMock(side_effect=_return_all_objects)
        req.sl_client['Product_Package'].getItems = \
            mock.MagicMock(side_effect=_return_prices)
        req.sl_client['Location_Datacenter'].getDatacenters = \
            mock.MagicMock(return_value=[{'name': DATACENTER_NAME,
                                         'id': DATACENTER_ID}])
        req.sl_client['Billing_Order'].getOrderTopLevelItems = \
            mock.MagicMock(
                return_value=[{'billingItem': {'resourceTableId':
                                               DISK_IMG_ID}}])
        req.sl_client['Virtual_Disk_Image'].getObject = \
            mock.MagicMock(side_effect=_return_disk_img_2)
        req.sl_client['Product_Order'].placeOrder = \
            mock.MagicMock(return_value={'orderId': ORDERID})
    ENDPOINT = "https://api.softlayer.com/rest/v3.1/"
else:
    print("Please respond with 'y' or 'N'")
#Ask the user for SL Username, API key and the ScanID
USERNAME = six.moves.input(
    "API Username: Not IBMid, from https://cloud.ibm.com/iam/apikeys :")
APIKEY = six.moves.input("API Key: from https://cloud.ibm.com/iam/apikeys :")

#For batch scan report exports, REPLACE the USERNAME & APIKEY lines found above
#with the lines below this requires only the SCANID to be inputted so no time is wasted
#USERNAME = '******'
#APIKEY = 'Enter API Key here from https://cloud.ibm.com/iam/apikeys'

#Create client
client = SoftLayer.create_client_from_env(username=USERNAME,
                                          api_key=APIKEY,
                                          endpoint_url=ENDPOINT)

#Find all Scans and grab a report
print("\n Here are all Nessus Scans for your account")
#listofscanids = client['Account'].getSecurityScanRequests(mask="mask[createDate, ipAddress, id, status[name]]")
#pp(listofscanids)

## Retrieve all requests and their status
object_mask = 'mask[createDate, ipAddress, id, status[name]]'

# Retrieve a list of requests and pull their object/status individually
requests = client['Account'].getSecurityScanRequests(mask='mask[id]')
for request in requests:
    request_object = client[
        'SoftLayer_Network_Security_Scanner_Request'].getObject(
Example #25
0
    1024, 2048, 4096, 6144, 8192, 12288, 16384, 32768, 49152, 65536
]
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)
    if (module.params.get('os_code') != 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
 def set_up(self):
     self.vs = SoftLayer.VSManager(self.client)
import SoftLayer
# client configuration
ENDPOINT = "http://stable.application.qadal0501.softlayer.local/v3/sldn/xmlrpc/"
# Your SoftLayer API username.
USERNAME = ''
# Generate one at https://manage.softlayer.com/Administrative/apiKeychain
API_KEY = 'apikey_goes_here'

# Declare the API client
client = SoftLayer.Client(endpoint_url=ENDPOINT,
                          username=USERNAME,
                          api_key=API_KEY)
#client = SoftLayer.Client(username=USERNAME,api_key=API_KEY)

templateObject = {
    "assignedUserId": 104672,
    "notifyUserOnUpdateFlag": True,
    "subjectId": 1522,
    "title": "ticket example"
}

contents = 'this the ticket contet'

attachedFiles = [{"data": "gICBdDQp9", "filename": "test2.txt"}]

attachID = 0
rootPassword = ""
controlPanelPassword = ""
accesPort = ""
attachedFiles = attachedFiles
Example #29
0
def cli(env, volume_id):
    """Display details for a specified volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume_id = helpers.resolve_id(block_manager.resolve_ids, volume_id,
                                         'Block Volume')
    block_volume = block_manager.get_block_volume_details(block_volume_id)
    block_volume = utils.NestedDict(block_volume)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
    table.add_row(['ID', block_volume['id']])
    table.add_row(['Username', block_volume['username']])
    table.add_row(['Type', storage_type])
    table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
    table.add_row(['LUN Id', "%s" % block_volume['lunId']])

    if block_volume.get('provisionedIops'):
        table.add_row(['IOPs', float(block_volume['provisionedIops'])])

    if block_volume.get('storageTierLevel'):
        table.add_row([
            'Endurance Tier',
            block_volume['storageTierLevel'],
        ])

    table.add_row([
        'Data Center',
        block_volume['serviceResource']['datacenter']['name'],
    ])
    table.add_row([
        'Target IP',
        block_volume['serviceResourceBackendIpAddress'],
    ])

    if block_volume['snapshotCapacityGb']:
        table.add_row([
            'Snapshot Capacity (GB)',
            block_volume['snapshotCapacityGb'],
        ])
        if 'snapshotSizeBytes' in block_volume['parentVolume']:
            table.add_row([
                'Snapshot Used (Bytes)',
                block_volume['parentVolume']['snapshotSizeBytes'],
            ])

    table.add_row([
        '# of Active Transactions',
        "%i" % block_volume['activeTransactionCount']
    ])

    if block_volume['activeTransactions']:
        for trans in block_volume['activeTransactions']:
            if 'transactionStatus' in trans and 'friendlyName' in trans[
                    'transactionStatus']:
                table.add_row([
                    'Ongoing Transaction',
                    trans['transactionStatus']['friendlyName']
                ])

    table.add_row([
        'Replicant Count',
        "%u" % block_volume.get('replicationPartnerCount', 0)
    ])

    if block_volume['replicationPartnerCount'] > 0:
        # This if/else temporarily handles a bug in which the SL API
        # returns a string or object for 'replicationStatus'; it seems that
        # the type is string for File volumes and object for Block volumes
        if 'message' in block_volume['replicationStatus']:
            table.add_row([
                'Replication Status',
                "%s" % block_volume['replicationStatus']['message']
            ])
        else:
            table.add_row([
                'Replication Status',
                "%s" % block_volume['replicationStatus']
            ])

        replicant_list = []
        for replicant in block_volume['replicationPartners']:
            replicant_table = formatting.Table(
                ['Replicant ID', replicant['id']])
            replicant_table.add_row(
                ['Volume Name',
                 utils.lookup(replicant, 'username')])
            replicant_table.add_row([
                'Target IP',
                utils.lookup(replicant, 'serviceResourceBackendIpAddress')
            ])
            replicant_table.add_row([
                'Data Center',
                utils.lookup(replicant, 'serviceResource', 'datacenter',
                             'name')
            ])
            replicant_table.add_row([
                'Schedule',
                utils.lookup(replicant, 'replicationSchedule', 'type',
                             'keyname')
            ])
            replicant_list.append(replicant_table)
        table.add_row(['Replicant Volumes', replicant_list])

    if block_volume.get('originalVolumeSize'):
        original_volume_info = formatting.Table(['Property', 'Value'])
        original_volume_info.add_row(
            ['Original Volume Size', block_volume['originalVolumeSize']])
        if block_volume.get('originalVolumeName'):
            original_volume_info.add_row(
                ['Original Volume Name', block_volume['originalVolumeName']])
        if block_volume.get('originalSnapshotName'):
            original_volume_info.add_row([
                'Original Snapshot Name', block_volume['originalSnapshotName']
            ])
        table.add_row(['Original Volume Properties', original_volume_info])

    notes = '{}'.format(block_volume.get('notes', ''))
    table.add_row(['Notes', notes])

    env.fout(table)
Example #30
0
import SoftLayer

# Your SoftLayer account credentials
USERNAME = ''
API_KEY = ''

# Connect to SoftLayer
client = SoftLayer.Client(username=USERNAME,
                          api_key=API_KEY,
                          endpoint_url=SoftLayer.API_PUBLIC_ENDPOINT)

# Search for bare metal servers that are reported to be down by the SL monitor
down_hardware = client['SoftLayer_Account'].getNetworkMonitorDownHardware()
for hw_obj in down_hardware:
    monitors = client['SoftLayer_Hardware'].getNetworkMonitors(id=hw_obj['id'])

    # Test whether this server's monitor is monitoring its public or private IP
    private_monitor = None
    public_monitor = None
    for monitor in monitors:
        if monitor['ipAddress'] == hw_obj['primaryIpAddress']:
            public_monitor = monitor.copy()
        elif monitor['ipAddress'] == hw_obj['privateIpAddress']:
            private_monitor = monitor.copy()

    # Reconfigure the monitor to use the private IP if necessary
    if private_monitor is None:
        if public_monitor is None:
            print "Host %s is flagged down by SL, has no public or private monitor!" % hw_obj[
                'fullyQualifiedDomainName']
        else:
 def set_up(self):
     self.dedicated_host = SoftLayer.DedicatedHostManager(self.client)
Example #32
0
 def set_up(self):
     self.metadata = SoftLayer.MetadataManager()
     self.make_request = mock.MagicMock()
     self.metadata.make_request = self.make_request
Example #33
0
 def set_up(self):
     self.ordering = SoftLayer.OrderingManager(self.client)
Example #34
0
 def test_raise_error(self, make_api_call):
     make_api_call.side_effect = SoftLayer.SoftLayerAPIError(
         'faultCode', 'faultString')
     self.assertRaises(
         SoftLayer.SoftLayerAPIError,
         self.metadata.make_request, 'something.json')
Example #35
0
@Author: SoftLayer Technologies, Inc. <*****@*****.**>
"""


# So we can talk to the SoftLayer API:
import SoftLayer

"""
 Your SoftLayer API username and key.
 Generate an API key at the SoftLayer Customer Portal
"""
API_USERNAME = '******'
API_KEY = 'set-me'

# Create a client instance to connect to the API service.
client = SoftLayer.Client(username=API_USERNAME, api_key=API_KEY)

# Set the password for the new user
userPassword = "******"

# Set the vpn password for the new user
vpnPassword = "******"
"""
userTemplate contains general information relating to a single SoftLayer customer portal user.
Personal information in this type such as names, addresses,
and phone numbers are not necessarily associated with the customer account the user is assigned to.
"""
userTemplateObject = {
    "address1": "315 Capitol Street",
    "city": "Dallas",
    "companyName": "company name",
Example #36
0
#!/usr/bin/env python
import pprint
import configparser

import SoftLayer
from SoftLayer import FileStorageManager
from sl.constants import convertstoragetoiops

config = configparser.ConfigParser()
config.read('softlayer.ini')

client = SoftLayer.create_client_from_env(
    username=config.get('General', 'username'),
    api_key=config.get('General', 'apikey'))

tfile = open('sl-file.psv', 'w')

SUBNETLU = {}
VDCS = {}
ALLVDCS = False

for vdc in config.items('VDCS'):
    if vdc[0].upper() == 'ALL':
        ALLVDCS = True
    else:
        VDCS[vdc[0].upper()] = True

for vdcn in config.items('VDCSUBNETID'):
    SUBNETLU[int(vdcn[1])] = vdcn[0].upper()

filem = FileStorageManager(client)
Example #37
0
def cli(env, size, datacenter):
    """Creates an iSCSI target."""

    iscsi_mgr = SoftLayer.ISCSIManager(env.client)
    iscsi_mgr.create_iscsi(size=size, location=datacenter)
Example #38
0
 def __init__(self, username=None, api_key=None):
     super(VirtualServerManager, self).__init__(
         SoftLayer.create_client_from_env(
             username=username, api_key=api_key))
Example #39
0
#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
Example #40
0
 def set_up(self):
     self.firewall = SoftLayer.FirewallManager(self.client)
Example #41
0
def conn_obj():
    client = SoftLayer.create_client_from_env(timeout=240)
    return client
Example #42
0
 ベアメタルにインストールできるOSイメージをリストします。

 location と pkgId を自身の環境に合わせて変更してください。

 location はデータセンターを表す記号です。 
   東京DC tok02

 pkgIdは、ベアメタルのパッケージの番号です。
   getBaremetalPkg.pyでリストできます。

 環境変数を事前にセットしてください。
   export SOFTLAYER_API_KEY=<API KEYをセット>
   export SOFTLAYER_USERNAME=<USER NAMEをセット>
   環境変数は、IBM Cloud Infrastructure (旧SoftLayer カスタマーポータル)
   のメニューバーから Accout -> Users -> API KEY で参照できます。
"""
import SoftLayer
import getOrderItemsDict as ItemsDict

client = SoftLayer.Client()
location = 'tok02'
pkgId = 551

items = ItemsDict.getOrderItemsDict(client, pkgId, location=location)
item = items['os']['items']
for key in item:

    # Ubuntu のみを選択表示
    #if key.startswith("OS_U"):
    print key, ",", item[key]['description'], ",", item[key]['priceId']
Example #43
0
    def test_init_with_ordering_manager(self):
        ordering_manager = SoftLayer.OrderingManager(self.client)
        mgr = SoftLayer.HardwareManager(self.client, ordering_manager)

        self.assertEqual(mgr.ordering_manager, ordering_manager)
Example #44
0
	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"]
Example #45
0
 def set_up(self):
     self.vs = SoftLayer.VSManager(self.client,
                                   SoftLayer.OrderingManager(self.client))
Example #46
0
def cli(env, **args):
    """Order/create virtual servers."""
    vsi = SoftLayer.VSManager(env.client)
    _validate_args(env, args)

    # Do not create a virtual server with test or export
    do_create = not (args['export'] or args['test'])

    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    data = _parse_create_args(env.client, args)

    output = []
    if args.get('test'):
        result = vsi.verify_create_instance(**data)

        if result['presetId']:
            ordering_mgr = SoftLayer.OrderingManager(env.client)
            item_prices = ordering_mgr.get_item_prices(result['packageId'])
            preset_prices = ordering_mgr.get_preset_prices(result['presetId'])
            search_keys = ["guest_core", "ram"]
            for price in preset_prices['prices']:
                if price['item']['itemCategory'][
                        'categoryCode'] in search_keys:
                    item_key_name = price['item']['keyName']
                    _add_item_prices(item_key_name, item_prices, result)

        table = _build_receipt_table(result['prices'], args.get('billing'))

        output.append(table)
        output.append(
            formatting.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')
        template.export_to_template(export_file,
                                    args,
                                    exclude=['wait', 'test'])
        env.fout('Successfully exported options to a template file.')

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

        result = vsi.create_instance(**data)

        table = formatting.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'], args.get('wait') or 1)
            table.add_row(['ready', ready])
            if ready is False:
                env.out(env.fmt(output))
                raise exceptions.CLIHalt(code=1)

    env.fout(output)
Example #47
0
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',
Example #48
0
def _parse_create_args(client, args):
    """Converts CLI arguments to args for VSManager.create_instance.

    :param dict args: CLI arguments
    """
    data = {
        "hourly": args.get('billing', 'hourly') == 'hourly',
        "domain": args['domain'],
        "hostname": args['hostname'],
        "private": args.get('private', None),
        "dedicated": args.get('dedicated', None),
        "disks": args['disk'],
        "cpus": args.get('cpu', None),
        "memory": args.get('memory', None),
        "flavor": args.get('flavor', None),
        "boot_mode": args.get('boot_mode', None)
    }

    # The primary disk is included in the flavor and the local_disk flag is not needed
    # Setting it to None prevents errors from the flag not matching the flavor
    if not args.get('san') and args.get('flavor'):
        data['local_disk'] = None
    else:
        data['local_disk'] = not args.get('san')

    if args.get('os'):
        data['os_code'] = args['os']

    if args.get('image'):
        if args.get('image').isdigit():
            image_mgr = SoftLayer.ImageManager(client)
            image_details = image_mgr.get_image(args.get('image'),
                                                mask="id,globalIdentifier")
            data['image_id'] = image_details['globalIdentifier']
        else:
            data['image_id'] = args['image']

    if args.get('datacenter'):
        data['datacenter'] = args['datacenter']

    if args.get('network'):
        data['nic_speed'] = args.get('network')

    if args.get('userdata'):
        data['userdata'] = args['userdata']
    elif args.get('userfile'):
        with open(args['userfile'], 'r') as userfile:
            data['userdata'] = userfile.read()

    if args.get('postinstall'):
        data['post_uri'] = args.get('postinstall')

    # Get the SSH keys
    if args.get('key'):
        keys = []
        for key in args.get('key'):
            resolver = SoftLayer.SshKeyManager(client).resolve_ids
            key_id = helpers.resolve_id(resolver, key, 'SshKey')
            keys.append(key_id)
        data['ssh_keys'] = keys

    if args.get('vlan_public'):
        data['public_vlan'] = args['vlan_public']

    if args.get('vlan_private'):
        data['private_vlan'] = args['vlan_private']

    data['public_subnet'] = args.get('subnet_public', None)

    data['private_subnet'] = args.get('subnet_private', None)

    if args.get('public_security_group'):
        pub_groups = args.get('public_security_group')
        data['public_security_groups'] = [group for group in pub_groups]

    if args.get('private_security_group'):
        priv_groups = args.get('private_security_group')
        data['private_security_groups'] = [group for group in priv_groups]

    if args.get('tag'):
        data['tags'] = ','.join(args['tag'])

    if args.get('host_id'):
        data['host_id'] = args['host_id']

    return data
Example #49
0
 def set_up(self):
     self.hardware = SoftLayer.HardwareManager(self.client)
    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',
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