Check to see if attributes are set on a CFN stack.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_cfn.get_template mystack
436401
def get_template(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        template = conn.get_template(name)
        log.info('Retrieved template for stack %s', name)
        return template
    except BotoServerError as e:
        log.debug(e)
        msg = 'Template {0} does not exist'.format(name)
        log.error(msg)
        return six.text_type(e)
640960
def _diff_stack(self, stack, **kwargs):
        """"""
        if self.cancel.wait(0):
            return INTERRUPTED

        if not build.should_submit(stack):
            return NotSubmittedStatus()

        if not build.should_update(stack):
            return NotUpdatedStatus()

        provider = self.build_provider(stack)

        provider_stack = provider.get_stack(stack.fqn)

        # get the current stack template & params from AWS
        try:
            [old_template, old_params] = provider.get_stack_info(
                provider_stack)
        except exceptions.StackDoesNotExist:
            old_template = None
            old_params = {}

        stack.resolve(self.context, provider)
        # generate our own template & params
        parameters = self.build_parameters(stack)
        new_params = dict()
        for p in parameters:
            new_params[p['ParameterKey']] = p['ParameterValue']
        new_template = stack.blueprint.rendered
        new_stack = normalize_json(new_template)

        output = ["============== Stack: %s ==============" % (stack.name,)]
        # If this is a completely new template dump our params & stack
        if not old_template:
            output.extend(self._build_new_template(new_stack, parameters))
        else:
            # Diff our old & new stack/parameters
            old_template = parse_cloudformation_template(old_template)
            if isinstance(old_template, str):
                # YAML templates returned from CFN need parsing again
                # "AWSTemplateFormatVersion: \"2010-09-09\"\nParam..."
                # ->
                # AWSTemplateFormatVersion: "2010-09-09"
                old_template = parse_cloudformation_template(old_template)
            old_stack = normalize_json(
                json.dumps(old_template,
                           sort_keys=True,
                           indent=4,
                           default=str)
            )
            output.extend(build_stack_changes(stack.name, new_stack, old_stack,
                                              new_params, old_params))
        ui.info('\n' + '\n'.join(output))

        stack.set_outputs(
            provider.get_output_dict(provider_stack))

        return COMPLETE
1373813
def find_template(self, name):
        """"""
        deftemplate = lib.EnvFindDeftemplate(self._env, name.encode())
        if deftemplate == ffi.NULL:
            raise LookupError("Template '%s' not found" % name)

        return Template(self._env, deftemplate)
361107
def exists(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        # Returns an object if stack exists else an exception
        exists = conn.describe_stacks(name)
        log.debug('Stack %s exists.', name)
        return True
    except BotoServerError as e:
        log.debug('boto_cfn.exists raised an exception', exc_info=True)
        return False
440659
def command_template(self):
        
        com_out = self.appname
        arg_string = ""
        flag_string = ""
        # Loop over the key, value pairs in self.args

        for key, val in self.args.items():
            # Check if the value is set in self._options
            # If so, get the value from there
            if val is None:
                opt_val = self._options[key][0]
            else:
                opt_val = val
            opt_type = self._options[key][2]
            if key == 'args':
                # 'args' is special, pull it out and move it to the back
                arg_string += ' {%s}' % key
            elif opt_type is bool:
                if opt_val:
                    flag_string += ' --%s' % (key)
            elif opt_type is list:
                if is_null(opt_val):
                    continue
                elif isinstance(opt_val, str):
                    com_out += ' --%s %s' % (key, opt_val)
                elif isinstance(opt_val, list):
                    for arg_val in opt_val:
                        com_out += ' --%s %s' % (key, arg_val)
            else:
                com_out += ' --%s {%s}' % (key, key)
        com_out += flag_string
        com_out += arg_string
        return com_out
436005
def stack_outputs(self, name):
        
        try:
            stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
            return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']}
        except botocore.client.ClientError:
            return {}
1147633
def on_after_transform_template(self, template):
        
        if self._wait_for_template_active_status and not self._validate_only:
            start_time = time()
            while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS:
                temp = self._in_progress_templates
                self._in_progress_templates = []

                # Check each resource to make sure it's active
                for application_id, template_id in temp:
                    get_cfn_template = (lambda application_id, template_id:
                                        self._sar_client.get_cloud_formation_template(
                                            ApplicationId=self._sanitize_sar_str_param(application_id),
                                            TemplateId=self._sanitize_sar_str_param(template_id)))
                    response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id)
                    self._handle_get_cfn_template_response(response, application_id, template_id)

                # Don't sleep if there are no more templates with PREPARING status
                if len(self._in_progress_templates) == 0:
                    break

                # Sleep a little so we don't spam service calls
                sleep(self.SLEEP_TIME_SECONDS)

            # Not all templates reached active status
            if len(self._in_progress_templates) != 0:
                application_ids = [items[0] for items in self._in_progress_templates]
                raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates "
                                                                "to reach ACTIVE status.")
