or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aws-resources.mdconstants.mdhelper-utilities.mdindex.mdintrinsic-functions.mdopenstack-support.mdparameters-outputs.mdtags-metadata.mdtemplate-management.mdvalidation.md
tile.json

tessl/pypi-troposphere

AWS CloudFormation creation library that facilitates building infrastructure templates programmatically in Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/troposphere@4.9.x

To install, run

npx @tessl/cli install tessl/pypi-troposphere@4.9.0

index.mddocs/

Troposphere

Troposphere is a Python library that facilitates creating AWS CloudFormation templates programmatically. It provides Python classes representing AWS resources and properties with built-in validation and type checking to catch errors early in development. The library supports generating both JSON and YAML CloudFormation templates and includes comprehensive coverage of AWS resource types.

Package Information

  • Package Name: troposphere
  • Language: Python 3.8+
  • Installation: pip install troposphere
  • License: BSD-2-Clause
  • Documentation: https://troposphere.readthedocs.io/en/latest/

Core Imports

import troposphere
from troposphere import Template, Parameter, Output, Ref, GetAtt

Common patterns for specific AWS services:

from troposphere.ec2 import Instance, SecurityGroup, VPC
from troposphere.s3 import Bucket, BucketPolicy
from troposphere.awslambda import Function, Permission

For CloudFormation intrinsic functions:

from troposphere import Join, Sub, FindInMap, If, Equals, Base64

For constants and validation:

from troposphere.constants import T2_MICRO, US_EAST_1, HTTP_PORT
from troposphere.validators import positive_integer, network_port

Basic Usage

from troposphere import Template, Parameter, Output, Ref
from troposphere.ec2 import Instance, SecurityGroup
from troposphere.constants import T2_MICRO

# Create a new CloudFormation template
template = Template()
template.set_description("Example EC2 instance with security group")

# Add parameters
instance_type_param = template.add_parameter(Parameter(
    "InstanceType",
    Type="String",
    Default=T2_MICRO,
    Description="EC2 instance type"
))

# Create a security group
security_group = template.add_resource(SecurityGroup(
    "MySecurityGroup",
    GroupDescription="Security group for EC2 instance",
    SecurityGroupIngress=[
        {
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIp": "0.0.0.0/0"
        }
    ]
))

# Create an EC2 instance
instance = template.add_resource(Instance(
    "MyInstance",
    InstanceType=Ref(instance_type_param),
    ImageId="ami-0abcdef1234567890",
    SecurityGroupIds=[Ref(security_group)]
))

# Add outputs
template.add_output(Output(
    "InstanceId",
    Value=Ref(instance),
    Description="Instance ID of the created EC2 instance"
))

# Generate CloudFormation template
print(template.to_json())

Architecture

Troposphere uses a hierarchical object model that mirrors CloudFormation's structure:

  • Template: Top-level container managing resources, parameters, outputs, mappings, and conditions
  • BaseAWSObject: Abstract base class providing validation and property management for all AWS objects
  • AWSObject: Base class for CloudFormation resources (EC2 instances, S3 buckets, etc.)
  • AWSProperty: Base class for complex resource properties and nested configuration objects
  • AWSHelperFn: Base class for CloudFormation intrinsic functions (Ref, GetAtt, Join, etc.)

This design ensures type safety through Python's class system while providing the flexibility to represent any CloudFormation construct. The library includes 1,472+ resource classes and 5,866+ property classes covering the complete AWS service catalog.

Capabilities

Template Management

Core functionality for creating and managing CloudFormation templates, including adding resources, parameters, outputs, and converting to JSON/YAML formats.

class Template:
    def __init__(self, Description: Optional[str] = None, Metadata: Optional[Dict[str, Any]] = None): ...
    def add_resource(self, resource) -> resource: ...
    def add_parameter(self, parameter) -> parameter: ...
    def add_output(self, output) -> output: ...
    def add_mapping(self, name: str, mapping: Dict[str, Any]) -> None: ...
    def add_condition(self, name: str, condition) -> str: ...
    def to_json(self, indent: int = 1, sort_keys: bool = True) -> str: ...
    def to_yaml(self, clean_up: bool = False, long_form: bool = False) -> str: ...

Template Management

CloudFormation Resources

AWS resource classes representing all CloudFormation resource types across 257 AWS services. Each resource class inherits from AWSObject and includes built-in property validation.

