Troposphere is a Python library which makes it easier to write and maintain CloudFormation templates. From the README:
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.
Troposphere can be easily installed inside a virtualenv with pip install troposphere. It’s also probably a good idea to make sure you can switch AWS accounts quickly on the CLI. This is needed when we want to run Ansible playbooks against CloudFormation. More on that later.
Let’s get to some examples.
Every Troposphere file has to start with a few imports and a description.
After that we will put in a few params which we will with data using Ansible later on. Here’s a parameter for the name of the CloudFormation stack.
And here’s a param for the name of a database. Notice the constraints we can use.
Creating an RDS instance
Here’s an example of a Troposphere template which will create a CloudFormation JSON file that will launch an RDS instance. We’ll give the RDS a name, assign some storage and a subnet, and we will say that its engine should be MySQL 5.6.
Notice the ref being used in some places. You can ref to a param to get its value returned.
CloudFormation allows us to give some output after CloudFormation is done doing its business. In this case we will join some data together to create a JDBC connection string. You can copy-paste this into the configuration of your application, obviously.
Notice how in the beginning of this tutorial we did
t = Template()? To generate the CloudFormation JSON file we’ll need to write the result of our Troposphere code to valid JSON. Troposphere will do this for us, of course.
Here’s the results of our hard work:
Some documentation on functions can be found on Nullege.
To make it easy to fill in the blanks on those params I use Ansible. Ansible can talk to CloudFormation to either run new CloudFormation stacks, or destroy them completely.
This is the last step in this tutorial. Again, Ansible will fill in our params using Ansible’s vars function and then we tell Ansible to run a CloudFormation task using our JSON file.
This allows you to run the same JSON file again and again by just changing some variables in an Ansible playbook.