Create a keystone tenant

    CLI Examples:

    .. code-block:: bash

        salt '*' keystone.tenant_create nova description='nova tenant'
        salt '*' keystone.tenant_create test enabled=False
7907
def tenant_create(name, description=None, enabled=True, profile=None,
                  **connection_args):
    '''
    
    '''
    kstone = auth(profile, **connection_args)
    new = getattr(kstone, _TENANTS, None).create(name, description, enabled)
    return tenant_get(new.id, profile=profile, **connection_args)
548135
def _auth(profile=None, api_version=1, **connection_args):
    '''
    
    '''

    if profile:
        prefix = profile + ':keystone.'
    else:
        prefix = 'keystone.'

    def get(key, default=None):
        '''
        Checks connection_args, then salt-minion config,
        falls back to specified default value.
        '''
        return connection_args.get('connection_' + key,
                                   __salt__['config.get'](prefix + key, default))

    user = get('user', 'admin')
    password = get('password', None)
    tenant = get('tenant', 'admin')
    tenant_id = get('tenant_id')
    auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')
    insecure = get('insecure', False)
    admin_token = get('token')
    region_name = get('region_name', None)

    if admin_token and api_version != 1 and not password:
        # If we had a password we could just
        # ignore the admin-token and move on...
        raise SaltInvocationError('Only can use keystone admin token ' +
                                  'with Heat API v1')
    elif password:
        # Can't use the admin-token anyway
        kwargs = {'username': user,
                  'password': password,
                  'tenant_id': tenant_id,
                  'auth_url': auth_url,
                  'region_name': region_name,
                  'tenant_name': tenant}
        # 'insecure' keyword not supported by all v2.0 keystone clients
        #   this ensures it's only passed in when defined
        if insecure:
            kwargs['insecure'] = True
    elif api_version == 1 and admin_token:
        kwargs = {'token': admin_token,
                  'auth_url': auth_url}
    else:
        raise SaltInvocationError('No credentials to authenticate with.')

    token = __salt__['keystone.token_get'](profile)
    kwargs['token'] = token['id']
    # This doesn't realy prevent the password to show up
    # in the minion log as keystoneclient.session is
    # logging it anyway when in debug-mode
    kwargs.pop('password')
    try:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']
    except KeyError:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']
    heat_endpoint = heat_endpoint % token
    log.debug('Calling heatclient.client.Client(%s, %s, **%s)',
              api_version, heat_endpoint, kwargs)
    # may raise exc.HTTPUnauthorized, exc.HTTPNotFound
    # but we deal with those elsewhere
    return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)
865400
def service_present(name, service_type, description=None,
                    profile=None, **connection_args):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Service "{0}" already exists'.format(name)}

    # Check if service is already present
    role = __salt__['keystone.service_get'](name=name,
                                            profile=profile,
                                            **connection_args)

    if 'Error' not in role:
        return ret
    else:
        if __opts__.get('test'):
            ret['result'] = None
            ret['comment'] = 'Service "{0}" will be added'.format(name)
            return ret
        # Create service
        __salt__['keystone.service_create'](name, service_type,
                                            description,
                                            profile=profile,
                                            **connection_args)
        ret['comment'] = 'Service "{0}" has been added'.format(name)
        ret['changes']['Service'] = 'Created'

    return ret
