AWS CloudFormation creation library that facilitates building infrastructure templates programmatically in Python
AWS resource classes representing all CloudFormation resource types across 257 AWS services. Each resource class inherits from AWSObject and includes built-in property validation, references, and attribute access.
Core base classes that all AWS resources inherit from, providing common functionality for validation, serialization, and CloudFormation integration.
class BaseAWSObject:
def __init__(self, title: Optional[str], template: Optional[Template] = None,
validation: bool = True, **kwargs):
"""
Base class for all AWS objects.
Args:
title: Logical name for the resource
template: Template to add resource to
validation: Whether to enable property validation
**kwargs: Resource properties
"""
def validate(self) -> None:
"""Validate resource properties."""
def to_dict(self, validation: bool = True) -> Dict[str, Any]:
"""
Convert resource to dictionary format.
Args:
validation: Whether to validate before conversion
Returns:
dict: Resource as dictionary
"""
def to_json(self, indent: int = 4, sort_keys: bool = True,
validation: bool = True) -> str:
"""
Convert resource to JSON string.
Args:
indent: JSON indentation
sort_keys: Whether to sort keys
validation: Whether to validate before conversion
Returns:
str: Resource as JSON
"""
def no_validation(self):
"""Disable validation for this resource."""
@classmethod
def from_dict(cls, title: str, d: Dict[str, Any]):
"""
Create resource from dictionary.
Args:
title: Resource logical name
d: Resource properties dictionary
Returns:
Resource instance
"""class AWSObject(BaseAWSObject):
dictname = "Properties"
def ref(self) -> Ref:
"""
Create Ref to this resource.
Returns:
Ref: Reference to this resource
"""
def get_att(self, value: str) -> GetAtt:
"""
Get resource attribute.
Args:
value: Attribute name
Returns:
GetAtt: Attribute reference
"""class AWSProperty(BaseAWSObject):
dictname = None
def __init__(self, title: Optional[str] = None, **kwargs):
"""
Base class for resource properties.
Args:
title: Property name (optional)
**kwargs: Property values
"""Amazon Elastic Compute Cloud resources for virtual servers, networking, and storage.
class Instance(AWSObject):
resource_type = "AWS::EC2::Instance"
# Inherits constructor from BaseAWSObject:
# def __init__(self, title: str, template: Optional[Template] = None,
# validation: bool = True, **kwargs)
# Key properties (set via constructor kwargs or attribute assignment):
# ImageId: str - AMI ID to launch (required)
# InstanceType: str - Instance type (required)
# KeyName: str - Key pair name for SSH access
# SecurityGroups: List[str] - Security group names (EC2-Classic)
# SecurityGroupIds: List[str] - Security group IDs (VPC)
# SubnetId: str - Subnet ID for VPC instances
# UserData: str - User data script
# IamInstanceProfile: str - IAM instance profile
# BlockDeviceMappings: List[dict] - Block device mappings
class SecurityGroup(AWSObject):
resource_type = "AWS::EC2::SecurityGroup"
# Inherits constructor from BaseAWSObject
# Key properties:
# GroupDescription: str - Security group description (required)
# VpcId: str - VPC ID (required for VPC security groups)
# SecurityGroupIngress: List[dict] - Inbound rules
# SecurityGroupEgress: List[dict] - Outbound rules
# GroupName: str - Security group name
class VPC(AWSObject):
resource_type = "AWS::EC2::VPC"
# Inherits constructor from BaseAWSObject
# Key properties:
# CidrBlock: str - VPC CIDR block (required)
# EnableDnsHostnames: bool - Enable DNS hostnames
# EnableDnsSupport: bool - Enable DNS support
# InstanceTenancy: str - Instance tenancy ('default', 'dedicated', 'host')
class Subnet(AWSObject):
resource_type = "AWS::EC2::Subnet"
# Inherits constructor from BaseAWSObject
# Key properties:
# VpcId: str - VPC ID (required)
# CidrBlock: str - Subnet CIDR block (required)
# AvailabilityZone: str - Availability zone
# MapPublicIpOnLaunch: bool - Auto-assign public IPAmazon Simple Storage Service resources for object storage, buckets, and access control.
class Bucket(AWSObject):
resource_type = "AWS::S3::Bucket"
# Inherits constructor from BaseAWSObject
# Key properties:
# BucketName: str - Bucket name
# AccessControl: str - Access control list
# BucketEncryption: dict - Bucket encryption configuration
# CorsConfiguration: dict - CORS configuration
# LifecycleConfiguration: dict - Lifecycle rules
# NotificationConfiguration: dict - Event notifications
# PublicAccessBlockConfiguration: dict - Public access settings
# VersioningConfiguration: dict - Versioning configuration
WebsiteConfiguration: dict = None, **kwargs):
"""
S3 Bucket resource.
Args:
title: Logical resource name
BucketName: Bucket name (auto-generated if not specified)
AccessControl: Canned ACL for bucket
BucketEncryption: Encryption configuration
CorsConfiguration: CORS configuration
LifecycleConfiguration: Lifecycle rules
NotificationConfiguration: Event notifications
PublicAccessBlockConfiguration: Public access block settings
VersioningConfiguration: Versioning settings
WebsiteConfiguration: Static website hosting
"""
class BucketPolicy(AWSObject):
resource_type = "AWS::S3::BucketPolicy"
# Inherits constructor from BaseAWSObject
# Key properties:
# Bucket: str - Bucket name or reference (required)
# PolicyDocument: dict - IAM policy document (required)AWS Lambda resources for serverless computing and event-driven applications.
class Function(AWSObject):
resource_type = "AWS::Lambda::Function"
# Inherits constructor from BaseAWSObject
# Key properties:
# Code: dict - Function code (S3 or inline) (required)
# Handler: str - Function handler (required)
# Role: str - Execution role ARN (required)
# Runtime: str - Runtime environment (required)
# FunctionName: str - Function name
# Description: str - Function description
# Environment: dict - Environment variables
# MemorySize: int - Memory allocation (128-10240 MB)
# Timeout: int - Timeout in seconds (1-900)
# VpcConfig: dict - VPC configuration
# DeadLetterConfig: dict - Dead letter queue configuration
class Permission(AWSObject):
resource_type = "AWS::Lambda::Permission"
# Inherits constructor from BaseAWSObject
# Key properties:
# Action: str - Lambda action ('lambda:InvokeFunction') (required)
# FunctionName: str - Function name or ARN (required)
# Principal: str - Principal requesting permission (required)
# SourceArn: str - Source ARN for permission
# SourceAccount: str - Source account ID
"""AWS resources use the BaseAWSObject constructor and set properties via keyword arguments or attribute assignment:
from troposphere import Template, Ref, GetAtt
from troposphere.ec2 import Instance, SecurityGroup
from troposphere.s3 import Bucket
# Create template
template = Template()
# Method 1: Set properties via constructor kwargs
instance = Instance(
"MyInstance",
ImageId="ami-12345678",
InstanceType="t2.micro",
KeyName="my-key"
)
# Method 2: Set properties via attribute assignment
security_group = SecurityGroup("MySecurityGroup")
security_group.GroupDescription = "My security group"
security_group.SecurityGroupIngress = [
{
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22,
"CidrIp": "0.0.0.0/0"
}
]
# Method 3: Mixed approach
bucket = Bucket(
"MyBucket",
BucketName="my-unique-bucket-name"
)
bucket.VersioningConfiguration = {
"Status": "Enabled"
}
# Add resources to template
template.add_resource(instance)
template.add_resource(security_group)
template.add_resource(bucket)
# Reference resources
instance.SecurityGroupIds = [Ref(security_group)]
# Get resource attributes
bucket_domain_name = GetAtt(bucket, "DomainName")Amazon Relational Database Service resources for managed databases.
class DBInstance(AWSObject):
resource_type = "AWS::RDS::DBInstance"
# Inherits constructor from BaseAWSObject
# Key properties:
# DBInstanceClass: str - DB instance class (required)
# Engine: str - Database engine (required)
# AllocatedStorage: int - Storage size in GB
# DBName: str - Database name
# MasterUsername: str - Master username
# MasterUserPassword: str - Master password
# VPCSecurityGroups: List[str] - VPC security groups
# DBSubnetGroupName: str - DB subnet group
# MultiAZ: bool - Multi-AZ deployment
# StorageEncrypted: bool - Storage encryption
class DBCluster(AWSObject):
resource_type = "AWS::RDS::DBCluster"
# Inherits constructor from BaseAWSObject
# Key properties:
# Engine: str - Database engine (required)
# MasterUsername: str - Master username
# MasterUserPassword: str - Master password
# DatabaseName: str - Database name
# VpcSecurityGroupIds: List[str] - VPC security group IDs
# DBSubnetGroupName: str - DB subnet groupIdentity and Access Management resources for authentication and authorization.
class Role(AWSObject):
resource_type = "AWS::IAM::Role"
def __init__(self, title: str, AssumeRolePolicyDocument: dict,
RoleName: str = None, ManagedPolicyArns: list = None,
Policies: list = None, Path: str = None, **kwargs):
"""
IAM Role resource.
Args:
title: Logical resource name
AssumeRolePolicyDocument: Trust policy document
RoleName: Role name
ManagedPolicyArns: Managed policy ARNs
Policies: Inline policies
Path: Role path
"""
class Policy(AWSObject):
resource_type = "AWS::IAM::Policy"
def __init__(self, title: str, PolicyDocument: dict, PolicyName: str,
Groups: list = None, Roles: list = None, Users: list = None, **kwargs):
"""
IAM Policy resource.
Args:
title: Logical resource name
PolicyDocument: Policy document
PolicyName: Policy name
Groups: Groups to attach policy to
Roles: Roles to attach policy to
Users: Users to attach policy to
"""All AWS resources support common properties that can be set as attributes:
# Common resource attributes
resource.Condition = condition_name
resource.CreationPolicy = creation_policy_dict
resource.DeletionPolicy = "Delete" | "Retain" | "Snapshot"
resource.DependsOn = dependency_list
resource.Metadata = metadata_dict
resource.UpdatePolicy = update_policy_dict
resource.UpdateReplacePolicy = "Delete" | "Retain" | "Snapshot"from troposphere import Template, Ref
from troposphere.ec2 import Instance, SecurityGroup
template = Template()
# Create security group
sg = template.add_resource(SecurityGroup(
"MySecurityGroup",
GroupDescription="Allow SSH access",
SecurityGroupIngress=[{
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22,
"CidrIp": "0.0.0.0/0"
}]
))
# Create EC2 instance
instance = template.add_resource(Instance(
"MyInstance",
ImageId="ami-0abcdef1234567890",
InstanceType="t2.micro",
SecurityGroupIds=[Ref(sg)],
KeyName="my-key-pair"
))
# Set resource attributes
instance.DeletionPolicy = "Retain"
instance.DependsOn = [sg]from troposphere.s3 import Bucket
# Create S3 bucket with custom properties
bucket = Bucket(
"MyBucket",
BucketName="my-unique-bucket-name",
VersioningConfiguration={
"Status": "Enabled"
},
BucketEncryption={
"ServerSideEncryptionConfiguration": [{
"ServerSideEncryptionByDefault": {
"SSEAlgorithm": "AES256"
}
}]
},
PublicAccessBlockConfiguration={
"BlockPublicAcls": True,
"BlockPublicPolicy": True,
"IgnorePublicAcls": True,
"RestrictPublicBuckets": True
}
)from troposphere import Ref, GetAtt, Output
from troposphere.ec2 import Instance
# Create instance
instance = Instance(
"MyInstance",
ImageId="ami-0abcdef1234567890",
InstanceType="t2.micro"
)
# Reference the instance
instance_ref = Ref(instance)
# or
instance_ref = instance.ref()
# Get instance attributes
public_ip = GetAtt(instance, "PublicIp")
# or
public_ip = instance.get_att("PublicIp")
# Use in outputs
Output(
"InstanceId",
Value=Ref(instance),
Description="Instance ID"
)
Output(
"PublicIP",
Value=GetAtt(instance, "PublicIp"),
Description="Instance public IP"
)Install with Tessl CLI
npx tessl i tessl/pypi-troposphere