Create an ami from a snapshot

    CLI Example:

    .. code-block:: bash

        salt-cloud -f register_image my-ec2-config ami_name=my_ami description="my description"
                root_device_name=/dev/xvda snapshot_id=snap-xxxxxxxx
9581
def register_image(kwargs=None, call=None):
    '''
    
    '''

    if call != 'function':
        log.error(
            'The create_volume function must be called with -f or --function.'
        )
        return False

    if 'ami_name' not in kwargs:
        log.error('ami_name must be specified to register an image.')
        return False

    block_device_mapping = kwargs.get('block_device_mapping', None)
    if not block_device_mapping:
        if 'snapshot_id' not in kwargs:
            log.error('snapshot_id or block_device_mapping must be specified to register an image.')
            return False
        if 'root_device_name' not in kwargs:
            log.error('root_device_name or block_device_mapping must be specified to register an image.')
            return False
        block_device_mapping = [{
            'DeviceName': kwargs['root_device_name'],
            'Ebs': {
                'VolumeType': kwargs.get('volume_type', 'gp2'),
                'SnapshotId': kwargs['snapshot_id'],
             }
        }]

    if not isinstance(block_device_mapping, list):
        block_device_mapping = [block_device_mapping]

    params = {'Action': 'RegisterImage',
              'Name': kwargs['ami_name']}

    params.update(_param_from_config('BlockDeviceMapping', block_device_mapping))

    if 'root_device_name' in kwargs:
        params['RootDeviceName'] = kwargs['root_device_name']

    if 'description' in kwargs:
        params['Description'] = kwargs['description']

    if 'virtualization_type' in kwargs:
        params['VirtualizationType'] = kwargs['virtualization_type']

    if 'architecture' in kwargs:
        params['Architecture'] = kwargs['architecture']

    log.debug(params)

    data = aws.query(params,
                     return_url=True,
                     return_root=True,
                     location=get_location(),
                     provider=get_provider(),
                     opts=__opts__,
                     sigver='4')

    r_data = {}
    for d in data[0]:
        for k, v in d.items():
            r_data[k] = v

    return r_data
1134954
def assure_snapshot(fnc):
    
    @wraps(fnc)
    def _wrapped(self, snapshot, *args, **kwargs):
        if not isinstance(snapshot, CloudBlockStorageSnapshot):
            # Must be the ID
            snapshot = self._snapshot_manager.get(snapshot)
        return fnc(self, snapshot, *args, **kwargs)
    return _wrapped
783714
def create_snapshot(self, volume, name, description=None, force=False):
        
        return self.api.create_snapshot(volume, name, description=description,
                force=force)
22237
def create_snapshot(self, systemId, snapshotSpecificationObject):
        
        self.conn.connection._check_login()
        #try:
        response = self.conn.connection._do_post("{}/{}{}/{}".format(self.conn.connection._api_url, "instances/System::", systemId, 'action/snapshotVolumes'), json=snapshotSpecificationObject.__to_dict__())
        #except:
        #    raise RuntimeError("create_snapshot_by_system_id() - Error communicating with ScaleIO gateway")
        return response
73282
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'joyent',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info(
        'Creating Cloud VM %s in %s',
        vm_['name'], vm_.get('location', DEFAULT_LOCATION)
    )

    # added . for fqdn hostnames
    salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
    kwargs = {
        'name': vm_['name'],
        'image': get_image(vm_),
        'size': get_size(vm_),
        'location': vm_.get('location', DEFAULT_LOCATION)
    }
    # Let's not assign a default here; only assign a network value if
    # one is explicitly configured
    if 'networks' in vm_:
        kwargs['networks'] = vm_.get('networks')

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    data = create_node(**kwargs)
    if data == {}:
        log.error('Error creating %s on JOYENT', vm_['name'])
        return False

    query_instance(vm_)
    data = show_instance(vm_['name'], call='action')

    vm_['key_filename'] = key_filename
    vm_['ssh_host'] = data[1]['primaryIp']

    __utils__['cloud.bootstrap'](vm_, __opts__)

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return data[1]
887276
def create_server(cloud, **kwargs):
    
    if cloud == 'ec2':
        _create_server_ec2(**kwargs)
    elif cloud == 'rackspace':
        _create_server_rackspace(**kwargs)
    elif cloud == 'gce':
        _create_server_gce(**kwargs)
    else:
        raise ValueError("Unknown cloud type: {}".format(cloud))
350572
def _get_jid_snapshots(jid, config='root'):
    '''
    
    '''
    jid_snapshots = [x for x in list_snapshots(config) if x['userdata'].get("salt_jid") == jid]
    pre_snapshot = [x for x in jid_snapshots if x['type'] == "pre"]
    post_snapshot = [x for x in jid_snapshots if x['type'] == "post"]

    if not pre_snapshot or not post_snapshot:
        raise CommandExecutionError("Jid '{0}' snapshots not found".format(jid))

    return (
        pre_snapshot[0]['id'],
        post_snapshot[0]['id']
    )
