Attach disk to vm.

    disk can be a disk name, or ID
    vm can be a vm name, or ID
332884
def attach(gandi, disk, vm, position, read_only, background, force):
    
    if not force:
        proceed = click.confirm("Are you sure you want to attach disk '%s'"
                                " to vm '%s'?" % (disk, vm))
        if not proceed:
            return

    disk_info = gandi.disk.info(disk)
    attached = disk_info.get('vms_id', False)
    if attached and not force:
        gandi.echo('This disk is still attached')
        proceed = click.confirm('Are you sure you want to detach %s?' % disk)

        if not proceed:
            return

    result = gandi.disk.attach(disk, vm, background, position, read_only)
    if background and result:
        gandi.pretty_echo(result)

    return result
405379
def attach_volume(self, volume_id, instance_id, device):
        """"""
        query = self.query_factory(
            action="AttachVolume", creds=self.creds, endpoint=self.endpoint,
            other_params={"VolumeId": volume_id, "InstanceId": instance_id,
                          "Device": device})
        d = query.submit()
        return d.addCallback(self.parser.attach_volume)
858265
def save_linked_hdds_info(self):
        

        hdd_table = []
        if self.linked_clone:
            if os.path.exists(self.working_dir):
                hdd_files = yield from self._get_all_hdd_files()
                vm_info = yield from self._get_vm_info()
                for entry, value in vm_info.items():
                    match = re.search("^([\s\w]+)\-(\d)\-(\d)$", entry)  # match Controller-PortNumber-DeviceNumber entry
                    if match:
                        controller = match.group(1)
                        port = match.group(2)
                        device = match.group(3)
                        if value in hdd_files and os.path.exists(os.path.join(self.working_dir, self._vmname, "Snapshots", os.path.basename(value))):
                            log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
                                                                                                                       id=self.id,
                                                                                                                       controller=controller,
                                                                                                                       port=port,
                                                                                                                       device=device))
                            hdd_table.append(
                                {
                                    "hdd": os.path.basename(value),
                                    "controller": controller,
                                    "port": port,
                                    "device": device,
                                }
                            )

            if hdd_table:
                try:
                    hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
                    with open(hdd_info_file, "w", encoding="utf-8") as f:
                        json.dump(hdd_table, f, indent=4)
                except OSError as e:
                    log.warning("VirtualBox VM '{name}' [{id}] could not write HHD info file: {error}".format(name=self.name,
                                                                                                              id=self.id,
                                                                                                              error=e.strerror))

        return hdd_table
205819
def show_disk(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_disks action must be called with -a or --action.'
        )

    ret = {}
    params = {
        'Action': 'DescribeInstanceDisks',
        'InstanceId': name
    }
    items = query(params=params)

    for disk in items['Disks']['Disk']:
        ret[disk['DiskId']] = {}
        for item in disk:
            ret[disk['DiskId']][item] = six.text_type(disk[item])

    return ret
1110495
def find_vm_by_name(self, si, path, name):
        
        return self.find_obj_by_path(si, path, name, self.VM)
76224
def attach_model(subscription, rgname, vmssvm_model, diskname, lun):
    ''''''
    disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + \
        '/providers/Microsoft.Compute/disks/' + diskname
    disk_model = {'lun': lun, 'createOption': 'Attach', 'caching': 'None',
                  'managedDisk': {'storageAccountType': 'Standard_LRS', 'id': disk_id}}
    vmssvm_model['properties']['storageProfile']['dataDisks'].append(
        disk_model)
    return vmssvm_model
105101
public OvhVolume project_serviceName_volume_volumeId_attach_POST(String serviceName, String volumeId, String instanceId) throws IOException {
		String qPath = "/cloud/project/{serviceName}/volume/{volumeId}/attach";
		StringBuilder sb = path(qPath, serviceName, volumeId);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "instanceId", instanceId);
		String resp = exec(qPath, "POST", sb.toString(), o);
		return convertTo(resp, OvhVolume.class);
	}
876441
def set_disk0(self, disk0):
        

        yield from self._hypervisor.send('vm set_disk0 "{name}" {disk0}'.format(name=self._name, disk0=disk0))

        log.info('Router "{name}" [{id}]: disk0 updated from {old_disk0}MB to {new_disk0}MB'.format(name=self._name,
                                                                                                    id=self._id,
                                                                                                    old_disk0=self._disk0,
                                                                                                    new_disk0=disk0))
        self._disk0 = disk0
