create an ec2 reservation if one doesn't already exist and call
        start_instance. Update instance attributes to the newly created instance
        attributes
11330
def start(self):
        
        if self.instance is None:
            reservation = self.ec2_backend.add_instances(
                image_id=self.ami_id,
                count=1,
                user_data="",
                security_group_names=[],
                security_group_ids=self.security_group_ids,
                instance_type=self.instance_type,
                key_name=self.ssh_keyname,
                ebs_optimized=self.ebs_optimized,
                subnet_id=self.subnet_id,
                associate_public_ip=self.associate_public_ip,
            )
            self.instance = reservation.instances[0]
            self.reported_os = {
                'Family': 'rhel (fixed)',
                'Name': 'amazon (fixed)',
                'Version': '2016.03 (fixed)'
            }
            self.platform = self.instance.platform
            self.security_group_ids = self.instance.security_groups
            self.architecture = self.instance.architecture
            self.virtualization_type = self.instance.virtualization_type
            self.subnet_id = self.instance.subnet_id
            self.root_device_type = self.instance.root_device_type

        self.ec2_backend.start_instances([self.instance.id])
504632
def update_instances(self):
        
        self.log.debug('Updating EC2Instances for {}/{}'.format(self.account.account_name, self.region))
        ec2 = self.session.resource('ec2', region_name=self.region)

        try:
            existing_instances = EC2Instance.get_all(self.account, self.region)
            instances = {}
            api_instances = {x.id: x for x in ec2.instances.all()}

            try:
                for instance_id, data in api_instances.items():
                    if data.instance_id in existing_instances:
                        instance = existing_instances[instance_id]

                        if data.state['Name'] not in ('terminated', 'shutting-down'):
                            instances[instance_id] = instance

                            # Add object to transaction if it changed
                            if instance.update(data):
                                self.log.debug('Updating info for instance {} in {}/{}'.format(
                                    instance.resource.resource_id,
                                    self.account.account_name,
                                    self.region
                                ))
                                db.session.add(instance.resource)
                    else:
                        # New instance, if its not in state=terminated
                        if data.state['Name'] in ('terminated', 'shutting-down'):
                            continue

                        tags = {tag['Key']: tag['Value'] for tag in data.tags or {}}
                        properties = {
                            'launch_date': to_utc_date(data.launch_time).isoformat(),
                            'state': data.state['Name'],
                            'instance_type': data.instance_type,
                            'public_ip': getattr(data, 'public_ip_address', None),
                            'public_dns': getattr(data, 'public_dns_address', None),
                            'created': isoformat(datetime.now())
                        }

                        instance = EC2Instance.create(
                            data.instance_id,
                            account_id=self.account.account_id,
                            location=self.region,
                            properties=properties,
                            tags=tags
                        )

                        instances[instance.resource.resource_id] = instance
                        self.log.debug('Added new EC2Instance {}/{}/{}'.format(
                            self.account.account_name,
                            self.region,
                            instance.resource.resource_id
                        ))

                # Check for deleted instances
                ik = set(list(instances.keys()))
                eik = set(list(existing_instances.keys()))

                for instanceID in eik - ik:
                    db.session.delete(existing_instances[instanceID].resource)
                    self.log.debug('Deleted EC2Instance {}/{}/{}'.format(
                        self.account.account_name,
                        self.region,
                        instanceID
                    ))

                db.session.commit()
            except:
                db.session.rollback()
                raise
        finally:
            del ec2
103680
def create(self, instance):
        
        with self.flushing():
            if instance.id is None:
                instance.id = self.new_object_id()
            self.session.add(instance)
        return instance
861125
def rename(self, name):
        """"""
        self.ec2.create_tags(Resources = [self.instance_id],
                             Tags      = [{'Key':   'Name',
                                           'Value':  name}])
        self.refresh_info()
9056
def update_instances
      instance_group_updater = InstanceGroupUpdater.new(
        ip_provider: @deployment_planner.ip_provider,
        instance_group: @instance_group,
        disk_manager: @disk_manager,
        template_blob_cache: @template_blob_cache,
        dns_encoder: @dns_encoder,
        link_provider_intents: @deployment_planner.link_provider_intents,
      )
      instance_group_updater.update
    end
