Convert Figma logo to code with AI

cloudtools logotroposphere

troposphere - Python library to create AWS CloudFormation descriptions

4,927
1,445
4,927
165

Top Related Projects

42,146

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.

20,922

Pulumi - Infrastructure as Code in any programming language 🚀

11,501

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code

⚡ Serverless Framework – Effortlessly build apps that auto-scale, incur zero costs when idle, and require minimal maintenance using AWS Lambda and other managed cloud services.

62,307

Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy and maintain. Automate everything from code deployment to network configuration to cloud management, in a language that approaches plain English, using SSH, with no agents to install on remote systems. https://docs.ansible.com.

109,710

Production-Grade Container Scheduling and Management

Quick Overview

Troposphere is a Python library that provides a set of tools to create AWS CloudFormation descriptions. It allows developers to write Python code that generates CloudFormation templates, making it easier to manage and version control infrastructure as code. Troposphere supports a wide range of AWS resources and can be used to create complex, dynamic CloudFormation templates.

Pros

  • Enables writing infrastructure as code using Python, providing more flexibility and power than raw JSON or YAML templates
  • Supports a wide range of AWS resources and services
  • Allows for dynamic template generation, making it easier to create reusable and parameterized infrastructure
  • Provides type checking and validation, reducing errors in CloudFormation templates

Cons

  • Requires knowledge of Python programming, which may be a barrier for some users
  • Can be more verbose than writing raw CloudFormation templates for simple use cases
  • May have a steeper learning curve compared to using the AWS Console or writing templates directly
  • Requires keeping the library updated to support new AWS services and features

Code Examples

  1. Creating an EC2 instance:
from troposphere import Ref, Template
from troposphere.ec2 import Instance

t = Template()

instance = t.add_resource(Instance(
    "MyInstance",
    ImageId="ami-0c55b159cbfafe1f0",
    InstanceType="t2.micro",
    KeyName=Ref("KeyPair"),
))

print(t.to_json())
  1. Creating an S3 bucket with a bucket policy:
from troposphere import Template, Ref, Join
from troposphere.s3 import Bucket, BucketPolicy

t = Template()

s3_bucket = t.add_resource(Bucket("S3Bucket"))

t.add_resource(BucketPolicy(
    "BucketPolicy",
    Bucket=Ref(s3_bucket),
    PolicyDocument={
        "Statement": [{
            "Action": ["s3:GetObject"],
            "Effect": "Allow",
            "Resource": Join("", ["arn:aws:s3:::", Ref(s3_bucket), "/*"]),
            "Principal": "*"
        }]
    }
))

print(t.to_json())
  1. Creating a VPC with public and private subnets:
from troposphere import Template, Ref
from troposphere.ec2 import VPC, Subnet, InternetGateway, VPCGatewayAttachment

t = Template()

vpc = t.add_resource(VPC(
    "MyVPC",
    CidrBlock="10.0.0.0/16",
    EnableDnsHostnames=True,
    EnableDnsSupport=True,
))

public_subnet = t.add_resource(Subnet(
    "PublicSubnet",
    CidrBlock="10.0.1.0/24",
    VpcId=Ref(vpc),
    MapPublicIpOnLaunch=True,
))

private_subnet = t.add_resource(Subnet(
    "PrivateSubnet",
    CidrBlock="10.0.2.0/24",
    VpcId=Ref(vpc),
))

internet_gateway = t.add_resource(InternetGateway("InternetGateway"))

t.add_resource(VPCGatewayAttachment(
    "VPCGatewayAttachment",
    VpcId=Ref(vpc),
    InternetGatewayId=Ref(internet_gateway),
))

print(t.to_json())

Getting Started

To get started with Troposphere:

  1. Install the library:

    pip install troposphere
    
  2. Import the necessary modules and create a template:

    from troposphere import Template
    t = Template()
    
  3. Add resources to your template:

    from troposphere.s3 import Bucket
    t.add_resource(Bucket("MyBucket"))
    
  4. Generate the CloudFormation template:

    print(t.to_json())
    

Competitor Comparisons

42,146

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.

Pros of Terraform

  • Multi-cloud support, allowing infrastructure management across various providers
  • Large ecosystem with extensive provider plugins and modules
  • Declarative syntax with state management for better consistency and reproducibility

Cons of Terraform

  • Steeper learning curve, especially for those new to infrastructure as code
  • Potential for state drift and management complexities in large-scale deployments
  • Less tightly integrated with specific cloud providers compared to native tools

Code Comparison

Terraform:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Troposphere:

from troposphere import ec2

instance = ec2.Instance("ExampleInstance",
    ImageId="ami-0c55b159cbfafe1f0",
    InstanceType="t2.micro"
)

