Git Product home page Git Product logo

emrichen's Introduction

Emrichen – Template engine for YAML & JSON

Build Status PyPI version

Emrichen 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 works within YAML (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:

!Defaults
tag: latest
image: !Format "nginx:{tag}"
replicas: 3
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: !Var replicas
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: !Var image
        ports:
        - containerPort: 80

This small template already demonstrates three of Emrichen's powerful tags: !Defaults that provides default values for variables; !Var that performs simple variable substitution; and !Format that performs string formatting.

Put it in a file, say, nginx.in.yaml (we use .in.yaml to denote templates) and render it using this command:

emrichen nginx.in.yaml

Prefer JSON output?

emrichen --output-format json nginx.in.yaml

Wanna change the tag?

emrichen --define tag=1-alpine nginx.in.yaml

Note how image is evaluated lazily – you need not override image just to change tag!

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.

Installation

Python 3.7+ required.

pip install emrichen

If you have cloned Emrichen from GitHub (for development):

pip install -e .

Supported tags

Tag Arguments Example Description
!All An iterable !All [true, false] Returns true iff all the items of the iterable argument are truthy.
!Any An iterable !Any [true, false] Returns true iff at least one of the items of the iterable argument is truthy.
!Base64 The value to encode !Base64 foobar Encodes the value (or a string representation thereof) into base64.
!Compose value: The value to apply tags on
tags: A list of tag names to apply, latest first
!Base64,Var foo Used internally to implement tag composition.
Usually not used in the spelt-out form.
See Tag composition below.
!Concat A list of lists !Concat [[1, 2], [3, 4]] Concatenates lists.
!Debug Anything, really !Debug,Var foo Enriches its argument, outputs it to stderr and returns it. Useful to check the value
of some expression deep in a big template, perhaps even one that doesn't even fully render.
!Defaults A dict of variable definitions See examples/defaults/ Defines default values for variables. These will be overridden by any other variable source.
NOTE: !Defaults must appear in a document of its own in the template file (ie. separated by ---). The document containing !Defaults will be erased from the output.
!Error Error message !Error "Must define either foo or bar, not both" If the !Error tag is present in the template after resolving all conditionals,
it will cause the template rendering to exit with error emitting the specified error message.
!Exists JSONPath expression !Exists foo Returns true if the JSONPath expression returns one or more matches, false otherwise.
!Filter test, over See tests/test_cond.py Takes in a list and only returns elements that pass a predicate.
!Format Format string !Format "{foo} {bar!d}" Interpolate strings using Python 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.
!Group Accepts the same arguments as !Loop, except template is optional (default identity), plus the following:
by: (required) An expression used to determine the key for the current value
result_as: (optional, string) When evaluating by, the enriched template is available under this name.
TBD Makes a dict out of a list. Keys are determined by by. Items with the same key are grouped in a list.
!If test, then, else See tests/test_cond.py Returns one of two values based on a condition.
!Include Path to a template to include !Include ../foo.yml Renders the requested template at this location. Both absolute and relative paths work.
!IncludeBase64 Path to a binary file !IncludeBase64 ../foo.pdf Loads the given binary file and returns the contents encoded as Base64.
!IncludeBinary Path to a binary file !IncludeBinary ../foo.pdf Loads the given binary file and returns the contents as bytes. This is practically only useful for hashing.
!IncludeGlob A string (or a list thereof) of glob patterns of templates to include !IncludeGlob bits/**.in.yml Expands 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 into
the same flat list.
Expansion results are lexicographically sorted.
As with Python's glob.glob(), use a double star (**) for recursion.
!IncludeText Path to an UTF-8 text file !IncludeText ../foo.toml Loads the given UTF-8 text file and returns the contents as a string.
!Index Accepts the same arguments as !Loop, except template is optional (default identity), plus the following:
by: (required) An expression used to determine the key for the current value
result_as: (optional, string) When evaluating by, the enriched template is available under this name.
duplicates: (optional, default error) error, warn(ing) or ignore duplicate values.
TBD Makes a dict out of a list. Keys are determined by by.
!IsBoolean Data to typecheck. !IsBoolean ... Returns True if the value enriched is of the given type, False otherwise.
!IsDict Data to typecheck. !IsDict ... Returns True if the value enriched is of the given type, False otherwise.
!IsInteger Data to typecheck. !IsInteger ... Returns True if the value enriched is of the given type, False otherwise.
!IsList Data to typecheck. !IsList ... Returns True if the value enriched is of the given type, False otherwise.
!IsNone Data to typecheck. !IsNone ... Returns True if the value enriched is None (null) or Void, False otherwise.
!IsNumber Data to typecheck. !IsNumber ... Returns True if the value enriched is of the given type, False otherwise.
!IsString Data to typecheck. !IsString ... Returns True if the value enriched is of the given type, False otherwise.
!Join items: (required) A list of items to be joined together.
separator: (optional, default space) The separator to place between the items.
OR
a 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.
!Lookup JSONPath expression !Lookup people[0].first_name Performs a JSONPath lookup returning the first match. If there is no match, an error is raised.
!LookupAll JSONPath expression !LookupAll people[*].first_name Performs a JSONPath lookup returning all matches as a list. If no matches are found, the empty list [] is returned.
!Loop over: (required) The data to iterate over (a literal list or dict, or !Var)
as: (optional, default item) The variable name given to the current value
index_as: (optional) The variable name given to the loop index. If over is a list, this is a numeric index starting from 0. If over is a dict, this is the dict key.
index_start: (optional, default 0) 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 is null. Added in 0.2.0
template: (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.
See examples/loop/. Loops over a list or dict and renders a template for each iteration. The output is always a list.
!MD5 Data 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.
!Merge A list of dicts !Merge [{a: 5}, {b: 6}] Merges objects. For overlapping keys the last one takes precedence.
!Not a value !Not !Var foo Logically negates the given value (in Python semantics).
!Op a, op, b See tests/test_cond.py Performs binary operators. Especially useful with !If to implement greater-than etc.
!SHA1 Data 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.
!SHA256 Data 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.
!URLEncode A string to encode
OR
url: The URL to combine query parameters into
query: 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.
!Var Variable name !Var image_name Replaced with the value of the variable.
!Void Anything or nothing foo: !Void The dict key, list item or YAML document that resolves to !Void is removed from the output.
!With vars: A dict of variable definitions.
template: The template to process with the variables defined.
See examples/with/. Binds local variables that are only visible within template. Useful for giving a name for common sub-expressions.

Tags in JSON

JSON 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-!Defaults document.
  • As !Defaults must appear in a document of its own, it's not supported in JSON templates. Use a var file instead.

Tag composition

Due to YAML, you can't do !Base64 !Var foo. We provide a convenient workaround: !Base64,Var foo.

Custom tags

It is possible to implement your own custom tags in Python. Tags are classes that inherit from the emrichen.tags.base.BaseTag class and implement the enrich(self, context: emrichen.context.Context) method. For examples of tag implementations, see the built-in tags under emrichen/tags/ or the example at tests/custom_tags/.

Place the implementation in a Python module that is on the PYTHONPATH. Same directory as the template is usually fine.

All subclasses of BaseTag are automatically registered as long as the module containing them is imported. If you are using the CLI, add -m your_tags to the command line where your_tags corresponds to your_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 using pip install -e .). The example is not installed when installing Emrichen from PyPI (pip install emrichen).

emrichen -m tests.custom_tags examples/custom_tags.yml

The example defines a !KubeEnv custom tag that turns a dictionary of key—value mappings into a list of environment variables in the format expected by Kubernetes.

CLI

usage: 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 > !Defaults

Examples

cd examples/kubernetes
emrichen -f vars.yml -D tag=build-256 deployment.in.yml

Python API

TODO

emrichen(template, *variable_sources, **override_variables)

Context(*variable_sources, **override_variables)

Template(template_source)

License

The 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.

emrichen's People

Contributors

akx avatar dkreuer avatar japsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

emrichen's Issues

Write !If tag to CommentedSeq

Thank you for putting together this awesome package.

I'm struggling to figure out how to yaml.dump a file containing an !If tag (in this case, within a CommentedSeq).

I'm probably missing something obvious but can't seem to figure it out. Any help much appreciated. Thank you!

Join Lists

Hi,

is there a way to join two lists? E.g.:

!Defaults
lamps:
  - {name: "lamp a"}
  - {name: "lamp b"}
sockets:
  - {name: "socket a"}
---
all_devices:
  !Loop
    over: !JoinLists lamps sockets
    as: device
    template:
      name: !Lookup device.name

Or, even better join them direcly in the Defaults section:

!Defaults
lamps:
  - {name: "lamp a"}
  - {name: "lamp b"}
sockets:
  - {name: "socket a"}
devices: !JoinLists lamps sockets
---

Did I miss something or is there currently no way to do this?

Use setup.py entry_points to discover Custom Tags

Hi,

I would like to propose using entry_points as another way of finding and loading custom tags.

This makes sharing and using tag implementations easier - avoids the need to specify them on every emrichen call (with -m mytag) and users can just pip install the package with the tag implementation (effectively becoming plugins)

If maintainers agree with the feature I would be happy to open a PR

`!Lookup` does not enrich on the fly

Template:

!Defaults
x:
  y: 5
z: !Var x
---
workie: !Lookup x.y
no_workie: !Lookup z.y

Expected output:

workie: 5
no_workie: 5

Actual output:

Traceback (most recent call last):
  File "/usr/local/bin/emrichen", line 11, in <module>
    load_entry_point('emrichen', 'console_scripts', 'emrichen')()
  File "/Users/sapaj1/Hobby/emrichen/emrichen/__main__.py", line 111, in main
    output = template.render(context, format=args.output_format)
  File "/Users/sapaj1/Hobby/emrichen/emrichen/template.py", line 22, in render
    enriched = self.enrich(context)
  File "/Users/sapaj1/Hobby/emrichen/emrichen/template.py", line 19, in enrich
    return context.enrich(self.template)
  File "/Users/sapaj1/Hobby/emrichen/emrichen/context.py", line 37, in enrich
    item = self.enrich(item)
  File "/Users/sapaj1/Hobby/emrichen/emrichen/context.py", line 30, in enrich
    val = self.enrich(val)
  File "/Users/sapaj1/Hobby/emrichen/emrichen/context.py", line 21, in enrich
    return self.enrich(value.enrich(self))
  File "/Users/sapaj1/Hobby/emrichen/emrichen/tags/lookup.py", line 19, in enrich
    raise KeyError(f'{self}: no matches for {self.data}')
KeyError: "Lookup('z.y'): no matches for z.y"

Co-operate with formats that use tags of their own such as CloudFormation

CloudFormation has its own functions such as !Subst and !Join etc. In order to be able to input and output CloudFormation templates, Emrichen needs a way to co-operate with foreign tags.

(Bad) options:

  1. Keep disallowing foreign tags and require CloudFormation users to use the { "Fn::Join": […] } form of CFN functions instead of the tag-based !Join form
  2. Prefix our own tags with some prefix, reducing the risk of collision, and pass foreign tags to the output as-is.
  3. Require foreign tags to be prefixed and strip the prefix upon processing

Unable to merge(?) an array with !Includes

sorry if this is just pebcak but .. i tried for 2 hours now and cant get anything to work.. i am trying to do something similar to #42 where my input is

!Defaults
butane_version: 1.1.0
---
variant: flatcar
version: !Var butane_version

storage:
  links: 
    !Include "links-ALL.yaml"
    !Include "links-docker_compose.yaml"
    - path: /tmp/test
      target: /tmp/blubb
      hard: false

links-ALL.yaml:

---
- path: /etc/localtime
  overwrite: true
  target: /usr/share/zoneinfo/Europe/Vienna
- path: /etc/systemd/system/multi-user.target.wants/docker.service
  target: /usr/lib/systemd/system/docker.service
  hard: false
  overwrite: true

links-docker_compose.yaml:

---
- path: /etc/extensions/docker_compose.raw
  target: /opt/extensions/docker_compose/docker_compose.raw
  hard: false

the expected outcome would be (reduced to relevant part):

storage:
  links: 
  - path: /etc/localtime
    overwrite: true
    target: /usr/share/zoneinfo/Europe/Vienna
  - path: /etc/systemd/system/multi-user.target.wants/docker.service
    target: /usr/lib/systemd/system/docker.service
    hard: false
    overwrite: true
  - path: /etc/extensions/docker_compose.raw
    target: /opt/extensions/docker_compose/docker_compose.raw
    hard: false
    - path: /tmp/test
      target: /tmp/blubb
      hard: false

however, regardless of what i try, nothing seems to work.
i tried various combinations of !Merge and !Concat and !IncludeGlob (with a non wildcard specific filename) but all of it just throws various errors..

can someone enlighten me what the right way to do this would be? :) much appreciated...

Only truncate --output-file after enriching

Consider the following files:

# a.yaml
a: 1
b: 2

# a.in.yaml – template
!Merge
  - !Include a.yaml
  - !Include a.update.yaml

# a.update.yaml – an incremental update to a.yaml
b: 3

Now, if you run emrichen --output-file a.yaml a.in.yaml, the resulting a.yaml will only contain

b: 3

instead of

a: 1
b: 3

because --output-file a.yaml is opened at application startup with w mode, truncating the file, and !Include a.yaml enriches to {}.

I would like to change this so that !Include a.yaml here would enrich to the original contents of a.yaml, and a.yaml would be opened for writing only after enriching the template.

Umlauts

I just had a Loop replace the german umlaut "ü" with \xFC which is ugly.

Escape {{}} during !Format

When input is

image: !Format "{replaceme_with_var} {{dont_replaceme}}"

Should output as:

image: foo {dont_replaceme}

is there support for this?

Implement conditionals

Use cases:

  • If the condition is met, return this value, otherwise return that value
  • If the condition is met, define this key in a dict, otherwise leave it out
  • If the condition is met, include this element in a list, otherwise leave it out

Simple conditions (Python truthiness of a value) are easy to implement. How about complex predicates (==, <, <=, >, >= etc.)?

Switching to a JSONPath implementation that supports ? is one option. Then we could just use !Lookup in the condition.

We do not want to execute Python to resolve the condition.

Typecheck functions not working

Hi,

I've noticed that the typecheck functions are always returning false on my install.

I'm running Ubuntu 22.04 with Python 3.10.12 and have installed emrichen 0.4.0 via pip install emrichen at version.

# x.yml
!Defaults

number: 1234
dict:
  key: 4321

---
test_number_isnumber: !IsNumber number
test_dict_isdict: !IsDict dict

test_number_isinteger: !IsInteger number

test_number_isstring: !IsString number
test_dict_isstring: !IsString dict
$ emrichen < x.yml 
> test_number_isnumber: false
> test_dict_isdict: false
> test_number_isinteger: false
> test_number_isstring: true
> test_dict_isstring: true

Give variable defaults in the template file

It was suggested the template file could include defaults for variables if the author so desires.

Perhaps it could leverage multi-document YAML files and look like this:

!Defaults
  foo: bar
  quux: 5
---
this_is_foo: !Var foo
also_quux: !Var quux

Output:

this_is_foo: bar
also_quux: 5

The document containing !Defaults may contain only that, it does not matter where in the document !Defaults is specified, there may be multiple documents containing !Defaults, latest wins, and any document containing !Defaults is erased from the output.

Help with !If omitting value in flow style list

I have recently been using emrichen to template yml concourse configuration files but I have run into a snag with !If.
I want to be able to omit a value in a list based on a variable. Here is the file I'm trying to template:

resources:
  - name: gitflow-test-git
    type: git
    icon: github
    source:
      uri: <SNIP>
      branch: master
      username: concourse
      password: <SNIP>

jobs:
  - name: build
    public: true
    plan:
      - get: gitflow-test-git
        trigger: true
      - task: build
        file: gitflow-test-git/ci/build.yml
        params:
          VERSION: !Var VERSION
          VERSION_MAJOR: !Var VERSION_MAJOR
          VERSION_MINOR: !Var VERSION_MINOR
          VERSION_PATCH: !Var VERSION_PATCH
          BRANCH: !Var BRANCH

      !If
        test: !Op [master, eq, !Var BRANCH]
        then:
          - task: deploy-prod
            file: gitflow-test-git/ci/deploy-prod.yml
        else: !Void

Ignoring the concourse jargon I want to be able to omit the deploy-prod task when branch resolves to non-master. I have been able to get the !If block to work when it is the only thing in the file. Eg:

echo "!If
           test: !Op [master, eq, !Var BRANCH]
           then:
             - task: deploy-prod
               file: gitflow-test-git/ci/deploy-prod.yml
           else: !Void" | emrichen --define "BRANCH=master"

resolves correctly to

- task: deploy-prod
  file: gitflow-test-git/ci/deploy-prod.yml

or

This may or not be a bug, I am somewhat new to yml and even newer to emrichen so please let me know the correct usage to achieve my desired functionality.

!Include doesn't indent?

collections:
  !Include ./configs/card1.yaml

Should indent each line of card1.yaml by 2, but it doesn't, which makes invalid YAML out of two valid YAMLs, right?

Please consider a new name

The name emrichen is easily confused with the very popular emscripten project. This project name is sharing the same start, middle character, and ending of the other word, which makes differentiating the two more difficult than it should be. Please consider a different name to make recall and reference of this project easier for everybody.

Thank you for releasing this tool.

Max recursion depth error

Would it be possible to make something like this work without a Max recursion error?

#original.yaml
!Defaults
name: John
---
greeting: !Format "Hi {name}!" 


#composed.yaml
!With
template: !Include original.yaml
vars: 
    name: !Format "{name} and Mark" 

I assume it is because we are referring to name in the definition of name: in composed.yaml, but I would expect that it would use the then already existing John default from original.yaml, resulting in "Hi John and Mark"

Dynamically generated dict keys

I'm trying to use emrichen as a preprocessor for HomeAssistant configuration files.
I need to be able to generate YAML-code like this:

homeassistant:
  customize:
    light.asdf:
      hidden: true
    light.foobar:
      hidden: true

My current emrichen template looks like this:

!Defaults
lamps:
  - {name: asdf, id: 123}
  - {name: foobar, id: 456}
---
homeassistant:
  customize:
	!Loop2
      over: !Var lamps
      as: lamp
      template:
        !Format "light.{lamp.name}":
          hidden: true

Is there a way to achieve this?

Multiple Include in the same level

Consider this, a.yml:

a: 1

And b.yml:

b: 2

Template ab.yml:

ab:
  !Include 1.yml
  !Include 2.yml

emrichen -f ab.yml is stuck and hangs.

But expected, ab.yml:

ab:
   a: 1
   b: 2

It might be related to this #20

Serializable BaseTag?

Looking to use templates to generate templates, but the challenge is supporting the yaml serialization of those that implement BaseTag, especially with nested expressions. Not sure if it makes sense to adopt Yamlable for better serialization support.

Loop over a variable that contains a list

Eg.

!Loop
  over: domain_names
  as: domain_name
  index_as: domain_index
  template:
    apiVersion: v1
    kind: DomainName
    metadata:
      name: !Var domain_name
      

Always produces a list.

String interpolation

Perhaps with an explicit tag like

!Format "{repository}:{tag}"

Or even make all string literals Jinja2 templates? It would certainly be pragmatic, but it would also reduce the ideological purity of the tool greatly.

Reference the Defaults dict

Hello,

Thank you for this tool, it's awesome.

Is there a way to reference the full list of Defaults to achieve something like:

apiVersion: v1
kind: ConfigMap

metadata:
  namespace: !Var namespace
  name: !Var name

data: !Var AllTheDefaults

I've been trying

  • !LookupAll "$" -- this should be the reference to the root dict but it errors out with "maximum recursion depth exceeded"
  • !LookupAll "*" -- this would likely create a new list of values from the root dict (I want the names too)
  • !Index {over: !LookupAll "$", ...} -- maximul recursion again

Preserve comments

This appears, at least with the limited testing I've done, to remove comments from my template files. This wouldn't be such a big deal, but there is one specific use case where it is, which is making the user-data file for cloud-init images. The first line of the file, must be #cloud-config. I am not sure if this is a packer requirement, or cloud init or AutoInstall, but it needs to be there none the less. Is it possible to ensure that comments are left in the output file?

!Loop - without a list

i am trying to render multiple deployments based on a variable

vars.yaml

backend_mutations:
  - name: backend
    command: /run.sh
    replicas: 1
  - name: backend-editors
    command: /run.sh
    replicas: 1
  - name: backend-cron
    command: /cron.sh
    replicas: 1

template.yaml
(redacted the rest of the deployment spec.)

!Loop
  over: !Var backend_mutations
  as: backend
  index_as: id
  template:
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: !Lookup backend.name
      labels:
        krn: !Lookup backend.name

the problem is that !Loop produces a list. which is not apply'able to K8s.

ideally i would like to generate a single output file with multiple yaml files in it. seperated by ---

like my supposed output would be like:

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  labels:
    krn: backend
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend-editors
  labels:
    krn: backend-editors
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend-cron
  labels:
    krn: backend-cron
---

is there anything i am missing - or is it currently not possible?

Typecasting?

I ran into an issue where I was trying to make a kubernetes manifest for a volumeMount and I wanted to make it configurable whether or not the volume was readOnly. I'm just using --include-env which means that when I provide the environment variable false it gets turned into the string 'false'.

I ended up doing

!Defaults
read_only_bool: !Op [!Var read_only, eq, 'true']

But it seems like it would be nice to have like a

read_only_bool: !Coerce [Boolean, !Var read_only]

That could apply standard yaml type guessing to the string and throw an error if it wasn't right (e.g. if you provided read_only=5 that would be a number and so would throw an error, or if you Coerced to numeric then you would end up with an error if you provided the string 'false'.)

Nested templating variable precedence

Hi,

Considering a template like

# generic.yaml
!Defaults
name: Unknown name
greeting: Unknown greeting
---
phrase: !Format "{greeting} {name}"

Which is templated once, with results as expected (phrase: Hello Mark):

# hello_mark.yaml
!With
template: generic.yaml
vars:
    name: Mark
    greeting: Hello

and then another template on top of the previous one

# hello_john.yaml
!With
template: hello_mark.yaml
vars:
    name: John

I expected it to result in phrase: Hello John but rather I got still phrase: Hello Mark. So it seems that the first (lower level) variables within the !With tag cannot be overriden by higher level !With templates.

Is this by design? Thanks!

Support JSONPath in `!Format`

Currently the argument to !Format is passed as-is to Python .format_map(). This means you can do {foo.__class__.__name__} but not {person.first_name}.

Implement our own format string parser that processes JSONPath expressions from within {}.

`io.UnsupportedOperation: underlying stream is not seekable` when output is a pipeline

$ emrichen postgres/secret.local.yaml | kc apply -n outline-ropecon -f -
Traceback (most recent call last):
  File "/Users/japsu/Hobby/venv3.10-emrichen/bin/emrichen", line 33, in <module>
    sys.exit(load_entry_point('emrichen', 'console_scripts', 'emrichen')())
  File "/Users/japsu/Hobby/emrichen/emrichen/__main__.py", line 35, in main
    args.output_file.seek(0)
io.UnsupportedOperation: underlying stream is not seekable
error: no objects passed to apply

Regression in #55 #54

Help understanding !If (include file only if var is set)

hi - struggling again, asking for help :)

  systemd:
    units: !Concat
      - !Include units/ALL.yaml
      - !Include units/docker_compose.yaml
      - !Include units/mount_docker.yaml
      - !Include units/mount_data.yaml
      - !If
        test: !Op [!Void, ne, !Var etcd_token]
        then: !Include units/etcd.yaml

i want to check if one of the "parent" files set the variable etcd_token - and if so, include the file.. is this doable?
TIA!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.