AWS CloudFormation creation library that facilitates building infrastructure templates programmatically in Python
Tag management for AWS resource tagging with validation, sorting, and concatenation support, plus metadata management for CloudFormation templates.
Create and manage AWS resource tags with automatic validation and sorting.
class Tag(AWSHelperFn):
def __init__(self, k: object, v: object):
"""
Single tag key-value pair.
Args:
k: Tag key
v: Tag value
"""
class Tags(AWSHelperFn):
def __init__(self, *args: object, **kwargs):
"""
Collection of tags with validation and sorting.
Args:
*args: Tag dictionaries or Tag objects
**kwargs: Tag key-value pairs
"""
def __add__(self, newtags: Tags) -> Tags:
"""
Concatenate tags collections.
Args:
newtags: Tags object to concatenate
Returns:
Tags: Combined tags collection
"""
def to_dict(self) -> List[Dict[str, Any]]:
"""
Convert tags to CloudFormation format.
Returns:
List[dict]: Tags in CloudFormation format
"""
@classmethod
def from_dict(cls, title: Optional[str] = None, **kwargs):
"""
Create Tags from dictionary.
Args:
**kwargs: Tag key-value pairs
Returns:
Tags: Tags object
"""from troposphere import Tag, Tags
from troposphere.ec2 import Instance
# Single tag
environment_tag = Tag("Environment", "Production")
# Multiple tags using kwargs
resource_tags = Tags(
Environment="Production",
Application="WebServer",
Owner="DevOps",
CostCenter="Engineering"
)
# Multiple tags using dictionaries
tag_dict = {
"Environment": "Production",
"Application": "WebServer",
"BackupRequired": "true"
}
resource_tags = Tags(tag_dict)
# Use tags in resources
instance = Instance(
"WebServer",
ImageId="ami-0abcdef1234567890",
InstanceType="t3.micro",
Tags=resource_tags
)from troposphere import Tags
# Base organization tags
org_tags = Tags(
Organization="MyCompany",
Department="Engineering",
CostCenter="12345"
)
# Environment-specific tags
env_tags = Tags(
Environment="Production",
Backup="Daily"
)
# Application-specific tags
app_tags = Tags(
Application="WebAPI",
Version="2.1.0"
)
# Combine all tags
combined_tags = org_tags + env_tags + app_tags
# Use in resource
from troposphere.s3 import Bucket
bucket = Bucket(
"AppBucket",
Tags=combined_tags
)from troposphere import Template, Parameter, Tags, Sub, Ref
template = Template()
# Parameters for dynamic tags
project_name = template.add_parameter(Parameter(
"ProjectName",
Type="String",
Description="Project name for tagging"
))
environment = template.add_parameter(Parameter(
"Environment",
Type="String",
AllowedValues=["dev", "staging", "prod"],
Description="Environment name"
))
# Dynamic tags using parameters
dynamic_tags = Tags(
ProjectName=Ref(project_name),
Environment=Ref(environment),
StackName=Ref("AWS::StackName"),
CreatedBy=Sub("CloudFormation-${AWS::StackName}"),
Timestamp=Sub("${AWS::StackId}")
)from troposphere import Template, Parameter, Tags, If, Equals, Ref
template = Template()
backup_enabled = template.add_parameter(Parameter(
"BackupEnabled",
Type="String",
Default="false",
AllowedValues=["true", "false"]
))
template.add_condition("EnableBackup", Equals(Ref(backup_enabled), "true"))
# Base tags
base_tags = Tags(
Environment="Production",
Application="Database"
)
# Conditional backup tag
backup_tag = Tags(
BackupSchedule=If("EnableBackup", "Daily", Ref("AWS::NoValue"))
)
# Combined tags
all_tags = base_tags + backup_tagfrom troposphere import Tags, Join, Select, Split, GetAZs
# Tags using intrinsic functions
function_tags = Tags(
# Tag with joined values
Location=Join("-", [Ref("AWS::Region"), Select(0, GetAZs())]),
# Tag with string manipulation
ShortStackName=Select(0, Split("-", Ref("AWS::StackName"))),
# Tag with substitution
ResourceName=Sub("${AWS::StackName}-${ResourceType}", ResourceType="Instance")
)from troposphere import Template
# Create template with metadata
template = Template(
Description="Web application infrastructure",
Metadata={
"AWS::CloudFormation::Interface": {
"ParameterGroups": [
{
"Label": {"default": "Network Configuration"},
"Parameters": ["VpcId", "SubnetIds"]
},
{
"Label": {"default": "Instance Configuration"},
"Parameters": ["InstanceType", "KeyName"]
}
],
"ParameterLabels": {
"VpcId": {"default": "VPC"},
"SubnetIds": {"default": "Subnets"},
"InstanceType": {"default": "Instance Type"},
"KeyName": {"default": "Key Pair"}
}
}
}
)
# Add additional metadata
template.set_metadata({
"Version": "1.0.0",
"Author": "DevOps Team",
"Purpose": "Production web server deployment",
"LastUpdated": "2024-01-15"
})Install with Tessl CLI
npx tessl i tessl/pypi-troposphere