439801
def _build_cached_instances(self):
        
        connection = self._connect()
        reservations = connection.get_all_reservations()
        cached_instances = {}
        for rs in reservations:
            for vm in rs.instances:
                cached_instances[vm.id] = vm
        return cached_instances
271026
def restart(self, instance_id):
        
        try:
            if not self._paused:
                log.debug("node %s is not paused, can't restart", instance_id)
                return
            self._paused = False
            result = self._subscription._sms.start_role(
                service_name=self._cloud_service._name,
                deployment_name=self._cloud_service._name,
                role_name=instance_id)
            self._subscription._wait_result(result)
        except Exception as exc:
            log.error('error restarting instance %s: %s', instance_id, exc)
            raise
        log.debug('restarted instance(instance_id=%s)', instance_id)
8671
def start(instance_id, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The stop action must be called with -a or --action.'
        )

    log.info('Starting instance %s', instance_id)

    params = {
        'action': 'StartInstances',
        'zone': _get_specified_zone(provider=get_configured_provider()),
        'instances.1': instance_id,
    }
    result = query(params)

    return result
613711
def create(vm_=None, call=None):
    '''
    
    '''
    if call:
        raise SaltCloudSystemExit(
            'You cannot create an instance with -a or -f.'
        )

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

    # Check for private_key and keyfile name for bootstrapping new instances
    deploy = config.get_cloud_config_value(
        'deploy', vm_, __opts__, default=True
    )
    win_password = config.get_cloud_config_value(
        'win_password', vm_, __opts__, default=''
    )
    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    if deploy:
        # The private_key and keyname settings are only needed for bootstrapping
        # new instances when deploy is True
        _validate_key_path_and_mode(key_filename)

    __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']
    )
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'ec2', vm_['driver']
    )

    vm_['key_filename'] = key_filename
    # wait_for_instance requires private_key
    vm_['private_key'] = key_filename

    # Get SSH Gateway config early to verify the private_key,
    # if used, exists or not. We don't want to deploy an instance
    # and not be able to access it via the gateway.
    vm_['gateway'] = get_ssh_gateway_config(vm_)

    location = get_location(vm_)
    vm_['location'] = location

    log.info('Creating Cloud VM %s in %s', vm_['name'], location)
    vm_['usernames'] = salt.utils.cloud.ssh_usernames(
        vm_,
        __opts__,
        default_users=(
            'ec2-user',  # Amazon Linux, Fedora, RHEL; FreeBSD
            'centos',    # CentOS AMIs from AWS Marketplace
            'ubuntu',    # Ubuntu
            'admin',     # Debian GNU/Linux
            'bitnami',   # BitNami AMIs
            'root'       # Last resort, default user on RHEL 5, SUSE
        )
    )

    if 'instance_id' in vm_:
        # This was probably created via another process, and doesn't have
        # things like salt keys created yet, so let's create them now.
        if 'pub_key' not in vm_ and 'priv_key' not in vm_:
            log.debug('Generating minion keys for \'%s\'', vm_['name'])
            vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
                salt.config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    __opts__
                )
            )
    else:
        # Put together all of the information required to request the instance,
        # and then fire off the request for it
        if keyname(vm_) is None:
            raise SaltCloudSystemExit(
                'The required \'keyname\' configuration setting is missing from the '
                '\'ec2\' driver.'
            )

        data, vm_ = request_instance(vm_, location)

        # If data is a str, it's an error
        if isinstance(data, six.string_types):
            log.error('Error requesting instance: %s', data)
            return {}

        # Pull the instance ID, valid for both spot and normal instances

        # Multiple instances may have been spun up, get all their IDs
        vm_['instance_id_list'] = []
        for instance in data:
            vm_['instance_id_list'].append(instance['instanceId'])

        vm_['instance_id'] = vm_['instance_id_list'].pop()
        if vm_['instance_id_list']:
            # Multiple instances were spun up, get one now, and queue the rest
            queue_instances(vm_['instance_id_list'])

    # Wait for vital information, such as IP addresses, to be available
    # for the new instance
    data = query_instance(vm_)

    # Now that the instance is available, tag it appropriately. Should
    # mitigate race conditions with tags
    tags = config.get_cloud_config_value('tag',
                                         vm_,
                                         __opts__,
                                         {},
                                         search_global=False)
    if not isinstance(tags, dict):
        raise SaltCloudConfigError(
            '\'tag\' should be a dict.'
        )

    for value in six.itervalues(tags):
        if not isinstance(value, six.string_types):
            raise SaltCloudConfigError(
                '\'tag\' values must be strings. Try quoting the values. '
                'e.g. "2013-09-19T20:09:46Z".'
            )

    tags['Name'] = vm_['name']

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

    salt.utils.cloud.wait_for_fun(
        set_tags,
        timeout=30,
        name=vm_['name'],
        tags=tags,
        instance_id=vm_['instance_id'],
        call='action',
        location=location
    )

    # Once instance tags are set, tag the spot request if configured
    if 'spot_config' in vm_ and 'tag' in vm_['spot_config']:

        if not isinstance(vm_['spot_config']['tag'], dict):
            raise SaltCloudConfigError(
                '\'tag\' should be a dict.'
            )

        for value in six.itervalues(vm_['spot_config']['tag']):
            if not isinstance(value, str):
                raise SaltCloudConfigError(
                    '\'tag\' values must be strings. Try quoting the values. '
                    'e.g. "2013-09-19T20:09:46Z".'
                )

        spot_request_tags = {}

        if 'spotRequestId' not in vm_:
            raise SaltCloudConfigError('Failed to find spotRequestId')

        sir_id = vm_['spotRequestId']

        spot_request_tags['Name'] = vm_['name']

        for k, v in six.iteritems(vm_['spot_config']['tag']):
            spot_request_tags[k] = v

        __utils__['cloud.fire_event'](
            'event',
            'setting tags',
            'salt/cloud/spot_request_{0}/tagging'.format(sir_id),
            args={'tags': spot_request_tags},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        salt.utils.cloud.wait_for_fun(
            set_tags,
            timeout=30,
            name=vm_['name'],
            tags=spot_request_tags,
            instance_id=sir_id,
            call='action',
            location=location
        )

    network_interfaces = config.get_cloud_config_value(
        'network_interfaces',
        vm_,
        __opts__,
        search_global=False
    )

    if network_interfaces:
        _update_enis(network_interfaces, data, vm_)

    # At this point, the node is created and tagged, and now needs to be
    # bootstrapped, once the necessary port is available.
    log.info('Created node %s', vm_['name'])

    instance = data[0]['instancesSet']['item']

    # Wait for the necessary port to become available to bootstrap
    if ssh_interface(vm_) == 'private_ips':
        ip_address = instance['privateIpAddress']
        log.info('Salt node data. Private_ip: %s', ip_address)
    else:
        ip_address = instance['ipAddress']
        log.info('Salt node data. Public_ip: %s', ip_address)
    vm_['ssh_host'] = ip_address

    if salt.utils.cloud.get_salt_interface(vm_, __opts__) == 'private_ips':
        salt_ip_address = instance['privateIpAddress']
        log.info('Salt interface set to: %s', salt_ip_address)
    else:
        salt_ip_address = instance['ipAddress']
        log.debug('Salt interface set to: %s', salt_ip_address)
    vm_['salt_host'] = salt_ip_address

    if deploy:
        display_ssh_output = config.get_cloud_config_value(
            'display_ssh_output', vm_, __opts__, default=True
        )

        vm_ = wait_for_instance(
            vm_, data, ip_address, display_ssh_output
        )

    # The instance is booted and accessible, let's Salt it!
    ret = instance.copy()

    # Get ANY defined volumes settings, merging data, in the following order
    # 1. VM config
    # 2. Profile config
    # 3. Global configuration
    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )
    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args={'volumes': volumes},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        created = create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'zone': ret['placement']['availabilityZone'],
                'instance_id': ret['instanceId'],
                'del_all_vols_on_destroy': vm_.get('del_all_vols_on_destroy', False)
            },
            call='action'
        )
        ret['Attached Volumes'] = created

    # Associate instance with a ssm document, if present
    ssm_document = config.get_cloud_config_value(
        'ssm_document', vm_, __opts__, None, search_global=False
    )
    if ssm_document:
        log.debug('Associating with ssm document: %s', ssm_document)
        assoc = ssm_create_association(
            vm_['name'],
            {'ssm_document': ssm_document},
            instance_id=vm_['instance_id'],
            call='action'
        )
        if isinstance(assoc, dict) and assoc.get('error', None):
            log.error(
                'Failed to associate instance %s with ssm document %s',
                vm_['instance_id'], ssm_document
            )
            return {}

    for key, value in six.iteritems(__utils__['cloud.bootstrap'](vm_, __opts__)):
        ret.setdefault(key, value)

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

    event_data = {
        'name': vm_['name'],
        'profile': vm_['profile'],
        'provider': vm_['driver'],
        'instance_id': vm_['instance_id'],
    }
    if volumes:
        event_data['volumes'] = volumes
    if ssm_document:
        event_data['ssm_document'] = ssm_document

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

    # Ensure that the latest node data is returned
    node = _get_node(instance_id=vm_['instance_id'])
    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
    ret.update(node)

    # Add any block device tags specified
    ex_blockdevicetags = {}
    blockdevicemappings_holder = block_device_mappings(vm_)
    if blockdevicemappings_holder:
        for _bd in blockdevicemappings_holder:
            if 'tag' in _bd:
                ex_blockdevicetags[_bd['DeviceName']] = _bd['tag']

    block_device_volume_id_map = {}

    if ex_blockdevicetags:
        for _device, _map in six.iteritems(ret['blockDeviceMapping']):
            bd_items = []
            if isinstance(_map, dict):
                bd_items.append(_map)
            else:
                for mapitem in _map:
                    bd_items.append(mapitem)

            for blockitem in bd_items:
                if blockitem['deviceName'] in ex_blockdevicetags and 'Name' not in ex_blockdevicetags[blockitem['deviceName']]:
                    ex_blockdevicetags[blockitem['deviceName']]['Name'] = vm_['name']
                if blockitem['deviceName'] in ex_blockdevicetags:
                    block_device_volume_id_map[blockitem[ret['rootDeviceType']]['volumeId']] = ex_blockdevicetags[blockitem['deviceName']]

    if block_device_volume_id_map:

        for volid, tags in six.iteritems(block_device_volume_id_map):
            __utils__['cloud.fire_event'](
                'event',
                'setting tags',
                'salt/cloud/block_volume_{0}/tagging'.format(str(volid)),
                args={'tags': tags},
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport']
            )

            __utils__['cloud.wait_for_fun'](
                set_tags,
                timeout=30,
                name=vm_['name'],
                tags=tags,
                resource_id=volid,
                call='action',
                location=location
            )

    return ret
