CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-terraformpy

Python library and CLI tool for generating Terraform JSON configurations using full Python programming capabilities

Overview
Eval results
Files

core-objects.mddocs/

Core Terraform Objects

Essential Terraform object types that form the foundation of any Terraform configuration. These classes provide Python representations of Terraform resources, data sources, providers, variables, outputs, modules, and configuration blocks.

Capabilities

Resource Objects

Represents Terraform resources - managed infrastructure components that Terraform creates, updates, and destroys.

class Resource:
    def __init__(self, type: str, name: str, **kwargs):
        """
        Create a Terraform resource.

        Parameters:
        - type: str - Terraform resource type (e.g., 'aws_instance', 'aws_s3_bucket')
        - name: str - Resource name for referencing
        - **kwargs: Resource-specific configuration attributes

        Example:
        Resource('aws_instance', 'web_server',
                instance_type='t3.micro',
                ami='ami-12345678')
        """

    def __getattr__(self, name: str) -> TypedObjectAttr:
        """Returns Terraform interpolation syntax for resource attributes.

        Example:
        web_server.id returns "${aws_instance.web_server.id}"
        web_server.public_ip returns "${aws_instance.web_server.public_ip}"
        """

Data Sources

Represents Terraform data sources - read-only information about existing infrastructure or external services.

class Data:
    def __init__(self, type: str, name: str, **kwargs):
        """
        Create a Terraform data source.

        Parameters:
        - type: str - Terraform data source type (e.g., 'aws_ami', 'aws_availability_zones')
        - name: str - Data source name for referencing
        - **kwargs: Data source-specific filter and configuration attributes

        Example:
        Data('aws_ami', 'ubuntu',
             most_recent=True,
             owners=['099720109477'],
             filters={'name': 'ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*'})
        """

    def __getattr__(self, name: str) -> TypedObjectAttr:
        """Returns Terraform interpolation syntax for data source attributes.

        Example:
        ubuntu_ami.id returns "${data.aws_ami.ubuntu.id}"
        ubuntu_ami.image_id returns "${data.aws_ami.ubuntu.image_id}"
        """

Provider Configuration

Represents Terraform provider configurations, including support for provider aliases and context management.