766790
def has_attribute(self, attribute: str) -> bool:
        
        return any([
            key_node.value == attribute for key_node, _ in self.yaml_node.value
        ])
648873
def retrieve_template(self):
        
        links = self.retrieve_instance_links()
        self.log.debug('Links is \n%s', pformat(links))
        self.pipeline_config['instance_links'].update(links)
        jsondata = get_template(
            template_file='infrastructure/app_data.json.j2',
            appinfo=self.appinfo,
            pipeline_config=self.pipeline_config,
            formats=self.generated,
            run_as_user=DEFAULT_RUN_AS_USER)
        self.log.debug('jsondata is %s', pformat(jsondata))
        return jsondata
829518
def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False):
        
        capabilities = []

        template = name + '-template-' + str(int(time.time())) + '.json'
        with open(template, 'wb') as out:
            out.write(bytes(self.cf_template.to_json(indent=None, separators=(',',':')), "utf-8"))

        self.upload_to_s3(template, working_bucket, disable_progress=disable_progress)
        if self.boto_session.region_name == "us-gov-west-1":
            url = 'https://s3-us-gov-west-1.amazonaws.com/{0}/{1}'.format(working_bucket, template)
        else:
            url = 'https://s3.amazonaws.com/{0}/{1}'.format(working_bucket, template)

        tags = [{'Key': key, 'Value': self.tags[key]}
                for key in self.tags.keys()
                if key != 'ZappaProject']
        tags.append({'Key':'ZappaProject','Value':name})
        update = True

        try:
            self.cf_client.describe_stacks(StackName=name)
        except botocore.client.ClientError:
            update = False

        if update_only and not update:
            print('CloudFormation stack missing, re-deploy to enable updates')
            return

        if not update:
            self.cf_client.create_stack(StackName=name,
                                        Capabilities=capabilities,
                                        TemplateURL=url,
                                        Tags=tags)
            print('Waiting for stack {0} to create (this can take a bit)..'.format(name))
        else:
            try:
                self.cf_client.update_stack(StackName=name,
                                            Capabilities=capabilities,
                                            TemplateURL=url,
                                            Tags=tags)
                print('Waiting for stack {0} to update..'.format(name))
            except botocore.client.ClientError as e:
                if e.response['Error']['Message'] == 'No updates are to be performed.':
                    wait = False
                else:
                    raise

        if wait:
            total_resources = len(self.cf_template.resources)
            current_resources = 0
            sr = self.cf_client.get_paginator('list_stack_resources')
            progress = tqdm(total=total_resources, unit='res', disable=disable_progress)
            while True:
                time.sleep(3)
                result = self.cf_client.describe_stacks(StackName=name)
                if not result['Stacks']:
                    continue  # might need to wait a bit

                if result['Stacks'][0]['StackStatus'] in ['CREATE_COMPLETE', 'UPDATE_COMPLETE']:
                    break

                # Something has gone wrong.
                # Is raising enough? Should we also remove the Lambda function?
                if result['Stacks'][0]['StackStatus'] in [
                                                            'DELETE_COMPLETE',
                                                            'DELETE_IN_PROGRESS',
                                                            'ROLLBACK_IN_PROGRESS',
                                                            'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
                                                            'UPDATE_ROLLBACK_COMPLETE'
                                                        ]:
                    raise EnvironmentError("Stack creation failed. "
                                           "Please check your CloudFormation console. "
                                           "You may also need to `undeploy`.")

                count = 0
                for result in sr.paginate(StackName=name):
                    done = (1 for x in result['StackResourceSummaries']
                            if 'COMPLETE' in x['ResourceStatus'])
                    count += sum(done)
                if count:
                    # We can end up in a situation where we have more resources being created
                    # than anticipated.
                    if (count - current_resources) > 0:
                        progress.update(count - current_resources)
                current_resources = count
            progress.close()

        try:
            os.remove(template)
        except OSError:
            pass

        self.remove_from_s3(template, working_bucket)
1180825
def show_top(queue=False, **kwargs):
    '''
    
    '''
    if 'env' in kwargs:
        # "env" is not supported; Use "saltenv".
        kwargs.pop('env')

    conflict = _check_queue(queue, kwargs)
    if conflict is not None:
        return conflict

    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
    try:
        st_ = salt.state.HighState(opts,
                                   proxy=__proxy__,
                                   initial_pillar=_get_initial_pillar(opts))
    except NameError:
        st_ = salt.state.HighState(opts, initial_pillar=_get_initial_pillar(opts))

    errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
    if errors:
        __context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
        raise CommandExecutionError('Pillar failed to render', info=errors)

    errors = []
    top_ = st_.get_top()
    errors += st_.verify_tops(top_)
    if errors:
        __context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
        return errors
    matches = st_.top_matches(top_)
    return matches
