Start an instance.

    CLI Examples:

    .. code-block:: bash

        salt-cloud -a start i-2f733r5n
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
148158
def cmd_ssh(self, argv, help):
        """"""
        parser = argparse.ArgumentParser(
            prog="%s ssh" % self.progname,
            description=help,
        )
        instances = self.get_instances(command='init_ssh_key')
        parser.add_argument("instance", nargs=1,
                            metavar="instance",
                            help="Name of the instance from the config.",
                            choices=sorted(instances))
        parser.add_argument("...", nargs=argparse.REMAINDER,
                            help="ssh options")
        iargs = enumerate(argv)
        sid_index = None
        user = None
        for i, arg in iargs:
            if not arg.startswith('-'):
                sid_index = i
                break
            if arg[1] in '1246AaCfgKkMNnqsTtVvXxYy':
                continue
            elif arg[1] in 'bcDeFiLlmOopRSw':
                value = iargs.next()
                if arg[1] == 'l':
                    user = value[1]
                continue
        # fake parsing for nice error messages
        if sid_index is None:
            parser.parse_args([])
        else:
            sid = argv[sid_index]
            if '@' in sid:
                user, sid = sid.split('@', 1)
            parser.parse_args([sid])
        instance = instances[sid]
        if user is None:
            user = instance.config.get('user')
        try:
            ssh_info = instance.init_ssh_key(user=user)
        except (instance.paramiko.SSHException, socket.error) as e:
            log.error("Couldn't validate fingerprint for ssh connection.")
            log.error(unicode(e))
            log.error("Is the instance finished starting up?")
            sys.exit(1)
        client = ssh_info['client']
        client.get_transport().sock.close()
        client.close()
        argv[sid_index:sid_index + 1] = instance.ssh_args_from_info(ssh_info)
        argv[0:0] = ['ssh']
        os.execvp('ssh', argv)
1036378
def restart_instance(self, instance):
        
        params = {'state': 'restarted'}
        url = '/instances/{}'.format(instance)
        self.patch_proto(url, params=params)
1303219
def _run_command(cmd, options=(), env=None):
    '''
    
    '''
    params = [cmd]
    params.extend(options)
    return __salt__['cmd.run_all'](params, env=env, python_shell=False)
1130656
def start_instance(self, instance):
        
        params = {'state': 'running'}
        url = '/instances/{}'.format(instance)
        self.patch_proto(url, params=params)
4587
def start(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The start action must be called with -a or --action.'
        )

    log.info('Starting node %s', name)

    return vm_action(name, kwargs={'action': 'resume'}, call=call)
4046
def start(name, vmid=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The start action must be called with -a or --action.'
        )

    log.debug('Start: %s (%s) = Start', name, vmid)
    if not set_vm_status('start', name, vmid=vmid):
        log.error('Unable to bring VM %s (%s) up..', name, vmid)
        raise SaltCloudExecutionFailure

    # xxx: TBD: Check here whether the status was actually changed to 'started'

    return {'Started': '{0} was started.'.format(name)}
