I have a collection that relies on a graphql API. The queries are pretty unpleasant, and to make them a bit more manageable I store them as jinja templates. However, I struggled getting ansible to include/find the jinja text files when I executed my modules. So now all of the jinja templates are stored in static python methods, which is not great.
I am wondering if someone has a better solution, or can help me simplify my current approach. I like that this has been extensible (there is a lot of abstraction/subclassing), but managing the jinja through a python lens makes linting and variable context more difficult.
Here is a (much abbreviated) example of my setup. In short, my module imports an API class in module_utils, which imports object classes in module_utils, which import jinja templates stored in python classes in module_utils.
# plugins/modules/my-module.py
.....
from ansible_collections.my.collection.plugins.module_utils.api import (
SomeApi,
)
.....
# plugins/module_utils/api.py
.....
from ansible_collections.my.collection.plugins.module_utils.objects import (
Event,
)
class SomeApi():
.....
def get_events_for_guid(
self, guid: str,
) -> Generator[Event, None, None]:
query_template = self.jinja_env.from_string(Event.J2_SEARCH_QUERY)
query = query_template.render(
guid=guid
)
r = self.run_query(query=query)
.....
# plugins/module_utils/objects.py
.....
from ansible_collections.my.collection.plugins.module_utils.query_templates import (
EventTemplates,
ChangeEventTemplates,
)
class Event(ObjectBase):
J2_SEARCH_QUERY = EventTemplates.j2_get_from_search()
J2_CREATE_QUERY = EventTemplates.j2_create()
class ChangeEvent(Event):
J2_CREATE_QUERY = ChangeEventTemplates.j2_create()
def __init__():
.....
# plugins/module_utils/query_templates.py
class EventTemplates:
def __init__(self):
pass
@staticmethod
def j2_get_from_search():
return """{
mutation {
entity(guid: "{{ entity_guid }}") {
.....
}
}
}"""
.....