1117372
def create_network_interface(call=None, kwargs=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The create_network_interface action must be called with -a or --action.'
        )

    # pylint: disable=invalid-name
    IPAllocationMethod = getattr(
        network_models,
        'IPAllocationMethod'
    )
    # pylint: disable=invalid-name
    NetworkInterface = getattr(
        network_models,
        'NetworkInterface'
    )
    # pylint: disable=invalid-name
    NetworkInterfaceIPConfiguration = getattr(
        network_models,
        'NetworkInterfaceIPConfiguration'
    )
    # pylint: disable=invalid-name
    PublicIPAddress = getattr(
        network_models,
        'PublicIPAddress'
    )

    if not isinstance(kwargs, dict):
        kwargs = {}

    vm_ = kwargs
    netconn = get_conn(client_type='network')

    if kwargs.get('location') is None:
        kwargs['location'] = get_location()

    if kwargs.get('network') is None:
        kwargs['network'] = config.get_cloud_config_value(
            'network', vm_, __opts__, search_global=False
        )

    if kwargs.get('subnet') is None:
        kwargs['subnet'] = config.get_cloud_config_value(
            'subnet', vm_, __opts__, search_global=False
        )

    if kwargs.get('network_resource_group') is None:
        kwargs['network_resource_group'] = config.get_cloud_config_value(
            'resource_group', vm_, __opts__, search_global=False
        )

    if kwargs.get('iface_name') is None:
        kwargs['iface_name'] = '{0}-iface0'.format(vm_['name'])

    try:
        subnet_obj = netconn.subnets.get(
            resource_group_name=kwargs['network_resource_group'],
            virtual_network_name=kwargs['network'],
            subnet_name=kwargs['subnet'],
        )
    except CloudError as exc:
        raise SaltCloudSystemExit(
            '{0} (Resource Group: "{1}", VNET: "{2}", Subnet: "{3}")'.format(
                exc.message,
                kwargs['network_resource_group'],
                kwargs['network'],
                kwargs['subnet']
            )
        )

    ip_kwargs = {}
    ip_configurations = None

    if 'load_balancer_backend_address_pools' in kwargs:
        pool_dicts = kwargs['load_balancer_backend_address_pools']
        if isinstance(pool_dicts, dict):
            pool_ids = []
            for load_bal, be_pools in pool_dicts.items():
                for pool in be_pools:
                    try:
                        lbbep_data = netconn.load_balancer_backend_address_pools.get(
                            kwargs['resource_group'],
                            load_bal,
                            pool,
                        )
                        pool_ids.append({'id': lbbep_data.as_dict()['id']})
                    except CloudError as exc:
                        log.error('There was a cloud error: %s', six.text_type(exc))
                    except KeyError as exc:
                        log.error('There was an error getting the Backend Pool ID: %s', six.text_type(exc))
            ip_kwargs['load_balancer_backend_address_pools'] = pool_ids

    if 'private_ip_address' in kwargs.keys():
        ip_kwargs['private_ip_address'] = kwargs['private_ip_address']
        ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.static
    else:
        ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.dynamic

    if kwargs.get('allocate_public_ip') is True:
        pub_ip_name = '{0}-ip'.format(kwargs['iface_name'])
        poller = netconn.public_ip_addresses.create_or_update(
            resource_group_name=kwargs['resource_group'],
            public_ip_address_name=pub_ip_name,
            parameters=PublicIPAddress(
                location=kwargs['location'],
                public_ip_allocation_method=IPAllocationMethod.static,
            ),
        )
        count = 0
        poller.wait()
        while True:
            try:
                pub_ip_data = netconn.public_ip_addresses.get(
                    kwargs['resource_group'],
                    pub_ip_name,
                )
                if pub_ip_data.ip_address:  # pylint: disable=no-member
                    ip_kwargs['public_ip_address'] = PublicIPAddress(
                        id=six.text_type(pub_ip_data.id),  # pylint: disable=no-member
                    )
                    ip_configurations = [
                        NetworkInterfaceIPConfiguration(
                            name='{0}-ip'.format(kwargs['iface_name']),
                            subnet=subnet_obj,
                            **ip_kwargs
                        )
                    ]
                    break
            except CloudError as exc:
                log.error('There was a cloud error: %s', exc)
            count += 1
            if count > 120:
                raise ValueError('Timed out waiting for public IP Address.')
            time.sleep(5)
    else:
        priv_ip_name = '{0}-ip'.format(kwargs['iface_name'])
        ip_configurations = [
            NetworkInterfaceIPConfiguration(
                name=priv_ip_name,
                subnet=subnet_obj,
                **ip_kwargs
            )
        ]

    network_security_group = None
    if kwargs.get('security_group') is not None:
        network_security_group = netconn.network_security_groups.get(
            resource_group_name=kwargs['resource_group'],
            network_security_group_name=kwargs['security_group'],
        )

    iface_params = NetworkInterface(
        location=kwargs['location'],
        network_security_group=network_security_group,
        ip_configurations=ip_configurations,
    )

    poller = netconn.network_interfaces.create_or_update(
        kwargs['resource_group'], kwargs['iface_name'], iface_params
    )
    try:
        poller.wait()
    except Exception as exc:
        log.warning('Network interface creation could not be polled. '
                 'It is likely that we are reusing an existing interface. (%s)', exc)

    count = 0
    while True:
        try:
            return _get_network_interface(kwargs['iface_name'], kwargs['resource_group'])
        except CloudError:
            count += 1
            if count > 120:
                raise ValueError('Timed out waiting for operation to complete.')
            time.sleep(5)
