示例#1
0
def render(  # pylint: disable=too-many-branches
    source, _saltenv, _sls, argline=None, **kwargs
):
    if not isinstance(source, dict):
        raise TypeError(f"Source must be a dict, not {type(source)}")

    selector = "grain"
    default = None
    key = "id"

    if argline:
        for arg in shlex.split(argline):
            try:
                (option, value) = arg.split("=", 2)
            except ValueError:
                option, value = arg, None

            if option in VALID_SELECTORS:
                if not value:
                    raise TemplateError(f"Selector {option!r} needs a value")
                selector = option
                key = value

            elif option == "default":
                if not value:
                    raise TemplateError(f"Option {option!r} needs a value")
                default = value

            else:
                raise TemplateError(f"Unknown option {option!r}")

    if selector == "grain":
        value = traverse_dict_and_list(__grains__, key, default)

    elif selector == "pillar":
        context = kwargs.get("context", {})
        if "pillar" in context:
            value = traverse_dict_and_list(context["pillar"], key, default)
        else:
            value = traverse_dict_and_list(__pillar__, key, default)

    if not value:
        LOG.debug("Skipping blank filter value: %r", value)
        return {}

    # Matching only works on strings
    value = str(value)

    for pattern in source:
        if fnmatch(value, pattern):
            return source[pattern]

    LOG.debug("No pattern matched value: %r", value)

    return {}
示例#2
0
 def get(self, key, default=None, require=False, **kwargs):
     if require:
         default = KeyError(f"Pillar key missing: {key}")
     value = traverse_dict_and_list(self, key, default, **kwargs)
     if isinstance(value, KeyError):
         raise value  # pylint: disable=raising-non-exception
     return value
示例#3
0
 def _tags_from_grain(self, item, grains):
     """
     Define a single tag from a grain value
     """
     tags = set()
     value = datautils.traverse_dict_and_list(
         grains, item, default=None, delimiter=self.options.delimiter)
     if value is None:
         pass
     elif not value:
         pass
     elif isinstance(value, six.string_types):
         if six.PY2:
             tags.add(value.encode('utf-8'))
         else:
             tags.add(value)
     elif isinstance(value, six.binary_type):
         tags.add(value)
     elif isinstance(value, dict):
         raise TypeError
     elif hasattr(value, '__iter__'):
         for nesteditem in value:
             if hasattr(nesteditem, '__iter__'):
                 pass
             elif isinstance(nesteditem, six.string_types):
                 tags.add(nesteditem.encode('utf-8'))
             else:
                 tags.add(nesteditem)
     else:
         tags.add(value)
     return tags
    def _tags_from_grain(self, item, grains):
        """
        Define a single tag from a grain value
        """
        value = datautils.traverse_dict_and_list(
            grains, item, default=None, delimiter=self.options.delimiter)

        return self._tags_from_value(value, 0)
示例#5
0
    def _attribute_from_grain(self, item, grains):
        """
        Provide the value for a single attribute from a grain
        """
        key = item.replace(':', '_')
        value = datautils.traverse_dict_and_list(
            grains, item, default='', delimiter=self.options.delimiter)

        if isinstance(value, list):
            log.warning(
                'Grain \'%s\' is a list. First item selected by default.',
                item)

        return key, ResourceGenerator._get_grain_value(value)
    def _attribute_from_grain(self, item, grains):
        """
        Provide the value for a single attribute from a grain
        """
        key = item.replace(":", "_")
        value = datautils.traverse_dict_and_list(
            grains, item, default="", delimiter=self.options.delimiter)

        if isinstance(value, list):
            LOG.warning(
                "Grain '%s' is a list. First item will be selected by default.",
                item)

        return key, ResourceGenerator._get_grain_value(value, 0)
示例#7
0
def sign(csr):
    """
    Requests to sign a CSR using dehydrated.

    csr:
        Certificate signing request as PEM-encoded string.
    """

    # Restores newlines in a PEM files that might have been lost by salt
    # argument parsing.
    match = _REGEXP_CSR.match(csr)
    if match:
        _, head, body, tail = match.groups()
        csr = "\n".join([head, *body.strip().split(" "), tail])

    requested = _extract_domain_names(csr)
    auth_file = traverse_dict_and_list(__opts__, "acme:runner:auth_file", None)
    if auth_file:
        logging.debug("Use auth_file from %s", auth_file)

        with fopen(auth_file, "r") as f:
            auth = yaml.safe_load(f)

        if not isinstance(auth, dict):
            raise SaltConfigurationError("Invalid auth_file: must be a dict")

        logging.debug("Authorizing domain names for %s: %s", __opts__["id"],
                      requested)

        for pattern, auth in auth.items():
            if not fnmatch.fnmatch(__opts__["id"], pattern):
                continue

            for name in requested.copy():
                for rule in auth:
                    if fnmatch.fnmatch(name, rule):
                        requested.remove(name)

        if requested:
            raise AuthorizationError(
                f"Unauthorized domains: {', '.join(requested)}")

    return __salt__["salt.cmd"]("acme.sign", csr)
示例#8
0
 def get(self, key, default=None, **kwargs):
     return traverse_dict_and_list(self, key, default, **kwargs)
示例#9
0
def get(key, default='', delimiter=':', merge=None, omit_opts=False,
        omit_pillar=False, omit_master=False, omit_grains=False):
    if merge is None:
        if not omit_opts:
            ret = traverse_dict_and_list(
                __opts__,
                key,
                '_|-',
                delimiter=delimiter)
            if ret != '_|-':
                return sdb.sdb_get(ret, __opts__)

        if not omit_grains:
            ret = traverse_dict_and_list(
                __grains__,
                key,
                '_|-',
                delimiter)
            if ret != '_|-':
                return sdb.sdb_get(ret, __opts__)

        if not omit_pillar:
            ret = traverse_dict_and_list(
                __pillar__,
                key,
                '_|-',
                delimiter=delimiter)
            if ret != '_|-':
                return sdb.sdb_get(ret, __opts__)

        if not omit_master:
            ret = traverse_dict_and_list(
                __pillar__.get('master', {}),
                key,
                '_|-',
                delimiter=delimiter)
            if ret != '_|-':
                return sdb.sdb_get(ret, __opts__)

        ret = traverse_dict_and_list(
            DEFAULTS,
            key,
            '_|-',
            delimiter=delimiter)
        log.debug("key: %s, ret: %s", key, ret)
        if ret != '_|-':
            return sdb.sdb_get(ret, __opts__)
    else:
        if merge not in ('recurse', 'overwrite'):
            log.warning('Unsupported merge strategy \'{0}\'. Falling back '
                        'to \'recurse\'.'.format(merge))
            merge = 'recurse'

        data = copy.copy(DEFAULTS)
        data = salt.utils.dictupdate.merge(data, __pillar__.get('master', {}), strategy=merge)
        data = salt.utils.dictupdate.merge(data, __pillar__, strategy=merge)
        data = salt.utils.dictupdate.merge(data, __grains__, strategy=merge)
        data = salt.utils.dictupdate.merge(data, __opts__, strategy=merge)
        ret = traverse_dict_and_list(
            data,
            key,
            '_|-',
            delimiter=delimiter)
        if ret != '_|-':
            return sdb.sdb_get(ret, __opts__)

    return default