def main(params):
    try:
        if len(params) < 4:
            print("insufficient parameters!")
        else:
            sl_user = str(params[0])
            sl_apikey = str(params[1])
            instance_id = int(params[2])
            image_name = str(params[3])

            client = SoftLayer.create_client_from_env(username=sl_user,
                                                      api_key=sl_apikey)

            # check if image with image_name exist or not
            # if exist, remove it
            imageManager = SoftLayer.ImageManager(client)
            image_list = imageManager.list_private_images(name=image_name)
            for image in image_list:
                info = imageManager.get_image(image['id'])
                print("found image with " + image_name + ", delete it")
                print(info)
                info = imageManager.delete_image(image['id'])

            # create transaction to capture the image
            vsManager = SoftLayer.VSManager(client)
            image_info = vsManager.capture(instance_id, image_name)
            print(image_info)

    except Exception:
        print(traceback.format_exc())
Ejemplo n.º 2
0
def main(dict):

    API_USERNAME = dict['user']
    API_KEY = dict['apikey']
    VSI = dict['vsi']

    client = SoftLayer.create_client_from_env(username=API_USERNAME,
                                              api_key=API_KEY)
    mgr = SoftLayer.VSManager(client)
    mgr_image = SoftLayer.ImageManager(client)

    vsiname = VSI
    image_list = mgr_image.list_private_images(name=vsiname + '_*')
    image_list.sort(key=lambda x: x['createDate'])

    number_of_snapshots = len(image_list)
    #  print('*** Before deleting old image templates')
    #      for i in range(0, number_of_snapshots):
    #           print(image_list[i]['id'], image_list[i]['createDate'],  image_list[i]['name'] )

    deleted_image = []
    if number_of_snapshots > 2:
        for i in range(0, number_of_snapshots - 2):
            #           print(i, image_list[i]['id'], image_list[i]['createDate'],  image_list[i]['name'] )
            deleted_image.append(image_list[i]['name'])
            mgr_image.delete_image(image_list[i]['id'])

    return {'VSI': VSI, 'deleted_image': deleted_image}
Ejemplo n.º 3
0
def cli(env, public):
    """List images."""

    image_mgr = SoftLayer.ImageManager(env.client)

    images = []
    if public in [False, None]:
        for image in image_mgr.list_private_images(mask=image_mod.MASK):
            images.append(image)

    if public in [True, None]:
        for image in image_mgr.list_public_images(mask=image_mod.MASK):
            images.append(image)

    table = formatting.Table(['guid', 'name', 'type', 'visibility', 'account'])

    images = [image for image in images if image['parentId'] == '']
    for image in images:

        visibility = (image_mod.PUBLIC_TYPE
                      if image['publicFlag'] else image_mod.PRIVATE_TYPE)
        table.add_row([
            image.get('globalIdentifier', formatting.blank()),
            formatting.FormattedItem(image['name'],
                                     click.wrap_text(image['name'], width=50)),
            formatting.FormattedItem(
                utils.lookup(image, 'imageType', 'keyName'),
                utils.lookup(image, 'imageType', 'name')),
            visibility,
            image.get('accountId', formatting.blank()),
        ])

    env.fout(table)
Ejemplo n.º 4
0
def cli(env, name, note, os_code, uri, ibm_api_key, root_key_crn, wrapped_dek,
        cloud_init, byol, is_encrypted):
    """Import an image.

    The URI for an object storage object (.vhd/.iso file) of the format:
    swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
    or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
    Object Storage
    """

    image_mgr = SoftLayer.ImageManager(env.client)
    result = image_mgr.import_image_from_uri(
        name=name,
        note=note,
        os_code=os_code,
        uri=uri,
        ibm_api_key=ibm_api_key,
        root_key_crn=root_key_crn,
        wrapped_dek=wrapped_dek,
        cloud_init=cloud_init,
        byol=byol,
        is_encrypted=is_encrypted
    )

    if not result:
        raise exceptions.CLIAbort("Failed to import Image")

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'
    table.add_row(['name', result['name']])
    table.add_row(['id', result['id']])
    table.add_row(['created', result['createDate']])
    table.add_row(['guid', result['globalIdentifier']])
    env.fout(table)
Ejemplo n.º 5
0
    def execute(self, args):
        image_mgr = SoftLayer.ImageManager(self.client)

        neither = not any([args['--private'], args['--public']])
        mask = 'id,accountId,name,globalIdentifier,blockDevices,parentId'

        images = []
        if args['--private'] or neither:
            for image in image_mgr.list_private_images(mask=mask):
                image['visibility'] = 'private'
                images.append(image)

        if args['--public'] or neither:
            for image in image_mgr.list_public_images(mask=mask):
                image['visibility'] = 'public'
                images.append(image)

        table = formatting.Table(
            ['id', 'account', 'visibility', 'name', 'global_identifier'])

        images = [image for image in images if image['parentId'] == '']
        for image in images:
            table.add_row([
                image['id'],
                image.get('accountId', formatting.blank()),
                image['visibility'],
                image['name'].strip(),
                image.get('globalIdentifier', formatting.blank()),
            ])

        return table