1123495
public void updateInstance(
      Instance my_instance,
      final String my_client_project,
      final String my_instance_id,
      final String my_display_name) {
    // [START instance_admin_client_update_instance]
    Instance instance = my_instance;
    final String clientProject = my_client_project;
    final String instanceId = my_instance_id;

    final String newDisplayName = my_display_name;

    InstanceInfo toUpdate =
        InstanceInfo.newBuilder(InstanceId.of(clientProject, instanceId))
            .setDisplayName(newDisplayName)
            .setNodeCount(instance.getNodeCount() + 1)
            .build();
    // Only update display name
    OperationFuture<Instance, UpdateInstanceMetadata> op =
        instanceAdminClient.updateInstance(toUpdate, InstanceInfo.InstanceField.DISPLAY_NAME);
    try {
      op.get();
    } catch (ExecutionException e) {
      throw (SpannerException) e.getCause();
    } catch (InterruptedException e) {
      throw SpannerExceptionFactory.propagateInterrupt(e);
    }
    // [END instance_admin_client_update_instance]
  }
237745
function new_instance()
	{
		if(!($tab = $this->table_name()))
			bors_throw("Try to get new db instance with undefined table");

		if(!$this->create_time(true))
			$this->set_create_time(time());

		if(!$this->modify_time(true))
			$this->set_modify_time(time());

//		$this->set_owner_id(bors()->user_id());
		$this->set_last_editor_id(bors()->user_id());

		$this->storage()->create($this);
	}