1199336
def main():
    
    p = argparse.ArgumentParser(description='Manage Amazon AWS services',
                                prog='aws',
                                version=__version__)
    subparsers = p.add_subparsers(help='Select Amazon AWS service to use')

    # Auto Scaling
    as_service = subparsers.add_parser('as', help='Amazon Auto Scaling')
    as_subparsers = as_service.add_subparsers(help='Perform action')

    as_service_list = as_subparsers.add_parser('list', help='List Auto Scaling groups')
    as_service_list.set_defaults(func=as_list_handler)

    # Elastic Cloud Computing
    ec2_service = subparsers.add_parser('ec2', help='Amazon Elastic Compute Cloud')
    ec2_subparsers = ec2_service.add_subparsers(help='Perform action')

    ec2_service_list = ec2_subparsers.add_parser('list', help='List items')
    ec2_service_list.add_argument('--elb', '-e', help='Filter instances inside this ELB instance')
    ec2_service_list.add_argument('--instances', '-i', nargs='*', metavar=('id', 'id'),
                                  help='List of instance IDs to use as filter')
    ec2_service_list.add_argument('--type', default='instances', choices=['instances', 'regions', 'images'],
                                  help='List items of this type')
    ec2_service_list.set_defaults(func=ec2_list_handler)

    ec2_service_fab = ec2_subparsers.add_parser('fab', help='Run Fabric commands')
    ec2_service_fab.add_argument('--elb', '-e', help='Run against EC2 instances for this ELB')
    ec2_service_fab.add_argument('--instances', '-i', nargs='*', metavar=('id', 'id'),
                                 help='List of instance IDs to use as filter')
    ec2_service_fab.add_argument('--file', '-f', nargs='+', help='Define fabfile to use')
    ec2_service_fab.add_argument('methods',
                                 metavar='method:arg1,arg2=val2,host=foo,hosts=\'h1;h2\',',
                                 nargs='+',
                                 help='Specify one or more methods to execute.')
    ec2_service_fab.set_defaults(func=ec2_fab_handler)

    ec2_service_create = ec2_subparsers.add_parser('create', help='Create and start new instances')
    ec2_service_create.set_defaults(func=ec2_create_handler)

    ec2_service_start = ec2_subparsers.add_parser('start', help='Start existing instances')
    ec2_service_start.add_argument('instance', nargs='+', help='ID of an instance to start')
    ec2_service_start.set_defaults(func=ec2_start_handler)

    ec2_service_stop = ec2_subparsers.add_parser('stop', help='Stop instances')
    ec2_service_stop.add_argument('instance', nargs='+', help='ID of an instance to stop')
    ec2_service_stop.add_argument('--force', '-f', action='store_true', help='Force stop')
    ec2_service_stop.set_defaults(func=ec2_stop_handler)

    ec2_service_terminate = ec2_subparsers.add_parser('terminate', help='Terminate instances')
    ec2_service_terminate.add_argument('instance', nargs='+', help='ID of an instance to terminate')
    ec2_service_terminate.set_defaults(func=ec2_terminate_handler)

    ec2_service_images = ec2_subparsers.add_parser('images', help='List AMI images')
    ec2_service_images.add_argument('image', nargs='*',
                                              help='Image ID to use as filter')
    ec2_service_images.set_defaults(func=ec2_images_handler)

    ec2_service_create_image = ec2_subparsers.add_parser('create-image', help='Create AMI image from instance')
    ec2_service_create_image.add_argument('instance', help='ID of an instance to image')
    ec2_service_create_image.add_argument('name', help='The name of the image')
    ec2_service_create_image.add_argument('--description', '-d', help='Optional description for the image')
    ec2_service_create_image.add_argument('--noreboot', action='store_true', default=False,
                                          help='Do not shutdown the instance before creating image. ' +
                                               'Note: System integrity might suffer if used.')
    ec2_service_create_image.set_defaults(func=ec2_create_image_handler)

    # Elastic Load Balancing
    elb_service = subparsers.add_parser('elb', help='Amazon Elastic Load Balancing')
    elb_subparsers = elb_service.add_subparsers(help='Perform action')

    elb_service_list = elb_subparsers.add_parser('list', help='List items')
    elb_service_list.add_argument('--type', default='balancers', choices=['balancers', 'regions'],
                                  help='List items of this type')
    elb_service_list.set_defaults(func=elb_list_handler)

    elb_service_instances = elb_subparsers.add_parser('instances', help='List registered instances')
    elb_service_instances.add_argument('balancer', help='Name of the Load Balancer')
    elb_service_instances.set_defaults(func=elb_instances_handler)

    elb_service_register = elb_subparsers.add_parser('register', help='Register instances to balancer')
    elb_service_register.add_argument('balancer', help='Name of the load balancer')
    elb_service_register.add_argument('instance', nargs='+', help='ID of an instance to register')
    elb_service_register.set_defaults(func=elb_register_handler)

    elb_service_deregister = elb_subparsers.add_parser('deregister', help='Deregister instances of balancer')
    elb_service_deregister.add_argument('balancer', help='Name of the Load Balancer')
    elb_service_deregister.add_argument('instance', nargs='+', help='ID of an instance to deregister')
    elb_service_deregister.set_defaults(func=elb_deregister_handler)

    elb_service_zones = elb_subparsers.add_parser('zones', help='Enable or disable availability zones')
    elb_service_zones.add_argument('balancer', help='Name of the Load Balancer')
    elb_service_zones.add_argument('zone', nargs='+', help='Name of the availability zone')
    elb_service_zones.add_argument('status', help='Disable of enable zones', choices=['enable', 'disable'])
    elb_service_zones.set_defaults(func=elb_zones_handler)

    elb_service_delete = elb_subparsers.add_parser('delete', help='Delete Load Balancer')
    elb_service_delete.add_argument('balancer', help='Name of the Load Balancer')
    elb_service_delete.set_defaults(func=elb_delete_handler)

    # elb_service_create = elb_subparsers.add_parser('create', help='Create new Load Balancer')
    # elb_service_delete = elb_subparsers.add_parser('delete', help='Delete Load Balancer')
    # elb_service_register = elb_subparsers.add_parser('register', help='Register EC2 instance')
    # elb_service_zone = elb_subparsers.add_parser('zone', help='Enable or disable region')

    arguments = p.parse_args()
    arguments.func(p, arguments)
