Python library and CLI tool for generating Terraform JSON configurations using full Python programming capabilities
npx @tessl/cli install tessl/pypi-terraformpy@1.3.0A Python library and command line tool that enables developers to generate Terraform JSON configurations using full Python programming capabilities instead of HashiCorp Configuration Language (HCL). Terraformpy provides a declarative API for creating Terraform resources, providers, variables, outputs, modules, and data sources through Python classes, with support for advanced features like resource interpolation, backend configuration, provider aliasing, and resource collections.
pip install terraformpyimport terraformpyMost common usage imports:
from terraformpy import Resource, Data, Provider, Variable, Output, Module, Terraform
from terraformpy import compile, resetFor resource collections:
from terraformpy import ResourceCollection, VariantFor helper utilities:
from terraformpy.helpers import relative_file, relative_pathFor AWS-specific hooks:
from terraformpy.hooks.aws import install_aws_security_group_attributes_as_blocks_hook
from terraformpy.hooks.aws import fill_in_optional_aws_security_group_rules_attrsfrom terraformpy import Resource, Variable, Output, Provider, compile
# Define variables
env = Variable('environment', default='dev')
instance_type = Variable('instance_type', default='t3.micro')
# Configure provider
provider = Provider('aws', region='us-west-2')
# Create resources
web_server = Resource('aws_instance', 'web_server',
instance_type=instance_type, # Variables are used directly
ami='ami-12345678',
tags={'Name': 'WebServer-${var.environment}'} # Terraform interpolation syntax
)
# Define outputs
Output('instance_id', value=web_server.id)
Output('public_ip', value=web_server.public_ip)
# Compile to Terraform JSON
terraform_config = compile()
print(terraform_config)
# Reset for next configuration
reset()Terraformpy uses a registration-based architecture with three key components:
${resource.attribute}) from Python attribute accessThis design enables declarative Python code to generate complex Terraform configurations while maintaining the benefits of Python's programming environment, including variables, loops, conditionals, and modules.
Essential Terraform object types including resources, data sources, providers, variables, outputs, modules, and terraform configuration blocks. These form the foundation of any Terraform configuration.
class Resource(type: str, name: str, **kwargs): ...
class Data(type: str, name: str, **kwargs): ...
class Provider(name: str, **kwargs): ...
class Variable(name: str, **kwargs): ...
class Output(name: str, **kwargs): ...
class Module(name: str, **kwargs): ...
class Terraform(**kwargs): ...Framework for creating reusable, parameterized groups of resources that can be instantiated with different configurations. Supports environment-specific variants and inheritance patterns.
class ResourceCollection(schematics.Model):
def create_resources(self): ...
class Variant(name: str): ...Utilities for working with file paths and local resources in Terraform configurations, enabling relative path references that work correctly regardless of where the Python script is executed.
def relative_file(filename: str, _caller_depth: int = 1) -> str: ...
def relative_path(path: str, _caller_depth: int = 1) -> str: ...Functions for compiling registered Terraform objects to JSON and managing the global object registry, including hook system for extending functionality.
def compile() -> dict: ...
def reset() -> None: ...
# Hook system
TFObject.add_hook(object_type: str, hook_function: Callable) -> NoneAWS-specific hooks and utilities for handling AWS resource configurations and provider quirks, including security group rule transformations and other AWS-specific fixes.
def install_aws_security_group_attributes_as_blocks_hook() -> None: ...
def fill_in_optional_aws_security_group_rules_attrs(object_id: str, attrs: dict) -> dict: ...
SECURITY_GROUP_RULE_OPTIONAL_ATTRS: tupleCLI tool for processing Python files containing Terraform configurations and generating JSON output files compatible with Terraform tooling.
terraformpy [options]Core types used throughout the terraformpy API:
class TFObject:
"""Base class for all Terraform objects with compilation and hook support."""
@classmethod
def compile() -> str:
"""Compile all registered objects to Terraform JSON."""
@classmethod
def reset() -> None:
"""Clear all registered objects from the registry."""
@classmethod
def add_hook(object_type: str, hook_function: Callable[[str, dict], dict]) -> None:
"""Add a transformation hook for objects of the specified type."""
class DuplicateKey(str):
"""
String subclass for handling duplicate JSON keys in provider configurations.
Allows the same key to appear multiple times in JSON dictionaries, which is
required for Terraform provider configurations but technically invalid in JSON.
Uses a counter-based hash to maintain insertion order and uniqueness.
"""
def __new__(cls, key: str) -> DuplicateKey:
"""Create a duplicate-safe key from a string."""
class OrderedDict(schematics.types.compound.DictType):
"""
Schematics DictType that preserves key insertion order.
Maintains the order in which keys are added to the dictionary,
which is important for consistent Terraform JSON generation.
"""
def convert(self, value, context=None):
"""Convert value while maintaining key insertion order."""
class TypedObjectAttr(str):
"""
String subclass that generates Terraform interpolation syntax for resource attributes.
Automatically creates Terraform interpolation expressions like ${resource.attribute}
when accessing attributes on Resource and Data objects.
"""
def __init__(self, terraform_name: str, attr_name: str):
"""
Create interpolation reference like ${resource_type.name.attribute}.
Parameters:
- terraform_name: Full Terraform object name (e.g., 'aws_instance.web')
- attr_name: Attribute name (e.g., 'id', 'public_ip')
"""
def __getitem__(self, key: str) -> TypedObjectAttr:
"""Support array/map indexing: resource.attribute[key]."""
def __getattr__(self, name: str) -> TypedObjectAttr:
"""Support nested attribute access: resource.attribute.nested."""