class Provider:
    def __init__(self, name: str, **kwargs):
        """
        Create a Terraform provider configuration.

        Parameters:
        - name: str - Provider name (e.g., 'aws', 'google', 'azurerm')
        - alias: str, optional - Provider alias for multiple configurations
        - **kwargs: Provider-specific configuration options

        Example:
        Provider('aws', region='us-west-2', alias='west')
        """

    def __enter__(self):
        """Context manager entry - resources created within use this provider."""

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit."""

Variable Declarations

Represents Terraform input variables that parameterize configurations.

class Variable:
    def __init__(self, name: str, **kwargs):
        """
        Create a Terraform variable.

        Parameters:
        - name: str - Variable name
        - default: Any, optional - Default value
        - description: str, optional - Variable description
        - type: str, optional - Variable type constraint
        - sensitive: bool, optional - Mark as sensitive
        - validation: dict, optional - Variable validation rules

        Example:
        Variable('environment',
                default='dev',
                description='Deployment environment',
                type='string')
        """

    def __repr__(self) -> str:
        """Returns ${var.name} interpolation syntax when used as string.

        Example:
        env = Variable('environment')
        str(env) returns "${var.environment}"
        """

Output Values

Represents Terraform output values that expose information from configurations.

class Output:
    def __init__(self, name: str, **kwargs):
        """
        Create a Terraform output.

        Parameters:
        - name: str - Output name
        - value: Any - Output value (usually interpolation reference)
        - description: str, optional - Output description
        - sensitive: bool, optional - Mark as sensitive

        Example:
        Output('instance_id',
              value=web_server.id,
              description='Web server instance ID')
        """

Module Instances

Represents Terraform module instances that encapsulate reusable infrastructure components.

class Module:
    def __init__(self, name: str, **kwargs):
        """
        Create a Terraform module instance.

        Parameters:
        - name: str - Module instance name
        - source: str - Module source path or URL
        - version: str, optional - Module version constraint
        - **kwargs: Module input variables

        Example:
        Module('vpc',
              source='terraform-aws-modules/vpc/aws',
              version='~> 3.0',
              cidr='10.0.0.0/16')
        """

    def __getattr__(self, name: str) -> str:
        """Returns Terraform interpolation syntax for module outputs.

        Example:
        vpc_module.vpc_id returns "${module.vpc.vpc_id}"
        vpc_module.subnet_ids returns "${module.vpc.subnet_ids}"
        """

Terraform Configuration

Represents Terraform configuration blocks for backend, required providers, and other settings.

class Terraform:
    def __init__(self, **kwargs):
        """
        Create a Terraform configuration block.

        Parameters:
        - backend: dict, optional - Backend configuration
        - required_providers: dict, optional - Provider requirements
        - required_version: str, optional - Terraform version constraint

        Example:
        Terraform(
            backend={'s3': {
                'bucket': 'my-tf-state',
                'key': 'terraform.tfstate',
                'region': 'us-west-2'
            }},
            required_providers={
                'aws': {
                    'source': 'hashicorp/aws',
                    'version': '~> 5.0'
                }
            }
        )
        """

Usage Examples

Basic Resource Creation

from terraformpy import Resource, Variable

# Create variable
instance_type = Variable('instance_type', default='t3.micro')

# Create resource with interpolation
web_server = Resource('aws_instance', 'web',
    instance_type=instance_type,  # Variable used directly
    ami='ami-12345678',
    tags={'Name': 'WebServer'}
)

Provider Context Management

from terraformpy import Provider, Resource

# Use provider context
with Provider('aws', region='us-west-2', alias='west'):
    # Resources created here automatically use the west provider
    Resource('aws_instance', 'west_server', instance_type='t3.micro')

# Different provider context
with Provider('aws', region='us-east-1', alias='east'):
    Resource('aws_instance', 'east_server', instance_type='t3.micro')

Data Source Usage

from terraformpy import Data, Resource

# Query existing AMI
ubuntu_ami = Data('aws_ami', 'ubuntu',
    most_recent=True,
    owners=['099720109477'],
    filters={'name': 'ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*'}
)

# Use in resource
web_server = Resource('aws_instance', 'web',
    ami=ubuntu_ami.id,  # Interpolation: ${data.aws_ami.ubuntu.id}
    instance_type='t3.micro'
)

Module Integration

from terraformpy import Module, Output

# Create module instance
vpc = Module('main_vpc',
    source='terraform-aws-modules/vpc/aws',
    version='~> 3.0',

    # Module inputs
    cidr='10.0.0.0/16',
    azs=['us-west-2a', 'us-west-2b'],
    private_subnets=['10.0.1.0/24', '10.0.2.0/24'],
    public_subnets=['10.0.101.0/24', '10.0.102.0/24'],
    enable_nat_gateway=True
)

# Reference module outputs
Output('vpc_id', value=vpc.vpc_id)  # Generates ${module.main_vpc.vpc_id}
Output('private_subnets', value=vpc.private_subnets)  # Generates ${module.main_vpc.private_subnets}

## Base Classes

Core base classes that provide the foundation for all Terraform objects in terraformpy.

### TFObject

Root base class for all Terraform objects with global registry and hook system.

```python { .api }
class TFObject:
    @classmethod
    def compile() -> dict:
        """Compile all registered objects to Terraform configuration dictionary."""

    @classmethod
    def reset() -> None:
        """Clear all registered objects from the global registry."""

    @classmethod
    def add_hook(object_type: str, hook_function: Callable[[dict], dict]) -> None:
        """Add transformation hook for objects of the specified type."""

    def build() -> dict:
        """Build the Terraform JSON representation of this object."""

NamedObject

Base class for Terraform objects with a single name (variables, outputs, providers, modules).

class NamedObject(TFObject):
    def __init__(self, _name: str, **kwargs):
        """
        Create a named Terraform object.

        Parameters:
        - _name: str - Object name
        - **kwargs: Object-specific attributes
        """

    @classmethod
    def add_hook(cls, object_name: str, hook_function: Callable[[dict], dict]) -> None:
        """Add hook for named objects that receives object attributes."""

TypedObject

Base class for Terraform objects with both type and name (resources, data sources).

class TypedObject(NamedObject):
    def __init__(self, _type: str, _name: str, **kwargs):
        """
        Create a typed Terraform object.

        Parameters:
        - _type: str - Terraform object type (e.g., 'aws_instance', 'aws_ami')
        - _name: str - Object name for referencing
        - **kwargs: Object-specific attributes
        """

    @classmethod
    def add_hook(cls, object_type: str, hook_function: Callable[[str, dict], dict]) -> None:
        """Add hook for typed objects that receives object ID and attributes."""

    def __getattr__(self, name: str) -> TypedObjectAttr:
        """Return Terraform interpolation syntax for accessing attributes."""

    @property
    def terraform_name(self) -> str:
        """Return the full Terraform name (type.name) for interpolation."""

TypedObjectAttr

String subclass that generates Terraform interpolation syntax for resource/data attributes.

class TypedObjectAttr(str):
    def __init__(self, terraform_name: str, attr_name: str):
        """
        Create Terraform interpolation reference.

        Parameters:
        - terraform_name: str - Full Terraform object name (e.g., 'aws_instance.web')
        - attr_name: str - Attribute name (e.g., 'id', 'public_ip')

        Returns string like: "${aws_instance.web.id}"
        """

    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."""

Install with Tessl CLI

npx tessl i tessl/pypi-terraformpy

docs

aws-hooks.md

cli.md

compilation-hooks.md

core-objects.md

helpers.md

index.md

resource-collections.md

tile.json