453101
def do_rebootInstance(self,args):
        """"""
        parser = CommandArgumentParser("rebootInstance")
        parser.add_argument(dest='instance',help='instance index or name');
        args = vars(parser.parse_args(args))

        instanceId = args['instance']
        try:
            index = int(instanceId)
            instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']
            instanceId = instances[index]
        except ValueError:
            pass

        client = AwsConnectionFactory.getEc2Client()
        client.reboot_instances(InstanceIds=[instanceId['InstanceId']])
803320
def update_cache_for_instance(
        model_name, instance_pk, instance=None, version=None):
    """"""
    cache = SampleCache()
    invalid = cache.update_instance(model_name, instance_pk, instance, version)
    for invalid_name, invalid_pk, invalid_version in invalid:
        update_cache_for_instance.delay(
            invalid_name, invalid_pk, version=invalid_version)
153413
def dynamic_start(self, access_token, instance_url=None, **kw):
        
        self.dynamic = {'access_token': str(access_token), 'instance_url': str(instance_url)}
        self.dynamic.update(kw)
379243
def create_db_instance(self, params):
        '''  '''
        if not self.connect_to_aws_rds():
            return False
        try:
            database = self.rdsc.create_dbinstance(
                id=params['id'],
                allocated_storage=params['size'],
                instance_class='db.t1.micro',
                engine='MySQL',
                master_username=params['username'],
                master_password=params['password'],
                db_name=params['dbname'],
                multi_az=False
            )
        except:
            return False
        else:
            return True