904360
def create(cls, env=None, args=None):
    
    env = {k: v for k, v in (os.environ if env is None else env).items()
           if k.startswith('PANTS_')}
    args = tuple(sys.argv if args is None else args)

    flags = set()
    short_flags = set()

    def filecontent_for(path):
      return FileContent(ensure_text(path), read_file(path, binary_mode=True))

    def capture_the_flags(*args, **kwargs):
      for arg in args:
        flags.add(arg)
        if len(arg) == 2:
          short_flags.add(arg)
        elif kwargs.get('type') == bool:
          flags.add('--no-{}'.format(arg[2:]))

    GlobalOptionsRegistrar.register_bootstrap_options(capture_the_flags)

    def is_bootstrap_option(arg):
      components = arg.split('=', 1)
      if components[0] in flags:
        return True
      for flag in short_flags:
        if arg.startswith(flag):
          return True
      return False

    # Take just the bootstrap args, so we don't choke on other global-scope args on the cmd line.
    # Stop before '--' since args after that are pass-through and may have duplicate names to our
    # bootstrap options.
    bargs = tuple(filter(is_bootstrap_option, itertools.takewhile(lambda arg: arg != '--', args)))

    config_file_paths = cls.get_config_file_paths(env=env, args=args)
    config_files_products = [filecontent_for(p) for p in config_file_paths]
    pre_bootstrap_config = Config.load_file_contents(config_files_products)

    initial_bootstrap_options = cls.parse_bootstrap_options(env, bargs, pre_bootstrap_config)
    bootstrap_option_values = initial_bootstrap_options.for_global_scope()

    # Now re-read the config, post-bootstrapping. Note the order: First whatever we bootstrapped
    # from (typically pants.ini), then config override, then rcfiles.
    full_configpaths = pre_bootstrap_config.sources()
    if bootstrap_option_values.pantsrc:
      rcfiles = [os.path.expanduser(str(rcfile)) for rcfile in bootstrap_option_values.pantsrc_files]
      existing_rcfiles = list(filter(os.path.exists, rcfiles))
      full_configpaths.extend(existing_rcfiles)

    full_config_files_products = [filecontent_for(p) for p in full_configpaths]
    post_bootstrap_config = Config.load_file_contents(
      full_config_files_products,
      seed_values=bootstrap_option_values
    )

    env_tuples = tuple(sorted(iteritems(env), key=lambda x: x[0]))
    return cls(env_tuples=env_tuples, bootstrap_args=bargs, args=args, config=post_bootstrap_config)
