majuna/app/terraform/__init__.py

51 lines
1.7 KiB
Python

from abc import ABCMeta, abstractmethod
import os
from typing import Tuple, Optional, Any
import jinja2
from app import app
class BaseAutomation(metaclass=ABCMeta):
short_name: str = "base"
description: str = "Abstract base automation."
frequency: int
"""
The short name of the automation provider. This is used as an opaque token throughout
the portal system.
"""
@abstractmethod
def automate(self, full: bool = False) -> Tuple[bool, str]:
raise NotImplementedError()
def working_directory(self, filename: Optional[str] = None) -> str:
"""
Provides a filesystem path that can be used during the automation run.
This is currently a persistent path, but this should not be relied upon
as future versions may use disposable temporary paths instead. State that
is needed in subsequent runs should be stored elsewhere.
:param filename: the filename inside the working directory to create a path for
:return: filesystem path for that filename
"""
return os.path.join(
app.config['TERRAFORM_DIRECTORY'],
self.short_name or self.__class__.__name__.lower(),
filename or ""
)
def tmpl_write(self, filename: str, template: str, **kwargs: Any) -> None:
"""
Write a Jinja2 template to the working directory for use by an automation module.
:param filename: filename to write to
:param template: Jinja2 template
:param kwargs: variables for use with the template
:return: None
"""
tmpl = jinja2.Template(template)
with open(self.working_directory(filename), 'w', encoding="utf-8") as tf:
tf.write(tmpl.render(**kwargs))