Ejemplo n.º 6
0
def cli(env, name, note, os_code, uri):
    """Import an image.

    The URI for an object storage object (.vhd/.iso file) of the format:
    swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
    """

    image_mgr = SoftLayer.ImageManager(env.client)
    result = image_mgr.import_image_from_uri(
        name=name,
        note=note,
        os_code=os_code,
        uri=uri,
    )

    if not result:
        raise exceptions.CLIAbort("Failed to import Image")

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'
    table.add_row(['name', result['name']])
    table.add_row(['id', result['id']])
    table.add_row(['created', result['createDate']])
    table.add_row(['guid', result['globalIdentifier']])
    env.fout(table)
Ejemplo n.º 7
0
def cli(env, name, note, osrefcode, uri):
    """Import an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    data = {}
    output = []
    if name:
        data['name'] = name
    if note:
        data['note'] = note
    if osrefcode:
        data['operatingSystemReferenceCode'] = osrefcode
    if uri:
        data['uri'] = uri

    # not sure if u should validate here or not
    # if uri.endswith(".vhd") and osrefcode == "":
    #    raise exceptions.CLIAbort("Please specify osrefcode for .vhdImage")

    result = image_mgr.import_image_from_uri(data)

    if not result:
        raise exceptions.CLIAbort("Failed to import Image")

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'
    table.add_row(['name', result['name']])
    table.add_row(['id', result['id']])
    table.add_row(['created', result['createDate']])
    table.add_row(['guid', result['globalIdentifier']])
    output.append(table)
    env.fout(output)
Ejemplo n.º 8
0
def cli(env, identifier):
    """Delete an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')

    image_mgr.delete_image(image_id)
Ejemplo n.º 9
0
 def __init__(self, client, id, imageName, hostname, domain, hasRecovery):
     self.client = client
     self.mgr = SoftLayer.VSManager(self.client)
     self.img_mgr = SoftLayer.ImageManager(self.client)
     self.id = id
     self.imageName = imageName
     self.hostname = hostname  #hostname and domain for the temp servers
     self.domain = domain
     self.hasRecovery = hasRecovery
Ejemplo n.º 10
0
 def __init__(self, swift_username, swift_auth_url=default_swift_url):
     self.conf = config.get_client_settings_config_file()
     self.swift_username = swift_username
     self.sl_client = sl.create_client_from_env()
     self.images = sl.ImageManager(self.sl_client)
     self.servers = sl.VSManager(self.sl_client)
     self.swift = client.Connection(authurl=swift_auth_url,
                                    user=swift_username,
                                    key=self.conf['api_key'])
Ejemplo n.º 11
0
def cli(env, identifier):
    """Get details for an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')

    image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
    disk_space = 0
    datacenters = []
    for child in image.get('children'):
        disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
        if child.get('datacenter'):
            datacenters.append(utils.lookup(child, 'datacenter', 'name'))

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', image['id']])
    table.add_row([
        'global_identifier',
        image.get('globalIdentifier', formatting.blank())
    ])
    table.add_row(['name', image['name'].strip()])
    table.add_row([
        'status',
        formatting.FormattedItem(
            utils.lookup(image, 'status', 'keyname'),
            utils.lookup(image, 'status', 'name'),
        )
    ])
    table.add_row([
        'active_transaction',
        formatting.transaction_status(image.get('transaction')),
    ])
    table.add_row(['account', image.get('accountId', formatting.blank())])
    table.add_row([
        'visibility', image_mod.PUBLIC_TYPE
        if image['publicFlag'] else image_mod.PRIVATE_TYPE
    ])
    table.add_row([
        'type',
        formatting.FormattedItem(
            utils.lookup(image, 'imageType', 'keyName'),
            utils.lookup(image, 'imageType', 'name'),
        )
    ])
    table.add_row(['flex', image.get('flexImageFlag')])
    table.add_row(['note', image.get('note')])
    table.add_row(['created', image.get('createDate')])
    table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
    table.add_row([
        'datacenters',
        formatting.listing(sorted(datacenters), separator=',')
    ])

    env.fout(table)
Ejemplo n.º 12
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')

            _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
Ejemplo n.º 13
0
def cli(env, identifier, add, locations):
    """Add/Remove datacenter of an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')

    if add:
        result = image_mgr.add_locations(image_id, locations)
    else:
        result = image_mgr.remove_locations(image_id, locations)

    env.fout(result)