1363615
def AddNewVolumeToInstance(self, instance_id, vol_size_gb):
    
    assert(vol_size_gb >= 1)
    if vol_size_gb > 1000: # probably spending too much if you go bigger
      raise RuntimeError('Adding volumes this large has not been tested.')
    instance = self.__GetInstanceById(instance_id)
    assert(instance)
    # select an unused device
    # see http://askubuntu.com/questions/47617/
    # how-to-attach-new-ebs-volume-to-ubuntu-machine-on-aws
    potential_device_names = ['/dev/xvdf',
                              '/dev/xvdg',
                              '/dev/xvdh', 
                              '/dev/xvdi']
    device_name = None
    for name in potential_device_names:
      if not self.DeviceExists(name, instance):
        device_name = name
        break
    if not device_name:
      raise RuntimeError('No suitable device names available')
    # Attach volume
    volume = self.ec2.create_volume(vol_size_gb, instance.placement)
    volume.attach(instance.id, device_name)
    # wait for volume to attach
    core.WaitForVolumeAttached(volume)
    while not self.DeviceExists(device_name, instance):
        logging.info( 'waiting for device to be attached...')
        time.sleep(5)
    assert(volume.id)
    assert(volume.attach_data.device == device_name)
    # format file system, mount the file system, update fstab to automount
    hostname = instance.dns_name
    add_ebs_volume_playbook = pkg_resources.resource_filename(__name__,
      'ami/playbooks/workstation/add_ebs_volume.yml')
    extra_vars = {}
    extra_vars['volume_name'] = volume.id
    extra_vars['volume_device'] = device_name
    assert(core.RunPlaybookOnHost(add_ebs_volume_playbook, hostname, 
                                  self.ssh_key, extra_vars))      
    return volume.id
1273914
private boolean attachVolumes() {

		// If volume is found in map, it has been successfully created (no need to check here)
		for( Map.Entry<String,String> entry : this.storageIdToVolumeId.entrySet()) {

			String volumeId = entry.getValue();
			String storageId = entry.getKey();

			// Give a name to the volume before attaching
			String nameTemplate = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_NAME_PREFIX);
			String name = Ec2IaasHandler.expandVolumeName(
					nameTemplate, this.applicationName, this.scopedInstance.getName());
			if(Utils.isEmptyOrWhitespaces(name)) name = "Created by Roboconf for " + this.tagName;
			tagResource(volumeId, name);

			// Attach volume now
			String mountPoint = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_MOUNT_POINT_PREFIX);
			if(Utils.isEmptyOrWhitespaces(mountPoint)) mountPoint = "/dev/sdf";

			AttachVolumeRequest attachRequest = new AttachVolumeRequest()
				.withInstanceId(this.machineId)
				.withDevice(mountPoint)
				.withVolumeId(volumeId);

			try {
				this.ec2Api.attachVolume(attachRequest);
			} catch(Exception e) {
				this.logger.warning("EBS Volume attachment error: " + e);
			}

			// Set deleteOnTermination flag ?
			if(Boolean.parseBoolean(Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_DELETE_OT_PREFIX))) {
				EbsInstanceBlockDeviceSpecification ebsSpecification = new EbsInstanceBlockDeviceSpecification()
					.withVolumeId(volumeId)
					.withDeleteOnTermination(true);

				InstanceBlockDeviceMappingSpecification mappingSpecification = new InstanceBlockDeviceMappingSpecification()
					.withDeviceName(mountPoint)
					.withEbs(ebsSpecification);

				ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest()
					.withInstanceId(this.machineId)
					.withBlockDeviceMappings(mappingSpecification);

				this.ec2Api.modifyInstanceAttribute(request);
			}
		}

		return true;
	}