Key Differences

  • Terraform uses HCL (HashiCorp Configuration Language), while Troposphere uses Python
  • Terraform is a standalone tool, whereas Troposphere is a Python library for generating CloudFormation templates
  • Terraform has built-in state management, while Troposphere relies on AWS CloudFormation for state handling

Use Cases

  • Terraform: Multi-cloud deployments, complex infrastructure setups, teams familiar with HCL
  • Troposphere: AWS-specific deployments, integration with existing Python codebases, generating CloudFormation templates programmatically
20,922

Pulumi - Infrastructure as Code in any programming language 🚀

Pros of Pulumi

  • Supports multiple programming languages (Python, JavaScript, TypeScript, Go, .NET)
  • Offers real-time feedback and error checking during development
  • Provides a unified workflow for multi-cloud deployments

Cons of Pulumi

  • Steeper learning curve for users new to infrastructure-as-code
  • Requires runtime installation and management
  • May have slower execution times compared to template-based solutions

Code Comparison

Troposphere (Python):

from troposphere import Template, ec2

t = Template()
instance = ec2.Instance("MyInstance",
    ImageId="ami-0c55b159cbfafe1f0",
    InstanceType="t2.micro")
t.add_resource(instance)

Pulumi (Python):

import pulumi
from pulumi_aws import ec2

instance = ec2.Instance("my-instance",
    instance_type="t2.micro",
    ami="ami-0c55b159cbfafe1f0")

pulumi.export("instanceId", instance.id)

Both Troposphere and Pulumi allow users to define cloud infrastructure using code. Troposphere focuses on generating CloudFormation templates for AWS, while Pulumi offers a more versatile approach supporting multiple cloud providers and programming languages. Troposphere may be easier for those familiar with CloudFormation, while Pulumi provides a more flexible and powerful infrastructure-as-code solution.

11,501

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code

