def on_post(self, req, resp, tenant_id): body = json.loads(req.stream.read().decode()) try: name = body['keypair']['name'] key = body['keypair'].get('public_key', generate_random_key()) except (KeyError, TypeError): return error_handling.bad_request( resp, 'Not all fields exist to create keypair.') validate_result = validate_keypair_name(resp, name) if not validate_result: return client = req.sl_client mgr = SoftLayer.SshKeyManager(client) # Make sure the key with that label doesn't already exist existing_keys = mgr.list_keys(label=name) if existing_keys: return error_handling.duplicate(resp, 'Duplicate key by that name') try: keypair = mgr.add_key(key, name) resp.body = {'keypair': format_keypair(keypair)} except SoftLayer.SoftLayerAPIError as e: if 'Unable to generate a fingerprint' in e.faultString: return error_handling.bad_request(resp, e.faultString) if 'SSH key already exists' in e.faultString: return error_handling.duplicate(resp, e.faultString) raise
def main(): module = AnsibleModule( argument_spec = dict( username = dict(required=True, type='str'), api_key = dict(required=True, type='str'), state = dict(default='present', choices=['present', 'absent']), label = dict(required=True, type='str'), public_key = dict(default=None, type='str') ) ) if not HAS_SOFTLAYER: module.fail_json(msg='softlayer is required for this module') client = SoftLayer.Client(username=module.params['username'], api_key=module.params['api_key']) mgr = SoftLayer.SshKeyManager(client) state = module.params['state'] if state == 'present': _create_key(module, mgr) elif state == 'absent': _delete_key(module, mgr) else: module.fail_json(msg="%s is not a valid state." % module.params['state'])
def on_get(self, req, resp, tenant_id): client = req.sl_client mgr = SoftLayer.SshKeyManager(client) keypairs = mgr.list_keys() resp.body = { 'keypairs': [{ 'keypair': format_keypair(keypair)} for keypair in keypairs]}
def _parse_create_args(client, args): """Converts CLI arguments to args for VSManager.create_instance. :param dict args: CLI arguments """ data = { "hourly": args['billing'] == 'hourly', "cpus": args['cpu'], "domain": args['domain'], "hostname": args['hostname'], "private": args['private'], "dedicated": args['dedicated'], "disks": args['disk'], "local_disk": not args['san'], } data["memory"] = args['memory'] if args.get('os'): data['os_code'] = args['os'] if args.get('image'): 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'] if args.get('tag'): data['tags'] = ','.join(args['tag']) return data
def execute(self, args): mgr = SoftLayer.SshKeyManager(self.client) key_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'), 'SshKey') if not mgr.edit_key( key_id, label=args['--label'], notes=args['--notes']): raise exceptions.CLIAbort('Failed to edit SSH key')
def execute(self, args): mgr = SoftLayer.SshKeyManager(self.client) key_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'), 'SshKey') if args['--really'] or formatting.no_going_back(key_id): mgr.delete_key(key_id) else: raise exceptions.CLIAbort('Aborted')
def cli(env, identifier): """Permanently removes an SSH key.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') if not (env.skip_confirmations or formatting.no_going_back(key_id)): raise exceptions.CLIAbort('Aborted') mgr.delete_key(key_id)
def cli(env, identifier, label, note): """Edits an SSH key.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') if not mgr.edit_key(key_id, label=label, notes=note): raise exceptions.CLIAbort('Failed to edit SSH key')
def _handle_sshkeys(self, payload, body, client): ssh_keys = [] key_name = body['server'].get('key_name') if key_name: sshkey_mgr = SoftLayer.SshKeyManager(client) keys = sshkey_mgr.list_keys(label=key_name) if len(keys) == 0: raise Exception('KeyPair could not be found') ssh_keys.append(keys[0]['id']) payload['ssh_keys'] = ssh_keys
def on_delete(self, req, resp, tenant_id, keypair_name): # keypair_name client = req.sl_client mgr = SoftLayer.SshKeyManager(client) keys = mgr.list_keys(label=keypair_name) if len(keys) == 0: return error_handling.not_found(resp, 'KeyPair not Found') mgr.delete_key(keys[0]['id']) resp.status = 202
def on_get(self, req, resp, tenant_id, keypair_name): client = req.sl_client mgr = SoftLayer.SshKeyManager(client) keys = mgr.list_keys(label=keypair_name) if len(keys) == 0: return error_handling.not_found(resp, 'KeyPair not found') keypair = mgr.get_key(keys[0]['id']) resp.body = {'keypair': format_keypair(keypair)}
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 execute(self, args): if args.get('--key'): key = args['--key'] else: key_file = open(path.expanduser(args['--file']), 'rU') key = key_file.read().strip() key_file.close() mgr = SoftLayer.SshKeyManager(self.client) result = mgr.add_key(key, args['<label>'], args.get('--notes')) return "SSH key added: %s" % result.get('fingerprint')
def create( self, node_name: str, image_name: str, size_of_disks: int = 0, no_of_volumes: int = 0, **kwargs, ) -> None: """ Create the instance with the provided data. Args: node_name: Name of the VM. image_name: Name of the image to use for creating the VM. vm_size: Flavor to be used to create the VM vm_network: Name of the network/s cloud_data: The cloud-init configuration information size_of_disks: The storage capacity of the volumes no_of_volumes: The number of volumes to be attached. """ LOG.info("Starting to create VM with name %s", node_name) try: ibmcloud_client = SoftLayer.VSManager(self.driver) keys = SoftLayer.SshKeyManager(self.driver).list_keys() key_ids = [d["id"] for d in keys if d["label"] == "Amarnath"] new_vsi = { "domain": "cephci-QE.cloud", "hostname": node_name, "datacenter": "che01", "flavor": "B1_2X4X25", "dedicated": False, "private": True, "os_code": image_name, "hourly": True, "ssh_keys": key_ids, "local_disk": False, "tags": "test, pleaseCancel", } if no_of_volumes: size_of_disks = 25 if size_of_disks <= 25 else size_of_disks new_vsi["disks"] = [str(size_of_disks)] * no_of_volumes self.node = ibmcloud_client.create_instance(**new_vsi) ibmcloud_client.wait_for_ready(self.node["id"]) except (ResourceNotFound, NetworkOpFailure, NodeError, VolumeOpFailure): raise except BaseException as be: # noqa LOG.error(be, exc_info=True) raise NodeError( f"Unknown error. Failed to create VM with name {node_name}")
def cli(env, label, in_file, key, note): """Add a new SSH key.""" if key: key_text = key else: key_file = open(path.expanduser(in_file), 'rU') key_text = key_file.read().strip() key_file.close() mgr = SoftLayer.SshKeyManager(env.client) result = mgr.add_key(key_text, label, note) env.fout("SSH key added: %s" % result.get('fingerprint'))
def execute(self, args): hardware = SoftLayer.HardwareManager(self.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, args.get('<identifier>'), 'hardware') keys = [] if args.get('--key'): for key in args.get('--key'): resolver = SoftLayer.SshKeyManager(self.client).resolve_ids key_id = helpers.resolve_id(resolver, key, 'SshKey') keys.append(key_id) if args['--really'] or formatting.no_going_back(hardware_id): hardware.reload(hardware_id, args['--postinstall'], keys) else: raise exceptions.CLIAbort('Aborted')
def cli(env, identifier, postinstall, key): """Reload operating system on a virtual server.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') keys = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') keys.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(vs_id)): raise exceptions.CLIAbort('Aborted') vsi.reload_instance(vs_id, postinstall, keys)
def execute(self, args): mgr = SoftLayer.SshKeyManager(self.client) keys = mgr.list_keys() table = formatting.Table(['id', 'label', 'fingerprint', 'notes']) for key in keys: table.add_row([ key['id'], key.get('label'), key.get('fingerprint'), key.get('notes', '-') ]) return table
def cli(env, identifier, postinstall, key, lvm): """Reload operating system on a server.""" hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') key_list = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') key_list.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(hardware_id)): raise exceptions.CLIAbort('Aborted') hardware.reload(hardware_id, postinstall, key_list, lvm)
def execute(self, args): mgr = SoftLayer.SshKeyManager(self.client) key_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'), 'SshKey') key = mgr.get_key(key_id) if args.get('--file'): with open(path.expanduser(args['--file']), 'w') as pub_file: pub_file.write(key['key']) table = formatting.KeyValueTable(['Name', 'Value']) table.add_row(['id', key['id']]) table.add_row(['label', key.get('label')]) table.add_row(['notes', key.get('notes', '-')]) return table
def cli(env, sortby): """List SSH keys.""" mgr = SoftLayer.SshKeyManager(env.client) keys = mgr.list_keys() table = formatting.Table(['id', 'label', 'fingerprint', 'notes']) table.sortby = sortby for key in keys: table.add_row([ key['id'], key.get('label'), key.get('fingerprint'), key.get('notes', '-') ]) return table
def cli(env, identifier, out_file): """Prints out an SSH key to the screen.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') key = mgr.get_key(key_id) if out_file: with open(path.expanduser(out_file), 'w') as pub_file: pub_file.write(key['key']) table = formatting.KeyValueTable(['Name', 'Value']) table.add_row(['id', key['id']]) table.add_row(['label', key.get('label')]) table.add_row(['notes', key.get('notes', '-')]) env.fout(table)
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 cli(env, label, in_file, key, note): """Add a new SSH key.""" if in_file is None and key is None: raise exceptions.ArgumentError( 'Either [-f | --in-file] or [-k | --key] arguments are required to add a key' ) if in_file and key: raise exceptions.ArgumentError( '[-f | --in-file] is not allowed with [-k | --key]') if key: key_text = key else: key_file = open(path.expanduser(in_file), 'rU') key_text = key_file.read().strip() key_file.close() mgr = SoftLayer.SshKeyManager(env.client) result = mgr.add_key(key_text, label, note) env.fout("SSH key added: %s" % result.get('fingerprint'))
def set_up(self): self.sshkey = SoftLayer.SshKeyManager(self.client)
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', "cpus": args.get('cpu', None), "ipv6": args.get('ipv6', None), "disks": args.get('disk', None), "os_code": args.get('os', None), "memory": args.get('memory', None), "flavor": args.get('flavor', None), "domain": args.get('domain', None), "host_id": args.get('host_id', None), "private": args.get('private', None), "transient": args.get('transient', None), "hostname": args.get('hostname', None), "nic_speed": args.get('network', None), "boot_mode": args.get('boot_mode', None), "dedicated": args.get('dedicated', None), "post_uri": args.get('postinstall', None), "datacenter": args.get('datacenter', None), "public_vlan": args.get('vlan_public', None), "private_vlan": args.get('vlan_private', None), "public_subnet": args.get('subnet_public', None), "private_subnet": args.get('subnet_private', 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('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('userdata'): data['userdata'] = args['userdata'] elif args.get('userfile'): with open(args['userfile'], 'r') as userfile: data['userdata'] = userfile.read() # 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('public_security_group'): pub_groups = args.get('public_security_group') data['public_security_groups'] = list(pub_groups) if args.get('private_security_group'): priv_groups = args.get('private_security_group') data['private_security_groups'] = list(priv_groups) if args.get('tag', False): data['tags'] = ','.join(args['tag']) if args.get('host_id'): data['host_id'] = args['host_id'] if args.get('placementgroup'): resolver = SoftLayer.managers.PlacementManager(client).resolve_ids data['placement_id'] = helpers.resolve_id(resolver, args.get('placementgroup'), 'PlacementGroup') return data
action='store_true', help="Don't prompt. Assume yes") parser.add_argument('hosts', metavar='HOST', nargs='+', help='host names to reload') opts = parser.parse_args() hosts = opts.hosts client = SoftLayer.create_client_from_env() vs = SoftLayer.VSManager(client) ssh = SoftLayer.SshKeyManager(client) hardware = SoftLayer.HardwareManager(client) instances = [] for i in vs.list_instances() + hardware.list_hardware(): for pattern in hosts: if fnmatch.fnmatchcase(i['fullyQualifiedDomainName'], pattern): instances.append(i) break if not opts.yes: names = [" - %s" % i['fullyQualifiedDomainName'] for i in instances] names = "\n".join(sorted(names)) prompt = raw_input("Going to reload:\n%s\nStart [y/N]: " % names)
def cli(env, identifier): """Get details of an Autoscale groups.""" autoscale = AutoScaleManager(env.client) group = autoscale.details(identifier) # Group Config Table table = formatting.KeyValueTable(["Group", "Value"]) table.align['Group'] = 'l' table.align['Value'] = 'l' table.add_row(['Id', group.get('id')]) # Ideally we would use regionalGroup->preferredDatacenter, but that generates an error. table.add_row(['Datacenter', group['regionalGroup']['locations'][0]['longName']]) table.add_row(['Termination', utils.lookup(group, 'terminationPolicy', 'name')]) table.add_row(['Minimum Members', group.get('minimumMemberCount')]) table.add_row(['Maximum Members', group.get('maximumMemberCount')]) table.add_row(['Current Members', group.get('virtualGuestMemberCount')]) table.add_row(['Cooldown', "{} seconds".format(group.get('cooldown'))]) table.add_row(['Last Action', utils.clean_time(group.get('lastActionDate'))]) for network in group.get('networkVlans', []): network_type = utils.lookup(network, 'networkVlan', 'networkSpace') router = utils.lookup(network, 'networkVlan', 'primaryRouter', 'hostname') vlan_number = utils.lookup(network, 'networkVlan', 'vlanNumber') vlan_name = "{}.{}".format(router, vlan_number) table.add_row([network_type, vlan_name]) env.fout(table) # Template Config Table config_table = formatting.KeyValueTable(["Template", "Value"]) config_table.align['Template'] = 'l' config_table.align['Value'] = 'l' template = group.get('virtualGuestMemberTemplate') config_table.add_row(['Hostname', template.get('hostname')]) config_table.add_row(['Domain', template.get('domain')]) config_table.add_row(['Core', template.get('startCpus')]) config_table.add_row(['Ram', template.get('maxMemory')]) network = template.get('networkComponents') config_table.add_row(['Network', network[0]['maxSpeed'] if network else 'Default']) ssh_keys = template.get('sshKeys', []) ssh_manager = SoftLayer.SshKeyManager(env.client) for key in ssh_keys: # Label isn't included when retrieved from the AutoScale group... ssh_key = ssh_manager.get_key(key.get('id')) config_table.add_row(['SSH Key {}'.format(ssh_key.get('id')), ssh_key.get('label')]) disks = template.get('blockDevices', []) disk_type = "Local" if template.get('localDiskFlag') else "SAN" for disk in disks: disk_image = disk.get('diskImage') config_table.add_row(['{} Disk {}'.format(disk_type, disk.get('device')), disk_image.get('capacity')]) config_table.add_row(['OS', template.get('operatingSystemReferenceCode')]) config_table.add_row(['Post Install', template.get('postInstallScriptUri') or 'None']) env.fout(config_table) # Policy Config Table policy_table = formatting.KeyValueTable(["Policy", "Cooldown"]) policies = group.get('policies', []) for policy in policies: policy_table.add_row([policy.get('name'), policy.get('cooldown') or group.get('cooldown')]) env.fout(policy_table) # Active Guests member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Active Guests") guests = group.get('virtualGuestMembers', []) for guest in guests: real_guest = guest.get('virtualGuest') member_table.add_row([ real_guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate')) ]) env.fout(member_table)
def _process_args(self, args, ds_options): """ Helper method to centralize argument processing without convoluting code flow of the main execute method. """ mgr = SoftLayer.HardwareManager(self.client) order = { 'hostname': args['--hostname'], 'domain': args['--domain'], 'bare_metal': False, 'package_id': args['--chassis'], } # Determine if this is a "Bare Metal Instance" or regular server bmc = False if args['--chassis'] == str(mgr.get_bare_metal_package_id()): bmc = True # Convert the OS code back into a price ID os_price = self._get_price_id_from_options(ds_options, 'os', args['--os']) if os_price: order['os'] = os_price else: raise exceptions.CLIAbort('Invalid operating system specified.') order['location'] = args['--datacenter'] or 'FIRST_AVAILABLE' if bmc: order['server'] = self._get_cpu_and_memory_price_ids( ds_options, args['--cpu'], args['--memory']) order['bare_metal'] = True if args['--billing'] == 'hourly': order['hourly'] = True else: order['server'] = args['--cpu'] order['ram'] = self._get_price_id_from_options( ds_options, 'memory', int(args['--memory'])) # Set the disk sizes disk_prices = [] disk_number = 0 for disk in args.get('--disk'): disk_price = self._get_disk_price(ds_options, disk, disk_number) disk_number += 1 if disk_price: disk_prices.append(disk_price) if not disk_prices: disk_prices.append(self._get_default_value(ds_options, 'disk0')) order['disks'] = disk_prices # Set the disk controller price if not bmc: if args.get('--controller'): dc_price = self._get_price_id_from_options( ds_options, 'disk_controller', args.get('--controller')) else: dc_price = self._get_price_id_from_options( ds_options, 'disk_controller', 'None') order['disk_controller'] = dc_price # Set the port speed port_speed = args.get('--network') or '100' nic_price = self._get_price_id_from_options(ds_options, 'nic', port_speed) if nic_price: order['port_speed'] = nic_price else: raise exceptions.CLIAbort('Invalid NIC speed specified.') if args.get('--postinstall'): order['post_uri'] = args.get('--postinstall') # Get the SSH keys if args.get('--key'): keys = [] for key in args.get('--key'): resolver = SoftLayer.SshKeyManager(self.client).resolve_ids key_id = helpers.resolve_id(resolver, key, 'SshKey') keys.append(key_id) order['ssh_keys'] = keys if args.get('--vlan_public'): order['public_vlan'] = args['--vlan_public'] if args.get('--vlan_private'): order['private_vlan'] = args['--vlan_private'] return order
def __init__(self, sl_client, instance_config, wait): SoftlayerVirtualServerBasic.__init__(self, sl_client, instance_config) self._sl_ssh_keys_manager = SoftLayer.SshKeyManager(sl_client) self._wait = wait