Ejemplo n.º 14
0
def cli(env, identifier):
    """Get details for an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
    image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)

    children_images = image.get('children')
    total_size = utils.lookup(image, 'firstChild',
                              'blockDevicesDiskSpaceTotal') or 0

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', image['id']])
    table.add_row([
        'global_identifier',
        image.get('globalIdentifier', formatting.blank())
    ])
    table.add_row(['name', image['name'].strip()])
    table.add_row([
        'status',
        formatting.FormattedItem(
            utils.lookup(image, 'status', 'keyname'),
            utils.lookup(image, 'status', 'name'),
        )
    ])

    table.add_row([
        'active_transaction',
        formatting.listing(_get_transaction_groups(children_images),
                           separator=','),
    ])
    table.add_row(['account', image.get('accountId', formatting.blank())])
    table.add_row([
        'visibility', image_mod.PUBLIC_TYPE
        if image['publicFlag'] else image_mod.PRIVATE_TYPE
    ])
    table.add_row([
        'type',
        formatting.FormattedItem(
            utils.lookup(image, 'imageType', 'keyName'),
            utils.lookup(image, 'imageType', 'name'),
        )
    ])
    table.add_row(['flex', image.get('flexImageFlag')])
    table.add_row(['note', image.get('note')])
    table.add_row(['created', image.get('createDate')])
    table.add_row(['total_size', formatting.b_to_gb(total_size)])
    table.add_row(['datacenters', _get_datacenter_table(children_images)])

    env.fout(table)
Ejemplo n.º 15
0
def cli(env, identifier, uri):
    """Export an image to object storage.

    The URI for an object storage object (.vhd/.iso file) of the format:
    swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
    """

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
    result = image_mgr.export_image_to_uri(image_id, uri)

    if not result:
        raise exceptions.CLIAbort("Failed to export Image")
Ejemplo n.º 16
0
 def execute(self, args):
     image_mgr = SoftLayer.ImageManager(self.client)
     data = {}
     if args.get('--name'):
         data['name'] = args.get('--name')
     if args.get('--note'):
         data['note'] = args.get('--note')
     if args.get('--tag'):
         data['tag'] = args.get('--tag')
     image_id = helpers.resolve_id(image_mgr.resolve_ids,
                                   args.get('<identifier>'), 'image')
     if not image_mgr.edit(image_id, **data):
         raise exceptions.CLIAbort("Failed to Edit Image")
Ejemplo n.º 17
0
def cli(env, identifier, name, note, tag):
    """Edit details of an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    data = {}
    if name:
        data['name'] = name
    if note:
        data['note'] = note
    if tag:
        data['tag'] = tag
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
    if not image_mgr.edit(image_id, **data):
        raise exceptions.CLIAbort("Failed to Edit Image")
Ejemplo n.º 18
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
Ejemplo n.º 19
0
    def execute(self, args):
        image_mgr = SoftLayer.ImageManager(self.client)
        image_id = helpers.resolve_id(image_mgr.resolve_ids,
                                      args.get('<identifier>'), 'image')

        image = image_mgr.get_image(image_id)

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

        table.add_row(['id', image['id']])
        table.add_row(['account', image.get('accountId', formatting.blank())])
        table.add_row(['name', image['name'].strip()])
        table.add_row([
            'global_identifier',
            image.get('globalIdentifier', formatting.blank())
        ])

        return table
Ejemplo n.º 20
0
 def set_up(self):
     self.client = testing.FixtureClient()
     self.image = SoftLayer.ImageManager(self.client)
     self.vgbdtg = self.client['Virtual_Guest_Block_Device_Template_Group']
     self.account = self.client['Account']
Ejemplo n.º 21
0
#This Python file uses the following encoding: utf-8
#!/usr/local/bin/python
# coding: latin-1
from __future__ import print_function
import SoftLayer
import json
import sys
imagename = sys.argv[1]
from SoftLayer.managers.vs import VSManager
client = SoftLayer.create_client_from_env()
img = SoftLayer.ImageManager(client)
for ysi1 in img.list_private_images(name=imagename):
    print(ysi1['globalIdentifier'])
Ejemplo n.º 22
0
    def __init__(self):

        self.client = config.client
        self.mgr  = SoftLayer.ImageManager(self.client)
Ejemplo n.º 23
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',
        "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
Ejemplo n.º 24
0
    def execute(self, args):
        image_mgr = SoftLayer.ImageManager(self.client)
        image_id = helpers.resolve_id(image_mgr.resolve_ids,
                                      args.get('<identifier>'), 'image')

        image_mgr.delete_image(image_id)
Ejemplo n.º 25
0
 def set_up(self):
     self.image = SoftLayer.ImageManager(self.client)
     self.vgbdtg = self.client['']
     self.account = self.client['Account']
Ejemplo n.º 26
0
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'):
        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']

    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'])

    return data