1869
def checkattr(metacls, attr, value):
        
        if not isinstance(value, (
                types.MethodType,
                types.FunctionType,
                classmethod,
                staticmethod,
                property)):
            if attr in dir(type('dummy', (object,), {})) + \
                    ['__metaclass__', '__qualname__']:
                return
            if attr.startswith('_'):
                raise SyntaxError(
                    "TreeModel attribute `{0}` "
                    "must not start with `_`".format(attr))
            if not inspect.isclass(value):
                if not isinstance(value, Column):
                    raise TypeError(
                        "TreeModel attribute `{0}` "
                        "must be an instance of "
                        "`rootpy.tree.treetypes.Column`".format(attr))
                return
            if not issubclass(value, (ROOT.TObject, ROOT.ObjectProxy)):
                raise TypeError(
                    "TreeModel attribute `{0}` must inherit "
                    "from `ROOT.TObject` or `ROOT.ObjectProxy`".format(
                        attr))
1360992
def is_proxy():
    '''
    
    '''
    import __main__ as main
    # This is a hack.  If a proxy minion is started by other
    # means, e.g. a custom script that creates the minion objects
    # then this will fail.
    ret = False
    try:
        # Changed this from 'salt-proxy in main...' to 'proxy in main...'
        # to support the testsuite's temp script that is called 'cli_salt_proxy'
        #
        # Add '--proxyid' in sys.argv so that salt-call --proxyid
        # is seen as a proxy minion
        if 'proxy' in main.__file__ or '--proxyid' in sys.argv:
            ret = True
    except AttributeError:
        pass
    return ret
1049135
def check(cls):
        
        attribs = [
            'app_version',
            'app_name',
            'config_file_path',
            'config_sep_str',
        ]
        for attrib in attribs:
            if getattr(cls, attrib) == 'not_set':
                raise IncompleteSetupError(f'elib_config setup is incomplete; missing: {attrib}')
335303
def get_ext_tops(config):
    '''
    
    '''
    config = copy.deepcopy(config)
    alternatives = {}
    required = ['jinja2', 'yaml', 'tornado', 'msgpack']
    tops = []
    for ns, cfg in salt.ext.six.iteritems(config or {}):
        alternatives[ns] = cfg
        locked_py_version = cfg.get('py-version')
        err_msg = None
        if not locked_py_version:
            err_msg = 'Alternative Salt library: missing specific locked Python version'
        elif not isinstance(locked_py_version, (tuple, list)):
            err_msg = ('Alternative Salt library: specific locked Python version '
                       'should be a list of major/minor version')
        if err_msg:
            raise salt.exceptions.SaltSystemExit(err_msg)

        if cfg.get('dependencies') == 'inherit':
            # TODO: implement inheritance of the modules from _here_
            raise NotImplementedError('This feature is not yet implemented')
        else:
            for dep in cfg.get('dependencies'):
                mod = cfg['dependencies'][dep] or ''
                if not mod:
                    log.warning('Module %s has missing configuration', dep)
                    continue
                elif mod.endswith('.py') and not os.path.isfile(mod):
                    log.warning('Module %s configured with not a file or does not exist: %s', dep, mod)
                    continue
                elif not mod.endswith('.py') and not os.path.isfile(os.path.join(mod, '__init__.py')):
                    log.warning('Module %s is not a Python importable module with %s', dep, mod)
                    continue
                tops.append(mod)

                if dep in required:
                    required.pop(required.index(dep))

            required = ', '.join(required)
            if required:
                msg = 'Missing dependencies for the alternative version' \
                      ' in the external configuration: {}'.format(required)
                log.error(msg)
                raise salt.exceptions.SaltSystemExit(msg)
        alternatives[ns]['dependencies'] = tops
    return alternatives
870830
def do_cli(ctx, template):
    

    sam_template = _read_sam_file(template)

    iam_client = boto3.client('iam')
    validator = SamTemplateValidator(sam_template, ManagedPolicyLoader(iam_client))

    try:
        validator.is_valid()
    except InvalidSamDocumentException as e:
        click.secho("Template provided at '{}' was invalid SAM Template.".format(template), bg='red')
        raise InvalidSamTemplateException(str(e))
    except NoCredentialsError as e:
        raise UserException("AWS Credentials are required. Please configure your credentials.")

    click.secho("{} is a valid SAM Template".format(template), fg='green')
746765
def get_template_setting(template_key, default=None):
    
    templates_var = getattr(settings, 'TEMPLATES', None)
    if templates_var:
        for tdict in templates_var:
            if template_key in tdict:
                return tdict[template_key]
    return default