CloudFormation templates with troposphere

troposphere

CloudFormation templates are great for automating the creation and destruction of AWS resources, but hand coding JSON is prone to errors and mistakes. A project called troposphere has been gaining traction and approaches writing CF templates a little differently.

Instead of writing JSON, you create objects with the troposphere library using Python. Each object represents one resource in AWS such as an instance, an EIP or security group. The library can even catch errors due to its built in property and type checking.

Since troposphere is a Python library, you install it by doing:

sudo pip install troposphere --upgrade

Here is a slightly more than trivial example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python

# Import troposphere
from troposphere import Template, Ref, Output, Join, GetAtt, Parameter
import troposphere.ec2 as ec2

# Create a template for resources to live in
template = Template()

keypair = template.add_parameter(Parameter(
    "KeyPair",
    Type="String",
    Description="The name of the keypair to use for SSH access",
))

# Create a security group
sg = ec2.SecurityGroup('MySecurityGroup')
sg.GroupDescription = "Allow access to MyInstance"
sg.SecurityGroupIngress = [
    ec2.SecurityGroupRule(
        IpProtocol="tcp",
        FromPort="22",
        ToPort="22",
        CidrIp="0.0.0.0/0",
    )]

# Add security group to template
template.add_resource(sg)

# Create an instance
instance = ec2.Instance("MyInstance")
instance.ImageId = "ami-ef277b86"
instance.InstanceType = "t1.micro"
instance.SecurityGroups = [Ref(sg)]
instance.KeyName = Ref(keypair)

# Add instance to template
template.add_resource(instance)

# Add output to template
template.add_output(Output(
    "InstanceAccess",
    Description="Command to use to SSH to instance",
    Value=Join("", ["ssh -i ", Ref(keypair), " ubuntu@", GetAtt(instance, "PublicDnsName")])
))

# Print out CloudFormation template in JSON
print template.to_json()

This code creates a security group that allows SSH access, and then creates an instances that uses that security group. As a parameter, it take in the name of the Keypair to use, and outputs the SSH command to use to access the machine.

You can see the actual CloudFormation template in this gist. That is not something that should be coded by hand… just look at all those quotes and nesting.

The library is still young, and will mature over time, but is already super useful.

comments powered by Disqus