Package: emrichen
Emrichen – Template engine for YAML & JSONEmrichen takes in templates written in YAML or JSON, processes tags that do things like variable substitution, and outputs YAML or JSON.What makes Emrichen better for generating YAML or JSON than a text-based template system is that it workswithinYAML (or JSON).Ever tried substituting a list or dict into a YAML document just to run into indentation issues? Horrible! Handling quotation marks and double backslash escapes? Nope!In Emrichen, variables are typed in the familiar JSON types, making these a non-issue. Emrichen is a pragmatic and powerful way to generate YAML and JSON.Consider the following template that produces a minimal Kubernetes deployment:!Defaultstag:latestimage:!Format"nginx:{tag}"replicas:3---apiVersion:apps/v1kind:Deploymentmetadata:name:nginxspec:selector:matchLabels:app:nginxreplicas:!Varreplicastemplate:metadata:labels:app:nginxspec:containers:-name:nginximage:!Varimageports:-containerPort:80This small template already demonstrates three of Emrichen's powerful tags:!Defaultsthat provides default values for variables;!Varthat performs simple variable substitution; and!Formatthat performs string formatting.Put it in a file, say,nginx.in.yaml(we use.in.yamlto denote templates) and render it using this command:emrichen nginx.in.yamlPrefer JSON output?emrichen --output-format json nginx.in.yamlWanna change the tag?emrichen --define tag=1-alpine nginx.in.yamlNote howimageis evaluated lazily – you need not overrideimagejust to changetag!See below for a table of supported tags. There's a lot of them. If you need one that's not there yet, please shoot us an issue or PR.InstallationPython 3.6+ required. Python 2 is not and will not be supported.pip install emrichenIf you have cloned Emrichen from GitHub (for development):pip install -e .Supported tagsTagArgumentsExampleDescription!AllAn iterable!All [true, false]Returns true iff all the items of the iterable argument are truthy.!AnyAn iterable!Any [true, false]Returns true iff at least one of the items of the iterable argument is truthy.!Base64The value to encode!Base64 foobarEncodes the value (or a string representation thereof) into base64.!Composevalue: The value to apply tags ontags: A list of tag names to apply, latest first!Base64,Var fooUsed internally to implement tag composition.Usually not used in the spelt-out form.SeeTag compositionbelow.!ConcatA list of lists!Concat [[1, 2], [3, 4]]Concatenates lists.!DebugAnything, really!Debug,Var fooEnriches its argument, outputs it to stderr and returns it. Useful to check the valueof some expression deep in a big template, perhaps even one that doesn't even fully render.!DefaultsA dict of variable definitionsSeeexamples/defaults/Defines default values for variables. These will be overridden by any other variable source.NOTE:!Defaultsmust appear in a document of its own in the template file (ie. separated by---).   The document containing!Defaultswill be erased from the output.!ErrorError message!Error "Must define either foo or bar, not both"If the!Errortag is present in the template after resolving all conditionals,it will cause the template rendering to exit with error emitting the specified error message.!ExistsJSONPath expression!Exists fooReturnstrueif the JSONPath expression returns one or more matches,falseotherwise.!Filtertest,overSeetests/test_cond.pyTakes in a list and only returns elements that pass a predicate.!FormatFormat string!Format "{foo} {bar!d}"Interpolate strings usingPython format strings.JSONPath supported in variable lookup (eg.{people[0].first_name}will do the right thing).NOTE:When the format string starts with{, you need to quote it in order to avoid being interpreted as a YAML object.!GroupAccepts the same arguments as!Loop, excepttemplateis optional (default identity), plus the following:by: (required) An expression used to determine the key for the current valueresult_as: (optional, string) When evaluatingby, the enrichedtemplateis available under this name.TBDMakes a dict out of a list. Keys are determined byby. Items with the same key are grouped in a list.!Iftest,then,elseSeetests/test_cond.pyReturns one of two values based on a condition.!IncludePath to a template to include!Include ../foo.ymlRenders the requested template at this location. Both absolute and relative paths work.!IncludeBase64Path to a binary file!IncludeBase64 ../foo.pdfLoads the given binary file and returns the contents encoded as Base64.!IncludeBinaryPath to a binary file!IncludeBinary ../foo.pdfLoads the given binary file and returns the contents as bytes.  This is practically only useful for hashing.!IncludeGlobA string (or a list thereof) of glob patterns of templates to include!IncludeGlob bits/**.in.ymlExpands the glob patterns and renders all templates into a list.YAML files that contain more than one document will have all of those templates rendered intothe same flat list.Expansion results are lexicographically sorted.As with Python'sglob.glob(), use a double star (**) for recursion.!IncludeTextPath to an UTF-8 text file!IncludeText ../foo.tomlLoads the given UTF-8 text file and returns the contents as a string.!IndexAccepts the same arguments as!Loop, excepttemplateis optional (default identity), plus the following:by: (required) An expression used to determine the key for the current valueresult_as: (optional, string) When evaluatingby, the enrichedtemplateis available under this name.duplicates: (optional, defaulterror)error,warn(ing)orignoreduplicate values.TBDMakes a dict out of a list. Keys are determined byby.!IsBooleanData to typecheck.!IsBoolean ...Returns True if the value enriched is of the given type, False otherwise.!IsDictData to typecheck.!IsDict ...Returns True if the value enriched is of the given type, False otherwise.!IsIntegerData to typecheck.!IsInteger ...Returns True if the value enriched is of the given type, False otherwise.!IsListData to typecheck.!IsList ...Returns True if the value enriched is of the given type, False otherwise.!IsNoneData to typecheck.!IsNone ...Returns True if the value enriched is None (null) or Void, False otherwise.!IsNumberData to typecheck.!IsNumber ...Returns True if the value enriched is of the given type, False otherwise.!IsStringData to typecheck.!IsString ...Returns True if the value enriched is of the given type, False otherwise.!Joinitems: (required) A list of items to be joined together.separator: (optional, default space) The separator to place between the items.ORa list of items to be joined together with a space as the separator.!Join [foo, bar]!Join { items: [foo, bar], separator: ', ' }Joins a list of items together with a separator. The result is always a string.!LookupJSONPath expression!Lookup people[0].first_namePerforms a JSONPath lookup returning the first match. If there is no match, an error is raised.!LookupAllJSONPath expression!LookupAll people[*].first_namePerforms a JSONPath lookup returning all matches as a list. If no matches are found, the empty list[]is returned.!Loopover: (required) The data to iterate over (a literal list or dict, or !Var)as: (optional, defaultitem) The variable name given to the current valueindex_as: (optional) The variable name given to the loop index. If over is a list, this is a numeric index starting from0. If over is a dict, this is the dict key.index_start: (optional, default0) First index, for eg. 1-based indexing.previous_as: (optional) The variable name given to the previous value. On the first iteration of the loop, the previous value isnull.Added in 0.2.0template: (required) The template to process for each iteration of the loop.as_documents: (optional) Whether to "unfold" the output of this loop into separate YAML documents when writing YAML. Only has an effect at the top level of a template.Seeexamples/loop/.Loops over a list or dict and renders a template for each iteration. The output is always a list.!MD5Data to hash!MD5 'some data to hash'Hashes the given data using the MD5 algorithm. If the data is not binary, it is converted to UTF-8 bytes.!MergeA list of dicts!Merge [{a: 5}, {b: 6}]Merges objects. For overlapping keys the last one takes precedence.!Nota value!Not !Var fooLogically negates the given value (in Python semantics).!Opa,op,bSeetests/test_cond.pyPerforms binary operators. Especially useful with!Ifto implement greater-than etc.!SHA1Data to hash!SHA1 'some data to hash'Hashes the given data using the SHA1 algorithm. If the data is not binary, it is converted to UTF-8 bytes.!SHA256Data to hash!SHA256 'some data to hash'Hashes the given data using the SHA256 algorithm. If the data is not binary, it is converted to UTF-8 bytes.!URLEncodeA string to encodeORurl: The URL to combine query parameters intoquery: An object of query string parameters to add OR a string of query string parameters!URLEncode "foo+bar"!URLEncode { url: "https://example.com/", query: { foo: bar } }Encodes strings for safe inclusion in a URL, or combines query string parameters into a URL.!VarVariable name!Var image_nameReplaced with the value of the variable.!VoidAnything or nothingfoo: !VoidThe dict key, list item or YAML document that resolves to!Voidis removed from the output.!Withvars: A dict of variable definitions.template: The template to process with the variables defined.Seeexamples/with/.Binds local variables that are only visible withintemplate. Useful for giving a name for common sub-expressions.Tags in JSONJSON doesn't have a native tag construct. Instead, use an object with a single key that is the name of the tag (including the bang, eg.!Var). For example:{"foo":{"!Var":"foo"}}Limitations of the JSON support:Object keys starting with!are not supported.A template rendered as JSON may only contain a single document.JSON templates always have a single document only.YAML templates may only contain a single non-!Void, non-!Defaultsdocument.As!Defaultsmust appear in a document of its own, it's not supported in JSON templates. Use a var file instead.Tag compositionDue to YAML, you can't do!Base64 !Var foo. We provide a convenient workaround:!Base64,Var foo.Custom tagsIt is possible to implement your own custom tags in Python. Tags are classes that inherit from theemrichen.tags.base.BaseTagclass and implement theenrich(self, context: emrichen.context.Context)method. For examples of tag implementations, see the built-in tags underemrichen/tags/or the example attests/custom_tags/.Place the implementation in a Python module that is on thePYTHONPATH. Same directory as the template is usually fine.All subclasses ofBaseTagare automatically registered as long as the module containing them is imported. If you are using the CLI, add-m your_tagsto the command line whereyour_tagscorresponds toyour_tags.py. If you are using Emrichen programmatically, be sure to import your custom tags (import your_tags) before instantiating a template.There is an example of custom tags that you can try out as follows (provided you have cloned Emrichen from GitHub and installed it usingpip install -e .). The example is not installed when installing Emrichen from PyPI (pip install emrichen).emrichen -m tests.custom_tags examples/custom_tags.ymlThe example defines a!KubeEnvcustom tag that turns a dictionary of key—value mappings into a list of environment variables in the format expected by Kubernetes.CLIusage: emrichen [-h] [--template-format {yaml,json}] [--var-file VAR_FILE]
usage: emrichen [-h] [--template-format {yaml,json}] [--var-file VAR_FILE]
                [--define VAR=VALUE] [--output-file OUTPUT_FILE]
                [--output-format {yaml,json,pprint}] [--include-env]
                [template_file]

A YAML to YAML preprocessor.

positional arguments:
  template_file         The YAML template to process. If unspecified, the
                        template is read from stdin.

optional arguments:
  -h, --help            show this help message and exit
  --template-format {yaml,json}
                        Template format. If unspecified, attempted to be
                        autodetected from the input filename (but defaults to
                        YAML).
  --var-file VAR_FILE, -f VAR_FILE
                        A YAML file containing an object whose top-level keys
                        will be defined as variables. May be specified
                        multiple times.
  --define VAR=VALUE, -D VAR=VALUE
                        Defines a single variable. May be specified multiple
                        times.
  --output-file OUTPUT_FILE, -o OUTPUT_FILE
                        Output file. If unspecified, the template output is
                        written into stdout.
  --output-format {yaml,json,pprint}
                        Output format. If unspecified, attempted to be
                        autodetected from the output filename (but defaults to
                        YAML).
  --include-env, -e     Expose process environment variables to the template.

Variable precedence: -D > -e > -f > !DefaultsExamplescd examples/kubernetes
emrichen -f vars.yml -D tag=build-256 deployment.in.ymlPython APITODOemrichen(template, *variable_sources, **override_variables)Context(*variable_sources, **override_variables)Template(template_source)LicenseThe MIT License (MIT)

Copyright © 2018–2022 Santtu Pajukanta
Copyright © 2018–2022 Aarni Koskela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.