AWS DevOps & Developer Productivity Blog
Use a CreationPolicy to Wait for On-Instance Configurations
When you provision an Amazon EC2 instance in an AWS CloudFormation stack, you might specify additional actions to configure the instance, such as install software packages or bootstrap applications. Normally, CloudFormation proceeds with stack creation after the instance has been successfully created. However, you can use a CreationPolicy so that CloudFormation proceeds with stack creation only after your configuration actions are done. That way you’ll know your applications are ready to go after stack creation succeeds.
A CreationPolicy instructs CloudFormation to wait on an instance until CloudFormation receives the specified number of signals. This policy takes effect only when CloudFormation creates the instance. Here’s what a creation policy looks like:
"AutoScalingGroup": { "Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": { ... }, "CreationPolicy": { "ResourceSignal": { "Count": "3", "Timeout": "PT5M" } } }
A CreationPolicy must be associated with a resource, such as an EC2 instance or an Auto Scaling group. This association is how CloudFormation knows what resource to wait on. In the example policy, the CreationPolicy is associated with an Auto Scaling group. CloudFormation waits on the Auto Scaling group until CloudFormation receives three signals within five minutes. Because the Auto Scaling group’s desired capacity is set to three, the signal count is set to three (one for each instance).
If three signals are not received after five minutes, CloudFormation immediately stops the stack creation labels the Auto Scaling group as failed to create, so make sure you specify a timeout period that gives your instances and applications enough time to be deployed.
Signaling a Resource
You can easily send signals from the instances that you’re provisioning. On those instances, you should be using the cfn-init helper script in the EC2 user data script to deploy applications. After the cfn-init script, just add a command to run the cfn-signal helper script, as in the following example:
"UserData": { "Fn::Base64": { "Fn::Join" [ "", [ "/opt/aws/bin/cfn-init ", ... "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref": "AWS::StackName" }, " --resource AutoScalingGroup " , " --region ", { "Ref" : "AWS::Region" }, "n" ] ] } }
When you signal CloudFormation, you need let it know what stack and what resource you’re signaling. In the example, the cfn-signal command specifies the stack that is provisioning the instance, the logical ID of the resource (AutoScalingGroup), and the region in which the stack is being created.
With the CreationPolicy attribute and the cfn-signal helper script, you can ensure that your stacks are created successfully only when your applications are successfully deployed. For more information, you can view a complete sample template in the AWS CloudFormation User Guide.