Have you ever set up a temporary application environment and wished you could schedule automatic deletion of the environment rather than remembering to clean it up after you are done? If the answer is yes, then this blog post is for you.
Here is an example of setting up an AWS CloudFormation stack with a configurable TTL (time-to-live). When the TTL is up, deletion of the stack is triggered automatically. You can use this idea regardless of whether you have a single Amazon EC2 instance in the stack or a complex application environment. You can even use this idea in combination with other deployment and management services such as AWS Elastic Beanstalk or AWS OpsWorks, as long as your environment is modeled inside an AWS CloudFormation stack.
In this example, first I setup a sample application on an EC2 instance and then configure a ‘TTL’:
Configuring TTL is simple. Just schedule execution of a one-line shell script, deletestack.sh, using the ‘at’ command. The shell script uses AWS Command Line Interface to call aws cloudformation delete-stack:
Notice that the EC2 instance requires permissions to delete all of the stack resources. The permissions are granted to the EC2 instance via an IAM role. Also, notice that for the stack deletion to succeed, the IAM role needs to be the last in the order of deletion. You can ensure that the role is the last in the order of deletion by making other resources dependent on the role. Finally, as a best practice, you should grant the least possible privilege to the role. You can do this by using a finer grained policy document for the IAM role:
You can try the full sample template here:
-- Chetan Dandekar, Senior Product Manager, Amazon Web Services.