1360148
def create_service(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_service function must be called with -f or --function.'
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('A name must be specified as "name"')

    if 'label' not in kwargs:
        raise SaltCloudSystemExit('A label must be specified as "label"')

    if 'location' not in kwargs and 'affinity_group' not in kwargs:
        raise SaltCloudSystemExit('Either a location or an affinity_group '
                                  'must be specified (but not both)')

    try:
        data = conn.create_hosted_service(
            kwargs['name'],
            kwargs['label'],
            kwargs.get('description', None),
            kwargs.get('location', None),
            kwargs.get('affinity_group', None),
            kwargs.get('extended_properties', None),
        )
        return {'Success': 'The service was successfully created'}
    except AzureConflictHttpError:
        raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
24246
def create(self, opts):
        """"""

        argv = opts.args
        count = len(argv)

        # unflagged arguments are conf, stanza, key. In this order
        # however, we must have a conf and stanza.
        cpres = True if count > 0 else False
        spres = True if count > 1 else False
        kpres = True if count > 2 else False 

        if kpres:
            kvpair = argv[2].split("=")
            if len(kvpair) != 2:
                error("Creating a k/v pair requires key and value", 2)
            else:
                key, value = kvpair

        if not cpres and not spres:
            error("Conf name and stanza name is required for create", 2)

        name = argv[0]
        stan = argv[1]
        conf = self.service.confs[name]

        if not kpres:
            # create stanza
            conf.create(stan)
            return 

        # create key/value pair under existing stanza
        stanza = conf[stan]
        stanza.submit({key: value})
1217927
def create_environment(self, **kwargs):
        
        environment = super().create_environment(**kwargs)
        environment.tests.update({
            'type': self.test_type,
            'kind': self.test_kind,
            'opposite_before_self': self.test_opposite_before_self,
        })
        environment.filters.update({
            'docstringline': self.filter_docstringline,
            'pyquotesingle': self.filter_pyquotesingle,
            'derivedname': self.filter_derived_name,
            'refqualifiers': self.filter_refqualifiers,
            'attrqualifiers': self.filter_attrqualifiers,
            'supertypes': self.filter_supertypes,
            'all_contents': self.filter_all_contents,
            'pyfqn': self.filter_pyfqn,
            're_sub': lambda v, p, r: re.sub(p, r, v),
            'set': self.filter_set,
        })

        from pyecore import ecore
        environment.globals.update({'ecore': ecore})

        return environment
1064819
def create_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
        
        tenant_name = fw_dict.get('tenant_name')
        ret = self._create_service_nwk(tenant_id, tenant_name, 'out')
        if ret:
            res = fw_const.DCNM_OUT_NETWORK_CREATE_SUCCESS
            LOG.info("out Service network created for tenant %s",
                     tenant_id)
        else:
            res = fw_const.DCNM_OUT_NETWORK_CREATE_FAIL
            LOG.info("out Service network create failed for tenant %s",
                     tenant_id)
        self.update_fw_db_result(tenant_id, dcnm_status=res)
        return ret
266598
def create_address(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_address function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when creating an address.'
        )
        return False
    if 'region' not in kwargs:
        log.error(
            'A region must be specified for the address.'
        )
        return False

    name = kwargs['name']
    ex_region = kwargs['region']
    ex_address = kwargs.get("address", None)
    kwargs['region'] = _expand_region(kwargs['region'])

    conn = get_conn()

    __utils__['cloud.fire_event'](
        'event',
        'create address',
        'salt/cloud/address/creating',
        args=salt.utils.data.simple_types_filter(kwargs),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    addy = conn.ex_create_address(name, ex_region, ex_address)

    __utils__['cloud.fire_event'](
        'event',
        'created address',
        'salt/cloud/address/created',
        args=salt.utils.data.simple_types_filter(kwargs),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Created GCE Address %s', name)

    return _expand_address(addy)
392938
def new_env(environment):
    
    if not environment:
        print("You need to supply an environment name")
        return

    parser = read_config()

    if environment in parser.sections():
        print("Environment '%s' already exists" % environment)
        return

    print("Please introduce (in order) the commands for '%s'\n" % environment)
    print("Press RETURN to end command and RETURN with empty line to finish\n")

    commands = []
    cmd = ""

    while True:
        try:
            cmd = raw_input("> ")

            if not cmd:
                break

            commands.append(cmd)

        except KeyboardInterrupt:
            return

    parser.add_section(environment)
    parser.set(environment, "cmd", "\n".join(commands))

    write_config(parser)

    print("Added environment '%s'" % environment)
1366299
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 'cloudstack',
                                                           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']),
        sock_dir=__opts__['sock_dir'],
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    conn = get_conn()
    # pylint: disable=not-callable
    kwargs = {
        'name': vm_['name'],
        'image': get_image(conn, vm_),
        'size': get_size(conn, vm_),
        'location': get_location(conn, vm_),
    }
    # pylint: enable=not-callable

    sg = get_security_groups(conn, vm_)
    if sg is not False:
        kwargs['ex_security_groups'] = sg

    if get_keypair(vm_) is not False:
        kwargs['ex_keyname'] = get_keypair(vm_)

    if get_networkid(vm_) is not False:
        kwargs['networkids'] = get_networkid(vm_)
        kwargs['networks'] = (   # The only attr that is used is 'id'.
                                 CloudStackNetwork(None, None, None,
                                                   kwargs['networkids'],
                                                   None, None),
                             )

    if get_project(conn, vm_) is not False:
        kwargs['project'] = get_project(conn, vm_)

    event_data = kwargs.copy()
    event_data['image'] = kwargs['image'].name
    event_data['size'] = kwargs['size'].name

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

    displayname = cloudstack_displayname(vm_)
    if displayname:
        kwargs['ex_displayname'] = displayname
    else:
        kwargs['ex_displayname'] = kwargs['name']

    volumes = {}
    ex_blockdevicemappings = block_device_mappings(vm_)
    if ex_blockdevicemappings:
        for ex_blockdevicemapping in ex_blockdevicemappings:
            if 'VirtualName' not in ex_blockdevicemapping:
                ex_blockdevicemapping['VirtualName'] = '{0}-{1}'.format(vm_['name'], len(volumes))
            __utils__['cloud.fire_event'](
                'event',
                'requesting volume',
                'salt/cloud/{0}/requesting'.format(ex_blockdevicemapping['VirtualName']),
                sock_dir=__opts__['sock_dir'],
                args={'kwargs': {'name': ex_blockdevicemapping['VirtualName'],
                                 'device': ex_blockdevicemapping['DeviceName'],
                                 'size': ex_blockdevicemapping['VolumeSize']}},
            )
            try:
                volumes[ex_blockdevicemapping['DeviceName']] = conn.create_volume(
                        ex_blockdevicemapping['VolumeSize'],
                        ex_blockdevicemapping['VirtualName']
                    )
            except Exception as exc:
                log.error(
                    'Error creating volume %s on CLOUDSTACK\n\n'
                    'The following exception was thrown by libcloud when trying to '
                    'requesting a volume: \n%s',
                    ex_blockdevicemapping['VirtualName'], exc,
                    # Show the traceback if the debug logging level is enabled
                    exc_info_on_loglevel=logging.DEBUG
                )
                return False
    else:
        ex_blockdevicemapping = {}
    try:
        data = conn.create_node(**kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on CLOUDSTACK\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    for device_name in six.iterkeys(volumes):
        try:
            conn.attach_volume(data, volumes[device_name], device_name)
        except Exception as exc:
            log.error(
                'Error attaching volume %s on CLOUDSTACK\n\n'
                'The following exception was thrown by libcloud when trying to '
                'attach a volume: \n%s',
                ex_blockdevicemapping.get('VirtualName', 'UNKNOWN'), exc,
                # Show the traceback if the debug logging level is enabled
                exc_info=log.isEnabledFor(logging.DEBUG)
            )
            return False

    ssh_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default='root'
    )

    vm_['ssh_host'] = get_ip(data)
    vm_['password'] = data.extra['password']
    vm_['key_filename'] = get_key()
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(data.__dict__)

    if 'password' in data.extra:
        del data.extra['password']

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

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

    return ret
891605
def user_create(name, password, email, tenant_id=None,
                enabled=True, profile=None, project_id=None, description=None, **connection_args):
    '''
    
    '''
    kstone = auth(profile, **connection_args)

    if _OS_IDENTITY_API_VERSION > 2:
        if tenant_id and not project_id:
            project_id = tenant_id
        item = kstone.users.create(name=name,
                                   password=password,
                                   email=email,
                                   project_id=project_id,
                                   enabled=enabled,
                                   description=description)
    else:
        item = kstone.users.create(name=name,
                                   password=password,
                                   email=email,
                                   tenant_id=tenant_id,
                                   enabled=enabled)
    return user_get(item.id, profile=profile, **connection_args)
955333
def create(name, packages=None, user=None):
    
    packages = packages or ''
    packages = packages.split(',')
    packages.append('pip')
    args = packages + ['--yes', '-q']
    cmd = _create_conda_cmd('create', args=args, env=name, user=user)
    ret = _execcmd(cmd, user=user, return0=True)

    if ret['retcode'] == 0:
        ret['result'] = True
        ret['comment'] = 'Virtual enviroment "%s" successfully created' % name
    else:
        if ret['stderr'].startswith('Error: prefix already exists:'):
            ret['result'] = True
            ret['comment'] = 'Virtual enviroment "%s" already exists' % name
        else:
            ret['result'] = False
            ret['error'] = salt.exceptions.CommandExecutionError(ret['stderr'])
    return ret
797390
def create(self, vm_, local_master=True):
        '''
        
        '''
        output = {}

        minion_dict = salt.config.get_cloud_config_value(
            'minion', vm_, self.opts, default={}
        )

        alias, driver = vm_['provider'].split(':')
        fun = '{0}.create'.format(driver)
        if fun not in self.clouds:
            log.error(
                'Creating \'%s\' using \'%s\' as the provider '
                'cannot complete since \'%s\' is not available',
                vm_['name'], vm_['provider'], driver
            )
            return

        deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts)
        make_master = salt.config.get_cloud_config_value(
            'make_master',
            vm_,
            self.opts
        )

        if deploy:
            if not make_master and 'master' not in minion_dict:
                log.warning(
                    'There\'s no master defined on the \'%s\' VM settings.',
                    vm_['name']
                )

            if 'pub_key' not in vm_ and 'priv_key' not in vm_:
                log.debug('Generating minion keys for \'%s\'', vm_['name'])
                priv, pub = salt.utils.cloud.gen_keys(
                    salt.config.get_cloud_config_value(
                        'keysize',
                        vm_,
                        self.opts
                    )
                )
                vm_['pub_key'] = pub
                vm_['priv_key'] = priv
        else:
            # Note(pabelanger): We still reference pub_key and priv_key when
            # deploy is disabled.
            vm_['pub_key'] = None
            vm_['priv_key'] = None

        key_id = minion_dict.get('id', vm_['name'])

        domain = vm_.get('domain')
        if vm_.get('use_fqdn') and domain:
            minion_dict['append_domain'] = domain

        if 'append_domain' in minion_dict:
            key_id = '.'.join([key_id, minion_dict['append_domain']])

        if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_:
            log.debug('Generating the master keys for \'%s\'', vm_['name'])
            master_priv, master_pub = salt.utils.cloud.gen_keys(
                salt.config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    self.opts
                )
            )
            vm_['master_pub'] = master_pub
            vm_['master_pem'] = master_priv

        if local_master is True and deploy is True:
            # Accept the key on the local master
            salt.utils.cloud.accept_key(
                self.opts['pki_dir'], vm_['pub_key'], key_id
            )

        vm_['os'] = salt.config.get_cloud_config_value(
            'script',
            vm_,
            self.opts
        )

        try:
            vm_['inline_script'] = salt.config.get_cloud_config_value(
                'inline_script',
                vm_,
                self.opts
            )
        except KeyError:
            pass

        try:
            alias, driver = vm_['provider'].split(':')
            func = '{0}.create'.format(driver)
            with salt.utils.context.func_globals_inject(
                self.clouds[fun],
                __active_provider_name__=':'.join([alias, driver])
            ):
                output = self.clouds[func](vm_)
            if output is not False and 'sync_after_install' in self.opts:
                if self.opts['sync_after_install'] not in (
                        'all', 'modules', 'states', 'grains'):
                    log.error('Bad option for sync_after_install')
                    return output

                # A small pause helps the sync work more reliably
                time.sleep(3)

                start = int(time.time())
                while int(time.time()) < start + 60:
                    # We'll try every <timeout> seconds, up to a minute
                    mopts_ = salt.config.DEFAULT_MASTER_OPTS
                    conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1])
                    mopts_.update(
                        salt.config.master_config(
                            os.path.join(conf_path,
                                         'master')
                        )
                    )

                    client = salt.client.get_local_client(mopts=mopts_)

                    ret = client.cmd(
                        vm_['name'],
                        'saltutil.sync_{0}'.format(self.opts['sync_after_install']),
                        timeout=self.opts['timeout']
                    )
                    if ret:
                        log.info(
                            six.u('Synchronized the following dynamic modules: '
                                  '  {0}').format(ret)
                        )
                        break
        except KeyError as exc:
            log.exception(
                'Failed to create VM %s. Configuration value %s needs '
                'to be set', vm_['name'], exc
            )
        # If it's a map then we need to respect the 'requires'
        # so we do it later
        try:
            opt_map = self.opts['map']
        except KeyError:
            opt_map = False
        if self.opts['parallel'] and self.opts['start_action'] and not opt_map:
            log.info('Running %s on %s', self.opts['start_action'], vm_['name'])
            client = salt.client.get_local_client(mopts=self.opts)
            action_out = client.cmd(
                vm_['name'],
                self.opts['start_action'],
                timeout=self.opts['timeout'] * 60
            )
            output['ret'] = action_out
        return output
925528
async def create_vm(self, *, preset_name, image, flavor, security_groups=None,
                        userdata=None, key_name=None, availability_zone=None,
                        subnet=None):
        
        info = {
            'id': next(self._id_it),
            'name': preset_name,
            'ip': ['127.0.0.1'],
            'created': 0,
            'state': VmState.RUNNING,
            'flavor': flavor,
            'image': image,
            'metadata': {'test-meta': 'abctest'},
            'timed_shutdown_at': 1522753481,
            'tags': ['a-tag', 'b-tag', 'c-tag']
        }
        logging.debug('Prepare vm: %s', info)
        vm = Vm(self, **info)
        self._vms[vm.id] = vm
        logging.debug('Create: %s', vm)
        return None
405666
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
           timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
           stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
                                 timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
    except BotoServerError as e:
        msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
        log.error(msg)
        log.debug(e)
        return False