1340938
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if (vm_['profile'] and
            config.is_profile_configured(__opts__,
                                         __active_provider_name__ or 'vmware',
                                         vm_['profile'],
                                         vm_=vm_) is False):
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    vm_name = config.get_cloud_config_value(
        'name', vm_, __opts__, default=None
    )
    folder = config.get_cloud_config_value(
        'folder', vm_, __opts__, default=None
    )
    datacenter = config.get_cloud_config_value(
        'datacenter', vm_, __opts__, default=None
    )
    resourcepool = config.get_cloud_config_value(
        'resourcepool', vm_, __opts__, default=None
    )
    cluster = config.get_cloud_config_value(
        'cluster', vm_, __opts__, default=None
    )
    datastore = config.get_cloud_config_value(
        'datastore', vm_, __opts__, default=None
    )
    host = config.get_cloud_config_value(
        'host', vm_, __opts__, default=None
    )
    template = config.get_cloud_config_value(
        'template', vm_, __opts__, default=False
    )
    num_cpus = config.get_cloud_config_value(
        'num_cpus', vm_, __opts__, default=None
    )
    cores_per_socket = config.get_cloud_config_value(
        'cores_per_socket', vm_, __opts__, default=None
    )
    memory = config.get_cloud_config_value(
        'memory', vm_, __opts__, default=None
    )
    devices = config.get_cloud_config_value(
        'devices', vm_, __opts__, default=None
    )
    extra_config = config.get_cloud_config_value(
        'extra_config', vm_, __opts__, default=None
    )
    annotation = config.get_cloud_config_value(
        'annotation', vm_, __opts__, default=None
    )
    power = config.get_cloud_config_value(
        'power_on', vm_, __opts__, default=True
    )
    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    deploy = config.get_cloud_config_value(
        'deploy', vm_, __opts__, search_global=True, default=True
    )
    wait_for_ip_timeout = config.get_cloud_config_value(
        'wait_for_ip_timeout', vm_, __opts__, default=20 * 60
    )
    domain = config.get_cloud_config_value(
        'domain', vm_, __opts__, search_global=False, default='local'
    )
    hardware_version = config.get_cloud_config_value(
        'hardware_version', vm_, __opts__, search_global=False, default=None
    )
    guest_id = config.get_cloud_config_value(
        'image', vm_, __opts__, search_global=False, default=None
    )
    customization = config.get_cloud_config_value(
        'customization', vm_, __opts__, search_global=False, default=True
    )
    customization_spec = config.get_cloud_config_value(
        'customization_spec', vm_, __opts__, search_global=False, default=None
    )
    win_password = config.get_cloud_config_value(
        'win_password', vm_, __opts__, search_global=False, default=None
    )
    win_organization_name = config.get_cloud_config_value(
        'win_organization_name', vm_, __opts__, search_global=False, default='Organization'
    )
    plain_text = config.get_cloud_config_value(
        'plain_text', vm_, __opts__, search_global=False, default=False
    )
    win_user_fullname = config.get_cloud_config_value(
        'win_user_fullname', vm_, __opts__, search_global=False, default='Windows User'
    )
    win_run_once = config.get_cloud_config_value(
        'win_run_once', vm_, __opts__, search_global=False, default=None
    )
    win_ad_domain = config.get_cloud_config_value(
        'win_ad_domain', vm_, __opts__, search_global=False, default=''
    )
    win_ad_user = config.get_cloud_config_value(
        'win_ad_user', vm_, __opts__, search_global=False, default=''
    )
    win_ad_password = config.get_cloud_config_value(
        'win_ad_password', vm_, __opts__, search_global=False, default=''
    )
    win_autologon = config.get_cloud_config_value(
        'win_autologon', vm_, __opts__, search_global=False, default=True
    )
    timezone = config.get_cloud_config_value(
        'timezone', vm_, __opts__, search_global=False, default=''
    )
    hw_clock_utc = config.get_cloud_config_value(
        'hw_clock_utc', vm_, __opts__, search_global=False, default=''
    )
    clonefrom_datacenter = config.get_cloud_config_value(
        'clonefrom_datacenter', vm_, __opts__, search_global=False, default=datacenter
    )

    # Get service instance object
    si = _get_si()

    container_ref = None
    clonefrom_datacenter_ref = None

    # If datacenter is specified, set the container reference to start search from it instead
    if datacenter:
        datacenter_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.Datacenter, datacenter)
        container_ref = datacenter_ref if datacenter_ref else None

    if 'clonefrom' in vm_:
        # If datacenter is specified, set the container reference to start search from it instead
        if datacenter:
            datacenter_ref = salt.utils.vmware.get_mor_by_property(
                                 si,
                                 vim.Datacenter,
                                 datacenter
                             )
            container_ref = datacenter_ref if datacenter_ref else None
            clonefrom_container_ref = datacenter_ref if datacenter_ref else None
        # allow specifying a different datacenter that the template lives in
        if clonefrom_datacenter:
            clonefrom_datacenter_ref = salt.utils.vmware.get_mor_by_property(
                                           si,
                                           vim.Datacenter,
                                           clonefrom_datacenter
                                       )
            clonefrom_container_ref = clonefrom_datacenter_ref if clonefrom_datacenter_ref else None

        # Clone VM/template from specified VM/template
        object_ref = salt.utils.vmware.get_mor_by_property(
                         si,
                         vim.VirtualMachine,
                         vm_['clonefrom'],
                         container_ref=clonefrom_container_ref
                     )
        if object_ref:
            clone_type = "template" if object_ref.config.template else "vm"
        else:
            raise SaltCloudSystemExit(
                'The VM/template that you have specified under clonefrom does not exist.'
            )
    else:
        clone_type = None
        object_ref = None

    # Either a cluster, or a resource pool must be specified when cloning from template or creating.
    if resourcepool:
        resourcepool_ref = salt.utils.vmware.get_mor_by_property(
                               si,
                               vim.ResourcePool,
                               resourcepool,
                               container_ref=container_ref
                           )
        if not resourcepool_ref:
            log.error("Specified resource pool: '%s' does not exist", resourcepool)
            if not clone_type or clone_type == "template":
                raise SaltCloudSystemExit('You must specify a resource pool that exists.')
    elif cluster:
        cluster_ref = salt.utils.vmware.get_mor_by_property(
                          si,
                          vim.ClusterComputeResource,
                          cluster,
                          container_ref=container_ref
                      )
        if not cluster_ref:
            log.error("Specified cluster: '%s' does not exist", cluster)
            if not clone_type or clone_type == "template":
                raise SaltCloudSystemExit('You must specify a cluster that exists.')
        else:
            resourcepool_ref = cluster_ref.resourcePool
    elif clone_type == "template":
        raise SaltCloudSystemExit(
            'You must either specify a cluster or a resource pool when cloning from a template.'
        )
    elif not clone_type:
        raise SaltCloudSystemExit(
            'You must either specify a cluster or a resource pool when creating.'
        )
    else:
        log.debug("Using resource pool used by the %s %s", clone_type, vm_['clonefrom'])

    # Either a datacenter or a folder can be optionally specified when cloning, required when creating.
    # If not specified when cloning, the existing VM/template\'s parent folder is used.
    if folder:
        folder_parts = folder.split('/')
        search_reference = container_ref
        for folder_part in folder_parts:
            if folder_part:
                folder_ref = salt.utils.vmware.get_mor_by_property(
                                 si,
                                 vim.Folder,
                                 folder_part,
                                 container_ref=search_reference
                             )
                search_reference = folder_ref
        if not folder_ref:
            log.error("Specified folder: '%s' does not exist", folder)
            log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
            folder_ref = object_ref.parent
    elif datacenter:
        if not datacenter_ref:
            log.error("Specified datacenter: '%s' does not exist", datacenter)
            log.debug("Using datacenter folder in which %s %s is present", clone_type, vm_['clonefrom'])
            folder_ref = object_ref.parent
        else:
            folder_ref = datacenter_ref.vmFolder
    elif not clone_type:
        raise SaltCloudSystemExit(
            'You must either specify a folder or a datacenter when creating not cloning.'
        )
    else:
        log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
        folder_ref = object_ref.parent

    if 'clonefrom' in vm_:
        # Create the relocation specs
        reloc_spec = vim.vm.RelocateSpec()

        if (resourcepool and resourcepool_ref) or (cluster and cluster_ref):
            reloc_spec.pool = resourcepool_ref

        # Either a datastore/datastore cluster can be optionally specified.
        # If not specified, the current datastore is used.
        if datastore:
            datastore_ref = salt.utils.vmware.get_mor_by_property(
                                si,
                                vim.Datastore,
                                datastore,
                                container_ref=container_ref
                            )
            if datastore_ref:
                # specific datastore has been specified
                reloc_spec.datastore = datastore_ref
            else:
                datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore, container_ref=container_ref)
                if not datastore_cluster_ref:
                    log.error("Specified datastore/datastore cluster: '%s' does not exist", datastore)
                    log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
        else:
            log.debug("No datastore/datastore cluster specified")
            log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])

        if host:
            host_ref = salt.utils.vmware.get_mor_by_property(
                           si,
                           vim.HostSystem,
                           host,
                           container_ref=container_ref
                       )
            if host_ref:
                reloc_spec.host = host_ref
            else:
                log.error("Specified host: '%s' does not exist", host)
    else:
        if not datastore:
            raise SaltCloudSystemExit(
                'You must specify a datastore when creating not cloning.'
            )
        else:
            datastore_ref = salt.utils.vmware.get_mor_by_property(
                                si,
                                vim.Datastore,
                                datastore
                            )
            if not datastore_ref:
                raise SaltCloudSystemExit("Specified datastore: '{0}' does not exist".format(datastore))

        if host:
            host_ref = salt.utils.vmware.get_mor_by_property(
                           _get_si(),
                           vim.HostSystem,
                           host,
                           container_ref=container_ref
                       )
            if not host_ref:
                log.error("Specified host: '%s' does not exist", host)

    # Create the config specs
    config_spec = vim.vm.ConfigSpec()

    # If the hardware version is specified and if it is different from the current
    # hardware version, then schedule a hardware version upgrade
    if hardware_version and object_ref is not None:
        hardware_version = 'vmx-{0:02}'.format(hardware_version)
        if hardware_version != object_ref.config.version:
            log.debug(
                "Scheduling hardware version upgrade from %s to %s",
                object_ref.config.version, hardware_version
            )
            scheduled_hardware_upgrade = vim.vm.ScheduledHardwareUpgradeInfo()
            scheduled_hardware_upgrade.upgradePolicy = 'always'
            scheduled_hardware_upgrade.versionKey = hardware_version
            config_spec.scheduledHardwareUpgradeInfo = scheduled_hardware_upgrade
        else:
            log.debug("Virtual hardware version already set to %s", hardware_version)

    if num_cpus:
        log.debug("Setting cpu to: %s", num_cpus)
        config_spec.numCPUs = int(num_cpus)

    if cores_per_socket:
        log.debug("Setting cores per socket to: %s", cores_per_socket)
        config_spec.numCoresPerSocket = int(cores_per_socket)

    if memory:
        try:
            memory_num, memory_unit = re.findall(r"[^\W\d_]+|\d+.\d+|\d+",
                                                 memory)
            if memory_unit.lower() == "mb":
                memory_mb = int(memory_num)
            elif memory_unit.lower() == "gb":
                memory_mb = int(float(memory_num)*1024.0)
            else:
                err_msg = "Invalid memory type specified: '{0}'".format(memory_unit)
                log.error(err_msg)
                return {'Error': err_msg}
        except (TypeError, ValueError):
            memory_mb = int(memory)
        log.debug("Setting memory to: %s MB", memory_mb)
        config_spec.memoryMB = memory_mb

    if devices:
        specs = _manage_devices(devices, vm=object_ref, container_ref=container_ref, new_vm_name=vm_name)
        config_spec.deviceChange = specs['device_specs']

    if extra_config:
        for key, value in six.iteritems(extra_config):
            option = vim.option.OptionValue(key=key, value=value)
            config_spec.extraConfig.append(option)

    if annotation:
        config_spec.annotation = six.text_type(annotation)

    if 'clonefrom' in vm_:
        clone_spec = handle_snapshot(
            config_spec,
            object_ref,
            reloc_spec,
            template,
            vm_
        )
        if not clone_spec:
            clone_spec = build_clonespec(config_spec,
                                         object_ref,
                                         reloc_spec,
                                         template)

        if customization and customization_spec:
            customization_spec = salt.utils.vmware.get_customizationspec_ref(si=si, customization_spec_name=customization_spec)
            clone_spec.customization = customization_spec.spec
        elif customization and (devices and 'network' in list(devices.keys())):
            global_ip = vim.vm.customization.GlobalIPSettings()
            if 'dns_servers' in list(vm_.keys()):
                global_ip.dnsServerList = vm_['dns_servers']

            non_hostname_chars = re.compile(r'[^\w-]')
            if re.search(non_hostname_chars, vm_name):
                host_name = re.split(non_hostname_chars,
                                     vm_name,
                                     maxsplit=1)[0]
                domain_name = re.split(non_hostname_chars,
                                       vm_name,
                                       maxsplit=1)[-1]
            else:
                host_name = vm_name
                domain_name = domain

            if 'Windows' not in object_ref.config.guestFullName:
                identity = vim.vm.customization.LinuxPrep()
                identity.hostName = vim.vm.customization.FixedName(name=host_name)
                identity.domain = domain_name
                if timezone:
                    identity.timeZone = timezone
                if isinstance(hw_clock_utc, bool):
                    identity.hwClockUTC = hw_clock_utc
            else:
                identity = vim.vm.customization.Sysprep()
                identity.guiUnattended = vim.vm.customization.GuiUnattended()
                identity.guiUnattended.autoLogon = win_autologon
                if win_autologon:
                    identity.guiUnattended.autoLogonCount = 1
                else:
                    identity.guiUnattended.autoLogonCount = 0
                identity.guiUnattended.password = vim.vm.customization.Password()
                identity.guiUnattended.password.value = win_password
                identity.guiUnattended.password.plainText = plain_text
                if timezone:
                    identity.guiUnattended.timeZone = timezone
                if win_run_once:
                    identity.guiRunOnce = vim.vm.customization.GuiRunOnce()
                    identity.guiRunOnce.commandList = win_run_once
                identity.userData = vim.vm.customization.UserData()
                identity.userData.fullName = win_user_fullname
                identity.userData.orgName = win_organization_name
                identity.userData.computerName = vim.vm.customization.FixedName()
                identity.userData.computerName.name = host_name
                identity.identification = vim.vm.customization.Identification()
                if win_ad_domain and win_ad_user and win_ad_password:
                    identity.identification.joinDomain = win_ad_domain
                    identity.identification.domainAdmin = win_ad_user
                    identity.identification.domainAdminPassword = vim.vm.customization.Password()
                    identity.identification.domainAdminPassword.value = win_ad_password
                    identity.identification.domainAdminPassword.plainText = plain_text
            custom_spec = vim.vm.customization.Specification(
                globalIPSettings=global_ip,
                identity=identity,
                nicSettingMap=specs['nics_map']
            )
            clone_spec.customization = custom_spec

        if not template:
            clone_spec.powerOn = power

        log.debug('clone_spec set to:\n%s', pprint.pformat(clone_spec))

    else:
        config_spec.name = vm_name
        config_spec.files = vim.vm.FileInfo()
        config_spec.files.vmPathName = '[{0}] {1}/{1}.vmx'.format(datastore, vm_name)
        config_spec.guestId = guest_id

        log.debug('config_spec set to:\n%s', pprint.pformat(config_spec))

    event_kwargs = vm_.copy()
    if event_kwargs.get('password'):
        del event_kwargs['password']

    try:
        __utils__['cloud.fire_event'](
            'event',
            'requesting instance',
            'salt/cloud/{0}/requesting'.format(vm_['name']),
            args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        if 'clonefrom' in vm_:
            log.info("Creating %s from %s(%s)", vm_['name'], clone_type, vm_['clonefrom'])

            if datastore and not datastore_ref and datastore_cluster_ref:
                # datastore cluster has been specified so apply Storage DRS recommendations
                pod_spec = vim.storageDrs.PodSelectionSpec(storagePod=datastore_cluster_ref)

                storage_spec = vim.storageDrs.StoragePlacementSpec(
                    type='clone',
                    vm=object_ref,
                    podSelectionSpec=pod_spec,
                    cloneSpec=clone_spec,
                    cloneName=vm_name,
                    folder=folder_ref
                )

                # get recommended datastores
                recommended_datastores = si.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec)

                # apply storage DRS recommendations
                task = si.content.storageResourceManager.ApplyStorageDrsRecommendation_Task(recommended_datastores.recommendations[0].key)
                salt.utils.vmware.wait_for_task(task, vm_name, 'apply storage DRS recommendations', 5, 'info')
            else:
                # clone the VM/template
                task = object_ref.Clone(folder_ref, vm_name, clone_spec)
                salt.utils.vmware.wait_for_task(task, vm_name, 'clone', 5, 'info')
        else:
            log.info('Creating %s', vm_['name'])

            if host:
                task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref, host_ref)
            else:
                task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref)
            salt.utils.vmware.wait_for_task(task, vm_name, "create", 15, 'info')
    except Exception as exc:
        err_msg = 'Error creating {0}: {1}'.format(vm_['name'], exc)
        log.error(
            err_msg,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return {'Error': err_msg}

    new_vm_ref = salt.utils.vmware.get_mor_by_property(si, vim.VirtualMachine, vm_name, container_ref=container_ref)

    # Find how to power on in CreateVM_Task (if possible), for now this will do
    try:
        if not clone_type and power:
            task = new_vm_ref.PowerOn()
            salt.utils.vmware.wait_for_task(task, vm_name, 'power', 5, 'info')
    except Exception as exc:
        log.info('Powering on the VM threw this exception. Ignoring.')
        log.info(exc)

    # If it a template or if it does not need to be powered on then do not wait for the IP
    out = None
    if not template and power:
        ip = _wait_for_ip(new_vm_ref, wait_for_ip_timeout)
        if ip:
            log.info("[ %s ] IPv4 is: %s", vm_name, ip)
            # ssh or smb using ip and install salt only if deploy is True
            if deploy:
                vm_['key_filename'] = key_filename
                # if specified, prefer ssh_host to the discovered ip address
                if 'ssh_host' not in vm_:
                    vm_['ssh_host'] = ip
                log.info("[ %s ] Deploying to %s", vm_name, vm_['ssh_host'])

                out = __utils__['cloud.bootstrap'](vm_, __opts__)

    data = show_instance(vm_name, call='action')

    if deploy and isinstance(out, dict):
        data['deploy_kwargs'] = out.get('deploy_kwargs', {})

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return data
915055
def create(vm_):
    '''
    

    '''
    name = vm_['name']
    machine = config.get_cloud_config_value(
        'machine', vm_, __opts__, default='')
    vm_['machine'] = machine
    host = config.get_cloud_config_value(
        'host', vm_, __opts__, default=NotImplemented)
    vm_['cwd'] = config.get_cloud_config_value(
        'cwd', vm_, __opts__, default='/')
    vm_['runas'] = config.get_cloud_config_value(
        'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
    vm_['timeout'] = config.get_cloud_config_value(
        'vagrant_up_timeout', vm_, __opts__, default=300)
    vm_['vagrant_provider'] = config.get_cloud_config_value(
        'vagrant_provider', vm_, __opts__, default='')
    vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}

    log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)

    local = salt.client.LocalClient()
    ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
    log.info('response ==> %s', ret[host])

    network_mask = config.get_cloud_config_value(
        'network_mask', vm_, __opts__, default='')
    if 'ssh_host' not in vm_:
        ret = local.cmd(host,
                        'vagrant.get_ssh_config',
                        [name],
                        kwarg={'network_mask': network_mask,
                                'get_private_key': True})[host]
    with tempfile.NamedTemporaryFile() as pks:
        if 'private_key' not in vm_ and ret and ret.get('private_key', False):
            pks.write(ret['private_key'])
            pks.flush()
            log.debug('wrote private key to %s', pks.name)
            vm_['key_filename'] = pks.name
        if 'ssh_host' not in vm_:
            try:
                vm_.setdefault('ssh_username', ret['ssh_username'])
                if ret.get('ip_address'):
                    vm_['ssh_host'] = ret['ip_address']
                else:  # if probe failed or not used, use Vagrant's reported ssh info
                    vm_['ssh_host'] = ret['ssh_host']
                    vm_.setdefault('ssh_port', ret['ssh_port'])
            except (KeyError, TypeError):
                raise SaltInvocationError(
                    'Insufficient SSH addressing information for {}'.format(name))

        log.info('Provisioning machine %s as node %s using ssh %s',
                 machine, name, vm_['ssh_host'])
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        return ret
1188337
def create(vm_):
    '''
    

    '''
    name = vm_['name']
    record = {}
    ret = {}

    # fire creating event
    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(name),
        args={
            'name': name,
            'profile': vm_['profile'],
            'provider': vm_['driver'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    log.debug('Adding %s to cloud cache.', name)
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'xen', vm_['driver']
    )

    # connect to xen
    session = _get_session()

    # determine resource pool
    resource_pool = _determine_resource_pool(session, vm_)

    # determine storage repo
    storage_repo = _determine_storage_repo(session, resource_pool, vm_)

    # build VM
    image = vm_.get('image')
    clone = vm_.get('clone')
    if clone is None:
        clone = True
    log.debug('Clone: %s ', clone)

    # fire event to read new vm properties (requesting)
    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(name),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    # create by cloning template
    if clone:
        _clone_vm(image, name, session)
    else:
        _copy_vm(image, name, session, storage_repo)

    # provision template to vm
    _provision_vm(name, session)
    vm = _get_vm(name, session)

    # start vm
    start(name, None, session)

    # get new VM
    vm = _get_vm(name, session)

    # wait for vm to report IP via guest tools
    _wait_for_ip(name, session)

    # set static IP if configured
    _set_static_ip(name, session, vm_)

    # if not deploying salt then exit
    deploy = vm_.get('deploy', True)
    log.debug('delopy is set to %s', deploy)
    if deploy:
        record = session.xenapi.VM.get_record(vm)
        if record is not None:
            _deploy_salt_minion(name, session, vm_)
    else:
        log.debug(
            'The Salt minion will not be installed, deploy: %s',
            vm_['deploy']
        )
    record = session.xenapi.VM.get_record(vm)
    ret = show_instance(name)
    ret.update({'extra': record})

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(name),
        args={
            'name': name,
            'profile': vm_['profile'],
            'provider': vm_['driver'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return ret
1016482
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if (vm_['profile'] and
           config.is_profile_configured(__opts__,
                                        (__active_provider_name__ or
                                         'oneandone'),
                                        vm_['profile']) is False):
            return False
    except AttributeError:
        pass

    data = None
    conn = get_conn()
    hdds = []

    # Assemble the composite server object.
    server = _get_server(vm_)

    if not bool(server.specs['hardware']['fixed_instance_size_id'])\
        and not bool(server.specs['server_type'] == 'baremetal'):
        # Assemble the hdds object.
        hdds = _get_hdds(vm_)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={'name': vm_['name']},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        data = conn.create_server(server=server, hdds=hdds)

        _wait_for_completion(conn,
                             get_wait_timeout(vm_),
                             data['id'])
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on 1and1\n\n'
            'The following exception was thrown by the 1and1 library '
            'when trying to run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    vm_['server_id'] = data['id']
    password = data['first_password']

    def __query_node_data(vm_, data):
        '''
        Query node data until node becomes available.
        '''
        running = False
        try:
            data = show_instance(vm_['name'], 'action')
            if not data:
                return False
            log.debug(
                'Loaded node data for %s:\nname: %s\nstate: %s',
                vm_['name'],
                pprint.pformat(data['name']),
                data['status']['state']
            )
        except Exception as err:
            log.error(
                'Failed to get nodes list: %s', err,
                # Show the trackback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
            # Trigger a failure in the wait for IP function
            return False

        running = data['status']['state'].lower() == 'powered_on'
        if not running:
            # Still not running, trigger another iteration
            return

        vm_['ssh_host'] = data['ips'][0]['ip']

        return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc.message))

    log.debug('VM is now running')
    log.info('Created Cloud VM %s', vm_)
    log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args={
            'name': vm_['name'],
            'profile': vm_['profile'],
            'provider': vm_['driver'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    if 'ssh_host' in vm_:
        vm_['password'] = password
        vm_['key_filename'] = get_key_filename(vm_)
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        ret.update(data)
        return ret
    else:
        raise SaltCloudSystemExit('A valid IP address was not found.')
285139
def create(self, name, provider='AwsEKS'):
        
        # ----- Create K8s cluster on provider -------
        # Create cluster object
        Cluster = getattr(providers, provider)
        cluster = Cluster(name=name, ssh_key_name='zsailer')
        cluster.create()

        # -------- Add cluster to kubeconf -----------

        # Add cluster to kubeconf
        self.kubeconf.open()
        self.kubeconf.add_cluster(
            cluster.cluster_name,
            server=cluster.endpoint_url,
            certificate_authority_data=cluster.ca_cert
        )

        # Add a user to kubeconf
        self.kubeconf.add_user(name)

        # Add a user exec call for this provider.
        self.kubeconf.add_to_user(
            name,
            **cluster.kube_user_data
        )

        # Add context mapping user to cluster.
        self.kubeconf.add_context(
            name,
            cluster_name=cluster.cluster_name,
            user_name=cluster.name
        )

        # Switch contexts.
        self.kubeconf.set_current_context(name)

        # Commit changes to file.
        self.kubeconf.close()
        
        # ------ Setup autorization -------
        kubectl('apply', input=cluster.get_auth_config())

        # -------- Setup Storage ----------
        kubectl('delete', 'storageclass', 'gp2')        
        kubectl('apply', input=cluster.get_storage_config())

        # ------- setup helm locally ------
        kubectl(
            '--namespace',
            'kube-system',
            'create',
            'serviceaccount',
            'tiller'
        )

        kubectl(
            'create',
            'clusterrolebinding',
            'tiller',
            '--clusterrole=cluster-admin',
            '--serviceaccount=kube-system:tiller'
        )

        # -------- Initialize Helm -----------
        helm(
            'init',
            '--service-account',
            'tiller'
        )

        # --------- Secure Helm --------------
        kubectl(
            'patch',
            'deployment',
            'tiller-deploy',
            namespace='kube-system',
            type='json',
            patch='[{"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["/tiller", "--listen=localhost:44134"]}]'
        )
30436
def create_node(vm_, newid):
    '''
    
    '''
    newnode = {}

    if 'technology' not in vm_:
        vm_['technology'] = 'openvz'  # default virt tech if none is given

    if vm_['technology'] not in ['qemu', 'openvz', 'lxc']:
        # Wrong VM type given
        log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)')
        raise SaltCloudExecutionFailure

    if 'host' not in vm_:
        # Use globally configured/default location
        vm_['host'] = config.get_cloud_config_value(
            'default_host', get_configured_provider(), __opts__, search_global=False
        )

    if vm_['host'] is None:
        # No location given for the profile
        log.error('No host given to create this VM on')
        raise SaltCloudExecutionFailure

    # Required by both OpenVZ and Qemu (KVM)
    vmhost = vm_['host']
    newnode['vmid'] = newid

    for prop in 'cpuunits', 'description', 'memory', 'onboot':
        if prop in vm_:  # if the property is set, use it for the VM request
            newnode[prop] = vm_[prop]

    if vm_['technology'] == 'openvz':
        # OpenVZ related settings, using non-default names:
        newnode['hostname'] = vm_['name']
        newnode['ostemplate'] = vm_['image']

        # optional VZ settings
        for prop in ['cpus', 'disk', 'ip_address', 'nameserver',
                     'password', 'swap', 'poolid', 'storage']:
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

    elif vm_['technology'] == 'lxc':
        # LXC related settings, using non-default names:
        newnode['hostname'] = vm_['name']
        newnode['ostemplate'] = vm_['image']

        static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory',
                        'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs')
        for prop in _get_properties('/nodes/{node}/lxc',
                                    'POST',
                                    static_props):
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

        if 'pubkey' in vm_:
            newnode['ssh-public-keys'] = vm_['pubkey']

        # inform user the "disk" option is not supported for LXC hosts
        if 'disk' in vm_:
            log.warning('The "disk" option is not supported for LXC hosts and was ignored')

        # LXC specific network config
        # OpenVZ allowed specifying IP and gateway. To ease migration from
        # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config.
        # If you need more control, please use the net0 option directly.
        # This also assumes a /24 subnet.
        if 'ip_address' in vm_ and 'net0' not in vm_:
            newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth'

            # gateway is optional and does not assume a default
            if 'gw' in vm_:
                newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw']

    elif vm_['technology'] == 'qemu':
        # optional Qemu settings
        static_props = (
            'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0')
        for prop in _get_properties('/nodes/{node}/qemu',
                                    'POST',
                                    static_props):
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

    # The node is ready. Lets request it to be added
    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)),
        },
        sock_dir=__opts__['sock_dir'],
    )

    log.debug('Preparing to generate a node using these parameters: %s ', newnode)
    if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu':
        postParams = {}
        postParams['newid'] = newnode['vmid']

        for prop in 'description', 'format', 'full', 'name':
            if 'clone_' + prop in vm_:  # if the property is set, use it for the VM request
                postParams[prop] = vm_['clone_' + prop]

        if 'host' in vm_:
            postParams['target'] = vm_['host']

        try:
            int(vm_['clone_from'])
        except ValueError:
            if ':' in vm_['clone_from']:
                vmhost = vm_['clone_from'].split(':')[0]
                vm_['clone_from'] = vm_['clone_from'].split(':')[1]

        node = query('post', 'nodes/{0}/qemu/{1}/clone'.format(
            vmhost, vm_['clone_from']), postParams)
    else:
        node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode)
    return _parse_proxmox_upid(node, vm_)