1010010
def describe_instances(id=nil)
      begin
        @describe_instances = ec2.describe_instances.reservationSet.item.map do |r|
          r.instancesSet.item.map do |i|
            inst_options = i.merge(r.merge(:cloud => cloud)).merge(cloud.cloud_provider.dsl_options)
            Ec2Instance.new(inst_options)
          end
        end.flatten
      rescue AWS::InvalidClientTokenId => e # AWS credentials invalid
        puts "Error contacting AWS: #{e}"
        raise e
      rescue Exception => e
        []
      end
    end
534715
def create_server_ec2(connection,
                      region,
                      disk_name,
                      disk_size,
                      ami,
                      key_pair,
                      instance_type,
                      tags={},
                      security_groups=None,
                      delete_on_termination=True,
                      log=False,
                      wait_for_ssh_available=True):
    

    if log:
        log_green("Started...")
        log_yellow("...Creating EC2 instance...")

    ebs_volume = EBSBlockDeviceType()
    ebs_volume.size = disk_size
    bdm = BlockDeviceMapping()
    bdm[disk_name] = ebs_volume

    # get an ec2 ami image object with our choosen ami
    image = connection.get_all_images(ami)[0]
    # start a new instance
    reservation = image.run(1, 1,
                            key_name=key_pair,
                            security_groups=security_groups,
                            block_device_map=bdm,
                            instance_type=instance_type)

    # and get our instance_id
    instance = reservation.instances[0]

    #  and loop and wait until ssh is available
    while instance.state == u'pending':
        if log:
            log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    if log:
        log_green("Instance state: %s" % instance.state)
    if wait_for_ssh_available:
        wait_for_ssh(instance.public_dns_name)

    # update the EBS volumes to be deleted on instance termination
    if delete_on_termination:
        for dev, bd in instance.block_device_mapping.items():
            instance.modify_attribute('BlockDeviceMapping',
                                      ["%s=%d" % (dev, 1)])

    # add a tag to our instance
    connection.create_tags([instance.id], tags)

    if log:
        log_green("Public dns: %s" % instance.public_dns_name)

    # returns our new instance
    return instance