class AWSObject(BaseAWSObject):
    def __init__(self, title: str, template: Optional[Template] = None, **kwargs): ...
    def ref(self) -> Ref: ...
    def get_att(self, value: str) -> GetAtt: ...

Key resource examples:

# EC2 Resources
class Instance(AWSObject):
    resource_type = "AWS::EC2::Instance": ...

class SecurityGroup(AWSObject):
    resource_type = "AWS::EC2::SecurityGroup": ...

# S3 Resources  
class Bucket(AWSObject):
    resource_type = "AWS::S3::Bucket": ...

# Lambda Resources
class Function(AWSObject):
    resource_type = "AWS::Lambda::Function": ...

AWS Resources

CloudFormation Intrinsic Functions

Complete implementation of CloudFormation intrinsic functions for references, string manipulation, conditionals, and data transformation within templates.

class Ref(AWSHelperFn):
    def __init__(self, data: object): ...

class GetAtt(AWSHelperFn):
    def __init__(self, logicalName: object, attrName: object): ...

class Join(AWSHelperFn):
    def __init__(self, delimiter: object, values: object): ...

class Sub(AWSHelperFn):
    def __init__(self, input_str: object, dict_values: Optional[Dict[str, Any]] = None, **values): ...

class If(AWSHelperFn):
    def __init__(self, cond: object, true: object, false: object): ...

Intrinsic Functions

Parameters and Outputs

CloudFormation template parameters for user inputs and outputs for exposing resource values, with comprehensive validation and cross-stack reference support.

class Parameter(AWSDeclaration):
    def __init__(self, title: str, Type: str, Default=None, NoEcho: bool = False, 
                 AllowedValues: list = None, Description: str = None, **kwargs): ...

class Output(AWSDeclaration):
    def __init__(self, title: str, Value: str, Description: str = None, 
                 Export: Export = None, **kwargs): ...

class Export(AWSHelperFn):
    def __init__(self, name: Union[str, AWSHelperFn]): ...

Parameters and Outputs

Constants and Pseudo Parameters

Pre-defined constants for AWS regions, instance types, ports, and pseudo parameters for dynamic CloudFormation values.

# Pseudo Parameters
AWS_ACCOUNT_ID: str = "AWS::AccountId"
AWS_REGION: str = "AWS::Region"
AWS_STACK_NAME: str = "AWS::StackName"

# Pseudo Parameter Refs
AccountId: Ref = Ref(AWS_ACCOUNT_ID)
Region: Ref = Ref(AWS_REGION)
StackName: Ref = Ref(AWS_STACK_NAME)

# Policy Constants
Delete: str = "Delete"
Retain: str = "Retain"
Snapshot: str = "Snapshot"

Constants

Validation and Type Safety

Comprehensive validation system with built-in validators for AWS-specific constraints, data types, and custom validation functions.

def positive_integer(x) -> int: ...
def network_port(x) -> int: ...
def s3_bucket_name(b) -> str: ...
def one_of(class_name, properties, property, conditionals): ...
def mutually_exclusive(class_name, properties, conditionals): ...
def exactly_one(class_name, properties, conditionals): ...

Validation

Tags and Metadata

Tag management for AWS resource tagging with validation, sorting, and concatenation support.

class Tag(AWSHelperFn):
    def __init__(self, k: object, v: object): ...

class Tags(AWSHelperFn):
    def __init__(self, *args: object, **kwargs): ...
    def __add__(self, newtags: Tags) -> Tags: ...

Tags and Metadata

Helper Utilities

Additional utilities for user data, template conversion, and stack monitoring to enhance CloudFormation workflow integration.

# UserData helpers
def from_file(filepath: str) -> str: ...
def from_file_sub(filepath: str) -> str: ...

# Template generator
class TemplateGenerator:
    def convert_template(self, template_data: dict) -> Template: ...

# Stack monitoring
def get_events(stackname: str, region: str = None, aws_profile: str = None): ...
def tail(stackname: str, region: str = None, aws_profile: str = None): ...

Helper Utilities

OpenStack Support

Limited OpenStack Heat template support for organizations using hybrid cloud deployments with both AWS and OpenStack infrastructure.

class HeatTemplate:
    def __init__(self, heat_template_version: str = None): ...

OpenStack Support