1129919
def create(vm_):
    '''
    
    '''
    clone_strategy = vm_.get('clone_strategy') or 'full'

    if clone_strategy not in ('quick', 'full'):
        raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))

    ip_source = vm_.get('ip_source') or 'ip-learning'

    if ip_source not in ('ip-learning', 'qemu-agent'):
        raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))

    validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True

    log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)

    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'libvirt',
                                                           vm_['profile']) is False:
            return False
    except AttributeError:
        pass

    # TODO: check name qemu/libvirt will choke on some characters (like '/')?
    name = vm_['name']

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(name),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined key_filename \'{0}\' does not exist'.format(
                key_filename
            )
        )
    vm_['key_filename'] = key_filename
    # wait_for_instance requires private_key
    vm_['private_key'] = key_filename

    cleanup = []
    try:
        # clone the vm
        base = vm_['base_domain']
        conn = __get_conn(vm_['url'])

        try:
            # for idempotency the salt-bootstrap needs -F argument
            #  script_args: -F
            clone_domain = conn.lookupByName(name)
        except libvirtError as e:
            domain = conn.lookupByName(base)
            # TODO: ensure base is shut down before cloning
            xml = domain.XMLDesc(0)

            kwargs = {
                'name': name,
                'base_domain': base,
            }

            __utils__['cloud.fire_event'](
                'event',
                'requesting instance',
                'salt/cloud/{0}/requesting'.format(name),
                args={
                    'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
                },
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport']
            )

            log.debug("Source machine XML '%s'", xml)

            domain_xml = ElementTree.fromstring(xml)
            domain_xml.find('./name').text = name
            if domain_xml.find('./description') is None:
                description_elem = ElementTree.Element('description')
                domain_xml.insert(0, description_elem)
            description = domain_xml.find('./description')
            description.text = "Cloned from {0}".format(base)
            domain_xml.remove(domain_xml.find('./uuid'))

            for iface_xml in domain_xml.findall('./devices/interface'):
                iface_xml.remove(iface_xml.find('./mac'))
                # enable IP learning, this might be a default behaviour...
                # Don't always enable since it can cause problems through libvirt-4.5
                if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
                    iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))

            # If a qemu agent is defined we need to fix the path to its socket
            # <channel type='unix'>
            #   <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
            #   <target type='virtio' name='org.qemu.guest_agent.0'/>
            #   <address type='virtio-serial' controller='0' bus='0' port='2'/>
            # </channel>
            for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
                #  is org.qemu.guest_agent.0 an option?
                if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
                    source_element = agent_xml.find("""./source[@mode='bind']""")
                    # see if there is a path element that needs rewriting
                    if source_element and 'path' in source_element.attrib:
                        path = source_element.attrib['path']
                        new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
                        log.debug("Rewriting agent socket path to %s", new_path)
                        source_element.attrib['path'] = new_path

            for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
                # print "Disk: ", ElementTree.tostring(disk)
                # check if we can clone
                driver = disk.find("./driver[@name='qemu']")
                if driver is None:
                    # Err on the safe side
                    raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
                disk_type = driver.attrib.get('type')
                log.info("disk attributes %s", disk.attrib)
                if disk_type == 'qcow2':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    if clone_strategy == 'quick':
                        new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
                    else:
                        new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                elif disk_type == 'raw':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    # TODO: more control on the cloned disk type
                    new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                else:
                    raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))

            clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
            log.debug("Clone XML '%s'", clone_xml)

            validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
            clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)

            cleanup.append({'what': 'domain', 'item': clone_domain})
            clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)

        log.debug("VM '%s'", vm_)

        if ip_source == 'qemu-agent':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
        elif ip_source == 'ip-learning':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE

        address = salt.utils.cloud.wait_for_ip(
            get_domain_ip,
            update_args=(clone_domain, 0, ip_source),
            timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
            interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )

        log.info('Address = %s', address)

        vm_['ssh_host'] = address

        # the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
        # salt-cloud -u is your friend
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)

        __utils__['cloud.fire_event'](
            'event',
            'created instance',
            'salt/cloud/{0}/created'.format(name),
            args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        return ret
    except Exception as e:  # pylint: disable=broad-except
        do_cleanup(cleanup)
        # throw the root cause after cleanup
        raise e
1096480
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'qingcloud',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])

    # params
    params = {
        'action': 'RunInstances',
        'instance_name': vm_['name'],
        'zone': _get_location(vm_),
        'instance_type': _get_size(vm_),
        'image_id': _get_image(vm_),
        'vxnets.1': vm_['vxnets'],
        'login_mode': vm_['login_mode'],
        'login_keypair': vm_['login_keypair'],
    }

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', params, list(params)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = query(params)
    new_instance_id = result['instances'][0]

    try:
        data = salt.utils.cloud.wait_for_ip(
            _query_node_data,
            update_args=(new_instance_id,),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60
            ),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10
            ),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    private_ip = data['private_ips'][0]

    log.debug('VM %s is now running', private_ip)

    vm_['ssh_host'] = private_ip

    # The instance is booted and accessible, let's Salt it!
    __utils__['cloud.bootstrap'](vm_, __opts__)

    log.info('Created Cloud VM \'%s\'', vm_['name'])

    log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return data
492176
def create_node_group(self):
        
        self.create_stack(
            self.node_group_name,
            'amazon-eks-nodegroup.yaml',
            capabilities=['CAPABILITY_IAM'],
            parameters=define_parameters(
                ClusterName=self.cluster_name,
                ClusterControlPlaneSecurityGroup=self.security_groups,
                Subnets=self.subnet_ids,
                VpcId=self.vpc_ids,
                KeyName=self.ssh_key_name,
                NodeAutoScalingGroupMaxSize="1",
                NodeVolumeSize="100",
                NodeImageId="ami-0a54c984b9f908c81",
                NodeGroupName=f"{self.name} OnDemand Nodes"
            )
        )
779815
def create(name, profile):
    '''
    
    '''
    cmd = 'salt-cloud --out json -p {0} {1}'.format(profile, name)
    out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
    try:
        ret = salt.utils.json.loads(out)
    except ValueError:
        ret = {}
    return ret