Pros of AWS CDK

  • Supports multiple programming languages (TypeScript, Python, Java, C#)
  • Provides higher-level constructs for easier resource creation
  • Offers built-in testing capabilities for infrastructure code

Cons of AWS CDK

  • Steeper learning curve due to its abstraction layers
  • Requires compilation step, which can slow down development process
  • Limited support for non-AWS resources compared to Troposphere

Code Comparison

AWS CDK (TypeScript):

import * as cdk from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3';

const bucket = new s3.Bucket(this, 'MyBucket', {
  versioned: true,
  encryption: s3.BucketEncryption.S3_MANAGED,
});

Troposphere (Python):

from troposphere import Template, s3

t = Template()
bucket = s3.Bucket("MyBucket",
    VersioningConfiguration=s3.VersioningConfiguration(
        Status="Enabled"
    ),
    BucketEncryption=s3.BucketEncryption(
        ServerSideEncryptionConfiguration=[
            s3.ServerSideEncryptionRule(
                ServerSideEncryptionByDefault=s3.ServerSideEncryptionByDefault(
                    SSEAlgorithm="AES256"
                )
            )
        ]
    )
)
t.add_resource(bucket)

Both AWS CDK and Troposphere are powerful tools for infrastructure as code, with AWS CDK offering a more abstracted approach and support for multiple languages, while Troposphere provides a more direct mapping to CloudFormation resources in Python.

⚡ Serverless Framework – Effortlessly build apps that auto-scale, incur zero costs when idle, and require minimal maintenance using AWS Lambda and other managed cloud services.

Pros of Serverless

  • Simplified deployment process with a focus on serverless architectures
  • Extensive plugin ecosystem for extending functionality
  • Multi-cloud support (AWS, Azure, Google Cloud, etc.)

Cons of Serverless

  • Limited to serverless-specific resources and architectures
  • Steeper learning curve for users new to serverless concepts
  • Less flexibility for complex infrastructure configurations

Code Comparison

Serverless (serverless.yml):

service: my-service
provider:
  name: aws
  runtime: nodejs14.x
functions:
  hello:
    handler: handler.hello

Troposphere (Python):

from troposphere import Template, Function
t = Template()
t.add_resource(Function(
    "MyFunction",
    Handler="index.handler",
    Runtime="nodejs14.x"
))

Key Differences

  • Serverless focuses on serverless architectures, while Troposphere is a general-purpose IaC tool
  • Serverless uses YAML for configuration, Troposphere uses Python
  • Troposphere offers more flexibility for complex infrastructure, but requires more code
  • Serverless provides a simpler deployment process, especially for serverless applications

Use Cases

  • Choose Serverless for rapid development of serverless applications with minimal configuration
  • Opt for Troposphere when working with complex, diverse AWS resources or when Python is preferred
62,307

Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy and maintain. Automate everything from code deployment to network configuration to cloud management, in a language that approaches plain English, using SSH, with no agents to install on remote systems. https://docs.ansible.com.

Pros of Ansible

  • Broader scope: Ansible is a complete configuration management and automation tool, while Troposphere is focused on AWS CloudFormation
  • Agentless architecture: Ansible doesn't require agents on managed nodes, simplifying deployment and maintenance
  • Extensive module library: Ansible has a vast collection of modules for various tasks and integrations

Cons of Ansible

  • Steeper learning curve: Ansible's broader scope means it can be more complex to learn and master compared to Troposphere's focused approach
  • Performance: Ansible can be slower for large-scale deployments compared to Troposphere's Python-based template generation

Code Comparison

Ansible playbook example:

- name: Create EC2 instance
  ec2:
    key_name: mykey
    instance_type: t2.micro
    image: ami-123456
    wait: yes
    group: webserver
    count: 1

Troposphere example:

instance = ec2.Instance("MyInstance",
    InstanceType="t2.micro",
    ImageId="ami-123456",
    KeyName="mykey",
    SecurityGroups=["webserver"],
)

Both examples create an EC2 instance, but Ansible uses YAML syntax and its ec2 module, while Troposphere uses Python to generate CloudFormation templates.

109,710

Production-Grade Container Scheduling and Management

Pros of Kubernetes

  • Widely adopted, industry-standard container orchestration platform
  • Extensive ecosystem with numerous tools and integrations
  • Highly scalable and suitable for large, complex deployments

Cons of Kubernetes

  • Steeper learning curve and more complex setup compared to Troposphere
  • Requires more resources and overhead for small-scale projects
  • Less focused on infrastructure-as-code for cloud providers

Code Comparison

Kubernetes manifest (YAML):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx

Troposphere (Python):

from troposphere import ec2

instance = ec2.Instance(
    "MyInstance",
    InstanceType="t2.micro",
    ImageId="ami-0c55b159cbfafe1f0"
)

Summary

Kubernetes is a powerful container orchestration platform suitable for large-scale deployments, while Troposphere is a Python library for generating AWS CloudFormation templates. Kubernetes offers more flexibility and scalability for containerized applications, but Troposphere is more focused on infrastructure-as-code for AWS specifically. The choice between the two depends on the project requirements, scale, and target infrastructure.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

=========== troposphere

.. image:: https://img.shields.io/pypi/v/troposphere.svg :target: https://pypi.python.org/pypi/troposphere :alt: PyPI Version

.. image:: https://github.com/cloudtools/troposphere/actions/workflows/tests.yml/badge.svg :target: https://github.com/cloudtools/troposphere/actions?query=branch%3Amain :alt: Build Status

.. image:: https://img.shields.io/pypi/l/troposphere.svg :target: https://opensource.org/licenses/BSD-2-Clause :alt: license: New BSD license

.. image:: https://readthedocs.org/projects/troposphere/badge/?version=latest :target: https://troposphere.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status

About

troposphere - library to create AWS CloudFormation_ descriptions

The troposphere library allows for easier creation of the AWS CloudFormation JSON_ by writing Python code to describe the AWS resources. troposphere also includes some basic support for OpenStack resources_ via Heat.

To facilitate catching CloudFormation or JSON errors early the library has property and type checking built into the classes.

Installation

troposphere can be installed using the pip distribution system for Python by issuing:

.. code:: sh

$ pip install troposphere

To install troposphere with awacs <https://github.com/cloudtools/awacs>_ (recommended soft dependency):

.. code:: sh

$ pip install troposphere[policy]

Alternatively, you can use setup.py to install by cloning this repository and issuing:

.. code:: sh

$ python setup.py install  # you may need sudo depending on your python installation

Examples

A simple example to create an instance would look like this:

.. code:: python

>>> from troposphere import Ref, Template
>>> import troposphere.ec2 as ec2
>>> t = Template()
>>> instance = ec2.Instance("myinstance")
>>> instance.ImageId = "ami-951945d0"
>>> instance.InstanceType = "t1.micro"
>>> t.add_resource(instance)
<troposphere.ec2.Instance object at 0x101bf3390>
>>> print(t.to_json())
{
    "Resources": {
        "myinstance": {
            "Properties": {
                "ImageId": "ami-951945d0",
                "InstanceType": "t1.micro"
            },
            "Type": "AWS::EC2::Instance"
        }
    }
}
>>> print(t.to_yaml())
Resources:
    myinstance:
        Properties:
            ImageId: ami-951945d0
            InstanceType: t1.micro
        Type: AWS::EC2::Instance

Alternatively, parameters can be used instead of properties:

.. code:: python

>>> instance = ec2.Instance("myinstance", ImageId="ami-951945d0", InstanceType="t1.micro")
>>> t.add_resource(instance)
<troposphere.ec2.Instance object at 0x101bf3550>

And add_resource() returns the object to make it easy to use with Ref():

.. code:: python

>>> instance = t.add_resource(ec2.Instance("myinstance", ImageId="ami-951945d0", InstanceType="t1.micro"))
>>> Ref(instance)
<troposphere.Ref object at 0x101bf3490>

Examples of the error checking (full tracebacks removed for clarity):

Incorrect property being set on AWS resource:

.. code:: python

>>> import troposphere.ec2 as ec2
>>> ec2.Instance("ec2instance", image="i-XXXX")
Traceback (most recent call last):
...
AttributeError: AWS::EC2::Instance object does not support attribute image

Incorrect type for AWS resource property:

.. code:: python

>>> ec2.Instance("ec2instance", ImageId=1)
Traceback (most recent call last):
...
TypeError: ImageId is <type 'int'>, expected <type 'basestring'>

Missing required property for the AWS resource:

.. code:: python

>>> from troposphere import Template
>>> import troposphere.ec2 as ec2
>>> t = Template()
>>> t.add_resource(ec2.Subnet("ec2subnet", VpcId="vpcid"))
<troposphere.ec2.Subnet object at 0x100830ed0>
>>> print(t.to_json())
Traceback (most recent call last):
...
ValueError: Resource CidrBlock required in type AWS::EC2::Subnet (title: ec2subnet)

Currently supported resource types

  • AWS Resource Types_
  • OpenStack Resource Types_

Duplicating a single instance sample would look like this

.. code:: python

# Converted from EC2InstanceSample.template located at:
# http://aws.amazon.com/cloudformation/aws-cloudformation-templates/

from troposphere import Base64, FindInMap, GetAtt
from troposphere import Parameter, Output, Ref, Template
import troposphere.ec2 as ec2


template = Template()

keyname_param = template.add_parameter(Parameter(
    "KeyName",
    Description="Name of an existing EC2 KeyPair to enable SSH "
                "access to the instance",
    Type="String",
))

template.add_mapping('RegionMap', {
    "us-east-1":      {"AMI": "ami-7f418316"},
    "us-west-1":      {"AMI": "ami-951945d0"},
    "us-west-2":      {"AMI": "ami-16fd7026"},
    "eu-west-1":      {"AMI": "ami-24506250"},
    "sa-east-1":      {"AMI": "ami-3e3be423"},
    "ap-southeast-1": {"AMI": "ami-74dda626"},
    "ap-northeast-1": {"AMI": "ami-dcfa4edd"}
})

ec2_instance = template.add_resource(ec2.Instance(
    "Ec2Instance",
    ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
    InstanceType="t1.micro",
    KeyName=Ref(keyname_param),
    SecurityGroups=["default"],
    UserData=Base64("80")
))

template.add_output([
    Output(
        "InstanceId",
        Description="InstanceId of the newly created EC2 instance",
        Value=Ref(ec2_instance),
    ),
    Output(
        "AZ",
        Description="Availability Zone of the newly created EC2 instance",
        Value=GetAtt(ec2_instance, "AvailabilityZone"),
    ),
    Output(
        "PublicIP",
        Description="Public IP address of the newly created EC2 instance",
        Value=GetAtt(ec2_instance, "PublicIp"),
    ),
    Output(
        "PrivateIP",
        Description="Private IP address of the newly created EC2 instance",
        Value=GetAtt(ec2_instance, "PrivateIp"),
    ),
    Output(
        "PublicDNS",
        Description="Public DNSName of the newly created EC2 instance",
        Value=GetAtt(ec2_instance, "PublicDnsName"),
    ),
    Output(
        "PrivateDNS",
        Description="Private DNSName of the newly created EC2 instance",
        Value=GetAtt(ec2_instance, "PrivateDnsName"),
    ),
])

print(template.to_json())

Community

We have a Google Group, cloudtools-dev_, where you can ask questions and engage with the troposphere community. Issues and pull requests are always welcome!

Licensing

troposphere is licensed under the BSD 2-Clause license. See LICENSE for the troposphere full license text.

.. _AWS CloudFormation: http://aws.amazon.com/cloudformation .. _AWS CloudFormation JSON: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html .. _OpenStack resources: http://docs.openstack.org/developer/heat/template_guide/openstack.html .. _cloudtools-dev: https://groups.google.com/forum/#!forum/cloudtools-dev .. _LICENSE: https://github.com/cloudtools/troposphere/blob/master/LICENSE .. _BSD 2-Clause license: http://opensource.org/licenses/BSD-2-Clause .. _AWS Resource Types: https://github.com/cloudtools/troposphere/blob/master/resources_aws.md .. _OpenStack Resource Types: https://github.com/cloudtools/troposphere/blob/master/resources_openstack.md