pyinfra-dev / pyinfra

pyinfra turns Python code into shell commands and runs them on your servers. Execute ad-hoc commands and write declarative operations. Target SSH servers, local machine and Docker containers. Fast and scales from one server to thousands.
https://pyinfra.com
MIT License
3.91k stars 382 forks source link

templating: what is available? #210

Closed mkinney closed 4 years ago

mkinney commented 4 years ago

Looking at the files.template() operation and wondering what variables are available.

Is there a templating library included?

Can you have things like "{{ date }}" or "{{ some_system_command|some_formatting }}"?

Should there be a fact called "internals" that would show things like date task was started, args passed to pyinfra, etc?

Fizzadar commented 4 years ago

So templates are currently rendered using jinja2 - this definitely needs better documenting!

Two globals are passed into the template: host and inventory as per https://github.com/Fizzadar/pyinfra/blob/master/pyinfra/modules/files.py#L461.

I'll leave this issue open to add documentation to the module explaining the above.

mkinney commented 4 years ago
  1. What filters exist?

For instance: {{ host.fact.deb_packages|to_json }}

pyinfra error (operation=Create a templated file): Error in template: templates/foo (L1578): no filter named 'to_json'

  1. I tried doing: inventory: {{ inventory|tojson }}

but I got this error:

--> An unexpected exception occurred:

  File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Inventory is not JSON serializable
  1. What is available from inventory? (Can you provide some examples that I could put in a template file?)
Fizzadar commented 4 years ago
  1. Filters wise just the standard jinja2 ones currently: https://jinja.palletsprojects.com/en/2.10.x/templates/#builtin-filters 2 & 3. This is really interesting - would be keen to have a to json method for inventory. Currently there are a bunch of methods to get inventory data as listed from https://github.com/Fizzadar/pyinfra/blob/master/pyinfra/api/inventory.py#L240 onwards.

I've added an issue to make Inventory objects JSON serialisable @ https://github.com/Fizzadar/pyinfra/issues/215.

Fizzadar commented 4 years ago

Have now added a link to jinja2 in the files.template docstring (https://github.com/Fizzadar/pyinfra/commit/efcfe50ff34b08abc896fa4b31cec085d8cf5f74), so closing this.

sanzoghenzo commented 1 year ago

Hi @Fizzadar , sorry to necropost this, but from the docmentation is still unclear that the objects passed to files.template are host, state, inventory and facts.

It would be nice to have a (simple) example before the one that passes variables as arguments, or even complete that example to use both arguments and the objects passed by default.