921995
def detach_disk(name=None, kwargs=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The detach_Disk action must be called with -a or --action.'
        )

    if not name:
        log.error(
            'Must specify an instance name.'
        )
        return False
    if not kwargs or 'disk_name' not in kwargs:
        log.error(
            'Must specify a disk_name to detach.'
        )
        return False

    node_name = name
    disk_name = kwargs['disk_name']

    conn = get_conn()
    node = conn.ex_get_node(node_name)
    disk = conn.ex_get_volume(disk_name)

    __utils__['cloud.fire_event'](
        'event',
        'detach disk',
        'salt/cloud/disk/detaching',
        args={
            'name': node_name,
            'disk_name': disk_name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = conn.detach_volume(disk, node)

    __utils__['cloud.fire_event'](
        'event',
        'detached disk',
        'salt/cloud/disk/detached',
        args={
            'name': node_name,
            'disk_name': disk_name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result
1068125
def volume_create_attach(name, call=None, **kwargs):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The create_attach_volumes action must be called with '
            '-a or --action.'
        )

    if type(kwargs['volumes']) is str:
        volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
    else:
        volumes = kwargs['volumes']

    ret = []
    for volume in volumes:
        created = False

        volume_dict = {
            'name': volume['name'],
        }
        if 'volume_id' in volume:
            volume_dict['volume_id'] = volume['volume_id']
        elif 'snapshot' in volume:
            volume_dict['snapshot'] = volume['snapshot']
        else:
            volume_dict['size'] = volume['size']

            if 'type' in volume:
                volume_dict['type'] = volume['type']
            if 'iops' in volume:
                volume_dict['iops'] = volume['iops']

        if 'id' not in volume_dict:
            created_volume = create_volume(**volume_dict)
            created = True
            volume_dict.update(created_volume)

        attach = attach_volume(
            name=volume['name'],
            server_name=name,
            device=volume.get('device', None),
            call='action'
        )

        if attach:
            msg = (
                '{0} attached to {1} (aka {2})'.format(
                    volume_dict['id'],
                    name,
                    volume_dict['name'],
                )
            )
            log.info(msg)
            ret.append(msg)
    return ret
1246867
def attach_storage(self, server, storage, storage_type, address):
        
        body = {'storage_device': {}}
        if storage:
            body['storage_device']['storage'] = str(storage)

        if storage_type:
            body['storage_device']['type'] = storage_type

        if address:
            body['storage_device']['address'] = address

        url = '/server/{0}/storage/attach'.format(server)
        res = self.post_request(url, body)
        return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self)
477014
def vm_info(name, quiet=False):
    '''
    
    '''
    data = query(quiet=True)
    return _find_vm(name, data, quiet)
1232717
def attach(self, to_linode, config=None):
        
        result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self,
                data={
                    "linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode,
                    "config": None if not config else config.id if issubclass(type(config), Base) else config,
        })

        if not 'id' in result:
            raise UnexpectedResponseError('Unexpected response when attaching volume!', json=result)

        self._populate(result)
        return True
640621
def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs):
    '''
    
    '''
    base_dir = disk.get('pool', None)
    if hypervisor in ['qemu', 'kvm', 'xen']:
        # Compute the base directory from the pool property. We may have either a path
        # or a libvirt pool name there.
        # If the pool is a known libvirt one with a target path, use it as target path
        if not base_dir:
            base_dir = _get_images_dir()
        else:
            if not base_dir.startswith('/'):
                # The pool seems not to be a path, lookup for pool infos
                infos = pool_info(base_dir, **kwargs)
                pool = infos[base_dir] if base_dir in infos else None
                if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'):
                    raise CommandExecutionError(
                                'Unable to create new disk {0}, specified pool {1} does not exist '
                                'or is unsupported'.format(disk['name'], base_dir))
                base_dir = pool['target_path']
    if hypervisor == 'bhyve' and vm_name:
        disk['filename'] = '{0}.{1}'.format(vm_name, disk['name'])
        disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename'])
    elif vm_name:
        # Compute the filename and source file properties if possible
        disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format'])
        disk['source_file'] = os.path.join(base_dir, disk['filename'])
1191620
def attach(gandi, ip, vm, background, force):
    
    try:
        ip_ = gandi.ip.info(ip)
        vm_ = gandi.iaas.info(vm)
    except UsageError:
        gandi.error("Can't find this ip %s" % ip)

    iface = gandi.iface.info(ip_['iface_id'])
    if iface.get('vm_id'):
        if vm_ and iface['vm_id'] == vm_.get('id'):
            gandi.echo('This ip is already attached to this vm.')
            return

        if not force:
            proceed = click.confirm('Are you sure you want to detach'
                                    ' %s from vm %s' %
                                    (ip_['ip'], iface['vm_id']))
            if not proceed:
                return

    return gandi.ip.attach(ip, vm, background, force)