1188789
def start(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudException(
            'The start action must be called with -a or --action.'
        )

    node_id = get_linode_id_from_name(name)
    node = get_linode(kwargs={'linode_id': node_id})

    if node['STATUS'] == 1:
        return {'success': True,
                'action': 'start',
                'state': 'Running',
                'msg': 'Machine already running'}

    response = _query('linode', 'boot', args={'LinodeID': node_id})['DATA']

    if _wait_for_job(node_id, response['JobID']):
        return {'state': 'Running',
                'action': 'start',
                'success': True}
    else:
        return {'action': 'start',
                'success': False}
375584
def start(self, **kwargs):
        

        pty_stdin, pty_stdout, pty_stderr = self.sockets()
        pumps = []

        if pty_stdin and self.interactive:
            pumps.append(io.Pump(io.Stream(self.stdin), pty_stdin, wait_for_output=False))

        if pty_stdout:
            pumps.append(io.Pump(pty_stdout, io.Stream(self.stdout), propagate_close=False))

        if pty_stderr:
            pumps.append(io.Pump(pty_stderr, io.Stream(self.stderr), propagate_close=False))

        if not self.container_info()['State']['Running']:
            self.client.start(self.container, **kwargs)

        flags = [p.set_blocking(False) for p in pumps]

        try:
            with WINCHHandler(self):
                self._hijack_tty(pumps)
        finally:
            if flags:
                for (pump, flag) in zip(pumps, flags):
                    io.set_blocking(pump, flag)
224841
def start_server(name)
      server = get_server(name)
      if !server || !server['id'] then
        puts "\nError: Virtual machine '#{name}' does not exist"
        exit 1
      end

      params = {
          'command' => 'startVirtualMachine',
          'id' => server['id']
      }

      json = send_async_request(params)
      json['virtualmachine']
    end
424397
def start(vm_name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The start action must be called with -a or --action.'
        )

    conn = get_conn()

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

    result = conn.ex_start_node(
        conn.ex_get_node(vm_name)
    )

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

    return result
86511
def start(self, **kwargs):
        
        return self.client.api.start(self.id, **kwargs)
600802
def new(cls, settings, *args, **kwargs):
        
        logger.debug('Initializing new "%s" Instance object' % settings['CLOUD'])
        cloud = settings['CLOUD']
        if cloud == 'bare':
            self = BareInstance(settings=settings, *args, **kwargs)
        elif cloud == 'aws':
            self = AWSInstance(settings=settings, *args, **kwargs)
        elif cloud == 'gcp':
            self = GCPInstance(settings=settings, *args, **kwargs)
        else:
            raise DSBException('Cloud "%s" not supported' % cloud)
        return self
863517
def salt_cloud():
    '''
    
    '''
    # Define 'salt' global so we may use it after ImportError. Otherwise,
    # UnboundLocalError will be raised.
    global salt  # pylint: disable=W0602

    try:
        # Late-imports for CLI performance
        import salt.cloud
        import salt.cloud.cli
    except ImportError as e:
        # No salt cloud on Windows
        log.error('Error importing salt cloud: %s', e)
        print('salt-cloud is not available in this system')
        sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
    if '' in sys.path:
        sys.path.remove('')

    client = salt.cloud.cli.SaltCloud()
    _install_signal_handlers(client)
    client.run()
418446
def start(name, jail=None):
    '''
    
    '''
    cmd = '{0} {1} onestart'.format(_cmd(jail), name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)
72889
def run(self):
        '''
        
        '''
        import salt.client
        self.parse_args()

        if self.config['log_level'] not in ('quiet', ):
            # Setup file logging!
            self.setup_logfile_logger()
            verify_log(self.config)

        try:
            # We don't need to bail on config file permission errors
            # if the CLI process is run with the -a flag
            skip_perm_errors = self.options.eauth != ''

            self.local_client = salt.client.get_local_client(
                self.get_config_file_path(),
                skip_perm_errors=skip_perm_errors,
                auto_reconnect=True)
        except SaltClientError as exc:
            self.exit(2, '{0}\n'.format(exc))
            return

        if self.options.batch or self.options.static:
            # _run_batch() will handle all output and
            # exit with the appropriate error condition
            # Execution will not continue past this point
            # in batch mode.
            self._run_batch()
            return

        if self.options.preview_target:
            minion_list = self._preview_target()
            self._output_ret(minion_list, self.config.get('output', 'nested'))
            return

        if self.options.timeout <= 0:
            self.options.timeout = self.local_client.opts['timeout']

        kwargs = {
            'tgt': self.config['tgt'],
            'fun': self.config['fun'],
            'arg': self.config['arg'],
            'timeout': self.options.timeout,
            'show_timeout': self.options.show_timeout,
            'show_jid': self.options.show_jid}

        if 'token' in self.config:
            import salt.utils.files
            try:
                with salt.utils.files.fopen(os.path.join(self.config['cachedir'], '.root_key'), 'r') as fp_:
                    kwargs['key'] = fp_.readline()
            except IOError:
                kwargs['token'] = self.config['token']

        kwargs['delimiter'] = self.options.delimiter

        if self.selected_target_option:
            kwargs['tgt_type'] = self.selected_target_option
        else:
            kwargs['tgt_type'] = 'glob'

        # If batch_safe_limit is set, check minions matching target and
        # potentially switch to batch execution
        if self.options.batch_safe_limit > 1:
            if len(self._preview_target()) >= self.options.batch_safe_limit:
                salt.utils.stringutils.print_cli('\nNOTICE: Too many minions targeted, switching to batch execution.')
                self.options.batch = self.options.batch_safe_size
                self._run_batch()
                return

        if getattr(self.options, 'return'):
            kwargs['ret'] = getattr(self.options, 'return')

        if getattr(self.options, 'return_config'):
            kwargs['ret_config'] = getattr(self.options, 'return_config')

        if getattr(self.options, 'return_kwargs'):
            kwargs['ret_kwargs'] = yamlify_arg(
                    getattr(self.options, 'return_kwargs'))

        if getattr(self.options, 'module_executors'):
            kwargs['module_executors'] = yamlify_arg(getattr(self.options, 'module_executors'))

        if getattr(self.options, 'executor_opts'):
            kwargs['executor_opts'] = yamlify_arg(getattr(self.options, 'executor_opts'))

        if getattr(self.options, 'metadata'):
            kwargs['metadata'] = yamlify_arg(
                    getattr(self.options, 'metadata'))

        # If using eauth and a token hasn't already been loaded into
        # kwargs, prompt the user to enter auth credentials
        if 'token' not in kwargs and 'key' not in kwargs and self.options.eauth:
            # This is expensive. Don't do it unless we need to.
            import salt.auth
            resolver = salt.auth.Resolver(self.config)
            res = resolver.cli(self.options.eauth)
            if self.options.mktoken and res:
                tok = resolver.token_cli(
                        self.options.eauth,
                        res
                        )
                if tok:
                    kwargs['token'] = tok.get('token', '')
            if not res:
                sys.stderr.write('ERROR: Authentication failed\n')
                sys.exit(2)
            kwargs.update(res)
            kwargs['eauth'] = self.options.eauth

        if self.config['async']:
            jid = self.local_client.cmd_async(**kwargs)
            salt.utils.stringutils.print_cli('Executed command with job ID: {0}'.format(jid))
            return

        # local will be None when there was an error
        if not self.local_client:
            return

        retcodes = []
        errors = []

        try:
            if self.options.subset:
                cmd_func = self.local_client.cmd_subset
                kwargs['sub'] = self.options.subset
                kwargs['cli'] = True
            else:
                cmd_func = self.local_client.cmd_cli

            if self.options.progress:
                kwargs['progress'] = True
                self.config['progress'] = True
                ret = {}
                for progress in cmd_func(**kwargs):
                    out = 'progress'
                    try:
                        self._progress_ret(progress, out)
                    except LoaderError as exc:
                        raise SaltSystemExit(exc)
                    if 'return_count' not in progress:
                        ret.update(progress)
                self._progress_end(out)
                self._print_returns_summary(ret)
            elif self.config['fun'] == 'sys.doc':
                ret = {}
                out = ''
                for full_ret in self.local_client.cmd_cli(**kwargs):
                    ret_, out, retcode = self._format_ret(full_ret)
                    ret.update(ret_)
                self._output_ret(ret, out, retcode=retcode)
            else:
                if self.options.verbose:
                    kwargs['verbose'] = True
                ret = {}
                for full_ret in cmd_func(**kwargs):
                    try:
                        ret_, out, retcode = self._format_ret(full_ret)
                        retcodes.append(retcode)
                        self._output_ret(ret_, out, retcode=retcode)
                        ret.update(full_ret)
                    except KeyError:
                        errors.append(full_ret)

            # Returns summary
            if self.config['cli_summary'] is True:
                if self.config['fun'] != 'sys.doc':
                    if self.options.output is None:
                        self._print_returns_summary(ret)
                        self._print_errors_summary(errors)

            # NOTE: Return code is set here based on if all minions
            # returned 'ok' with a retcode of 0.
            # This is the final point before the 'salt' cmd returns,
            # which is why we set the retcode here.
            if not all(exit_code == salt.defaults.exitcodes.EX_OK for exit_code in retcodes):
                sys.stderr.write('ERROR: Minions returned with non-zero exit code\n')
                sys.exit(salt.defaults.exitcodes.EX_GENERIC)

        except (AuthenticationError,
                AuthorizationError,
                SaltInvocationError,
                EauthAuthenticationError,
                SaltClientError) as exc:
            ret = six.text_type(exc)
            self._output_ret(ret, '', retcode=1)