Troposphere

4.10.1 · active · verified Fri Apr 10

Troposphere is an open-source Python library that simplifies the creation of AWS CloudFormation JSON and YAML templates by allowing developers to define AWS resources using Python code. It offers a Pythonic syntax, built-in property and type checking to catch errors early, and promotes modular code. The library is actively maintained with frequent updates driven by the latest AWS Resource Specification, and also provides basic support for OpenStack Heat resources.

Warnings

Install

Imports

Quickstart

This quickstart code demonstrates how to create a basic AWS CloudFormation template using Troposphere to launch an EC2 instance. It defines an instance with a specific AMI, instance type, and key pair, and then outputs its public DNS name. Remember to replace `ami-0c55b159cbfafe1f0` and `my-ssh-key` with valid values for your AWS region and account. The template is then printed as a JSON string.

from troposphere import Template, Ref
import troposphere.ec2 as ec2

t = Template()
t.set_description("AWS CloudFormation template to create a single EC2 instance.")

instance_name = "MyWebServer"
instance = t.add_resource(ec2.Instance(
    instance_name,
    ImageId="ami-0c55b159cbfafe1f0", # Example AMI ID (Ubuntu 20.04 LTS HVM, SSD Volume Type)
    InstanceType="t2.micro",
    KeyName="my-ssh-key", # Replace with your EC2 Key Pair name
    Tags=[
        {"Key": "Name", "Value": instance_name}
    ]
))

# Output the Public DNS name of the instance
t.add_output(
    [Ref(instance.get_att("PublicDnsName"))],
    "Public DNS Name for the new EC2 instance",
    "PublicDns"
)

print(t.to_json(indent=2))

view raw JSON →