Enrico Zini: Ansible conditionals in Transilience
This is part of a series of posts on ideas for an ansible-like provisioning
system, implemented in Transilience.
I thought a lot of what I managed to do so far with Transilience would be
impossible, but then here I am. How about
Ansible conditionals?
Those must be impossible, right?
Let's give it a try.
A quick recon of Ansible sources
Looking into Ansible's sources,
Generating Python code
Transilience does not only support running Ansible roles, but also converting
them to Python code. I can keep this up by traversing the
Jinja2 AST generating Python expressions.
The code is straightforward enough that I can throw in a bit of pattern
matching to make some expressions more idiomatic for Python:
Scanning for variables
Lastly, I can implement scanning conditionals for variable references to add as
fields to the Role dataclass:
The result in action
Take this simple Ansible task:
Run it through
Besides one harmless set of parentheses too much, what I wasn't sure would be
possible is there, right there, staring at me with a mischievous grin.
Next: Building a Transilience playbook in a zipapp.
when expressions are
lists of strings
AND-ed together.
The expressions are Jinja2 expressions that Ansible
pastes into a mini-template, renders, and checks the string that comes out.
A quick recon of Jinja2
Jinja2 has a convenient function (jinja2.Environment.compile_expression)
that compiles a template snippet into a Python function.
It can also
parse a template into an AST
that can be inspected in various ways.
Evaluating Ansible conditionals in Python
Environment.compile_expression seems to really do precisely what we need for
this, straight out of the box.
There is an issue with the concept of "defined": for Ansible it seems to mean
"the variable is present in the template context". In Transilience instead, all
variables are fields in the Role dataclass, and can be None when not set.
This means that we need to remove variables that are set to None before
passing the parameters to the compiled Jinjae expression:
class Conditional: """ An Ansible conditional expression """ def __init__(self, engine: template.Engine, body: str): # Original unparsed expression self.body: str = body # Expression compiled to a callable self.expression: Callable = engine.env.compile_expression(body) def evaluate(self, ctx: Dict[str, Any]): ctx = name: val for name, val in ctx.items() if val is not None return self.expression(**ctx)
class Conditional: def __init__(self, engine: template.Engine, body: str): ... parser = jinja2.parser.Parser(engine.env, body, state='variable') self.jinja2_ast: nodes.Node = parser.parse_expression() def get_python_code(self) -> str: return to_python_code(self.jinja2_ast def to_python_code(node: nodes.Node) -> str: if isinstance(node, nodes.Name): if node.ctx == "load": return f"self. node.name " else: raise NotImplementedError(f"jinja2 Name nodes with ctx= node.ctx!r are not supported: node!r ") elif isinstance(node, nodes.Test): if node.name == "defined": return f" to_python_code(node.node) is not None" elif node.name == "undefined": return f" to_python_code(node.node) is None" else: raise NotImplementedError(f"jinja2 Test nodes with name= node.name!r are not supported: node!r ") elif isinstance(node, nodes.Not): if isinstance(node.node, nodes.Test): # Special case match well-known structures for more idiomatic Python if node.node.name == "defined": return f" to_python_code(node.node.node) is None" elif node.node.name == "undefined": return f" to_python_code(node.node.node) is not None" elif isinstance(node.node, nodes.Name): return f"not to_python_code(node.node) " return f"not ( to_python_code(node.node) )" elif isinstance(node, nodes.Or): return f"( to_python_code(node.left) or to_python_code(node.right) )" elif isinstance(node, nodes.And): return f"( to_python_code(node.left) and to_python_code(node.right) )" else: raise NotImplementedError(f"jinja2 node.__class__ nodes are not supported: node!r ")
class FindVars(jinja2.visitor.NodeVisitor): def __init__(self): self.found: Set[str] = set() def visit_Name(self, node): if node.ctx == "load": self.found.add(node.name) class Conditional: ... def list_role_vars(self) -> Sequence[str]: fv = FindVars() fv.visit(self.jinja2_ast) return fv.found
--- - name: Example task file: state: touch path: /tmp/test when: (is_test is defined and is_test) or debug is defined
./provision --ansible-to-python test and you get:
from __future__ import annotations from typing import Any from transilience import role from transilience.actions import builtin, facts @role.with_facts([facts.Platform]) class Role(role.Role): # Role variables used by templates debug: Any = None is_test: Any = None def all_facts_available(self): if ((self.is_test is not None and self.is_test) or self.debug is not None): self.add( builtin.file(path='/tmp/test', state='touch'), name='Example task')




As you may know, Puppet uses facter to get facts about the machine it is about to configure. That s fine, and a nice concept. One can later use variables in a puppet manifest to do different things depending on what facter tells. For example, the operating system name oh no! This thing is really stupid Here s the code one has to do to be compatible with puppet from version 3 up to 5:
Despite having worked on a
I managed to break a USB port on the Desk Pi. It has a pair of forward facing ports, I plugged my wireless keyboard dongle into it and when trying to remove it the solid spacer bit in the socket broke off. I ve never had this happen to me before and I ve been using USB devices for 20 years, so I m putting the blame on a shoddy socket.
The first drive I tried was an old Crucial M500 mSATA device. I have an adaptor that makes it look like a normal 2.5 drive so I used that. Unfortunately it resulted in a boot loop; the Pi would boot its initial firmware, try to talk to the drive and then reboot before even loading Linux. The DeskPi Pro comes with an m2 adaptor and I had a spare m2 drive, so I tried that and it all worked fine. This might just be power issues, but it was an unfortunate experience especially after the USB port had broken off.
(Given I ended up using an M.2 drive another case option would have been the
The case is a little snug; I was worried I was going to damage things as I slid it in. Additionally the construction process is a little involved. There s a good set of instructions, but there are a lot of pieces and screws involved. This includes a couple of
I hate the need for an external USB3 dongle to bridge from the Pi to the USB/SATA adaptor. All the cases I ve seen with an internal drive bay have to do this, because the USB3 isn t brought out internally by the Pi, but it just looks ugly to me. It s hidden at the back, but meh.
Fan control is via a USB/serial device, which is fine, but it attaches to the USB C power port which defaults to being a USB peripheral. Raspbian based kernels support device tree overlays which allows easy reconfiguration to host mode, but for a Debian based system I ended up rolling my own dtb file. I changed
Previously: 
In May, I got selected as a
Welcome to gambaru.de. Here is my monthly report that covers what I have been doing for Debian. If you re interested in Java, Games and LTS topics, this might be interesting for you.
Debian Games
Often, when I mention how things work in the interactive theorem prover [Isabelle/HOL] (in the following just Isabelle
long time no blog post. & the
If you have a bunch of machines running OpenBSD for firewalling purposes, which is pretty standard, you might start to use source-control to maintain the rulesets. You might go further, and use some kind of integration testing to deploy changes from your revision control system into production.
Of course before you deploy any
Here is my monthly update covering what I have been doing in the free software world (
A brown bag bug fix release 0.0.3 of