Lesson 4 of 5 AWS CloudFormation

Bootstrapping Instances and Extending CloudFormation with Custom Resources

Some configuration cannot be expressed as resource properties: software must be installed on instances, the stack must wait until that software is ready, and some tasks need custom code. This lesson explains the CloudFormation helper scripts, creation policies and wait conditions, and Lambda-backed custom resources, including the failure modes that leave stacks waiting.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how cfn-init, cfn-signal and cfn-hup configure instances from template metadata.
  • Distinguish between creation policies and wait conditions and explain how resource signals work.
  • Explain how Lambda-backed custom resources receive requests and return responses.
  • Identify why a stack hangs on a custom resource or signal and how to prevent it.

User Data and Helper Scripts

EC2 user data runs a script when an instance first boots. Writing complex configuration as a user data script is fragile: it is hard to read, runs only once and gives CloudFormation no indication of whether it succeeded. The CloudFormation helper scripts, preinstalled on Amazon Linux AMIs and available as a package for other systems, provide a declarative alternative.

cfn-init
Reads the AWS::CloudFormation::Init metadata of a resource and applies it: installs packages, creates groups and users, downloads sources, writes files, runs commands and enables services, in that order within each config. configSets define the order of several configs.
cfn-signal
Sends a success or failure signal to a resource with a creation policy or to a wait condition, usually with the exit code of cfn-init.
cfn-hup
A daemon that checks the resource metadata for changes, every 15 minutes by default, and runs hooks, typically rerunning cfn-init, when the metadata changes during a stack update. It lets stack updates change instance configuration without replacing instances.
cfn-get-metadata
Retrieves metadata for use by scripts.
Resources:
  WebServer:
    Type: AWS::EC2::Instance
    CreationPolicy:
      ResourceSignal:
        Count: 1
        Timeout: PT15M
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            dnf:
              nginx: []
          files:
            /etc/nginx/conf.d/app.conf:
              source: !Sub "https://${ConfigBucket}.s3.${AWS::Region}.amazonaws.com/app.conf"
          services:
            systemd:
              nginx: {enabled: true, ensureRunning: true}
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: t4g.small
      IamInstanceProfile: !Ref WebProfile
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region}
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region}

The instance stays CREATE_IN_PROGRESS until cfn-signal reports. If cfn-init fails, -e $? sends a failure signal and the stack rolls back immediately instead of waiting for the timeout. Downloading files from a private bucket requires an AWS::CloudFormation::Authentication section or an instance profile with read access.

Creation Policies and Wait Conditions

A creation policy is an attribute on an EC2 instance, an Auto Scaling group or a few other resource types. It tells CloudFormation to wait for a number of success signals within a timeout before marking the resource complete. For Auto Scaling groups, the count is usually the desired capacity, and each instance signals separately. A timeout or failure signal fails the resource and triggers rollback. The maximum timeout is 12 hours.

A wait condition is a pair of resources, AWS::CloudFormation::WaitConditionHandle and AWS::CloudFormation::WaitCondition. The handle provides a presigned URL to which any process can send a signal, and the wait condition waits for a count of signals within a timeout. Wait conditions are useful when the signal comes from something other than the resource, such as an external system or an on-premises process, and to pause stack creation until a later step, with DependsOn controlling what waits. For EC2 instances and Auto Scaling groups, AWS recommends creation policies.

The following diagram shows the path of a success signal.

How a creation policy waits for signals. Each instance's user data runs cfn-init to apply the template's configuration and then cfn-signal with cfn-init's exit code. The signal is an API call to the CloudFormation endpoint, so instances in private subnets need a NAT gateway or a CloudFormation interface endpoint. The resource completes when the required number of success signals arrives within the timeout; a failure signal or a timeout fails it and triggers rollback. A wait condition handle instead gives any external process a presigned URL to signal.
A signal that cannot reach the endpoint looks the same as a failed configuration.
Match the pairs

Bootstrap helpers

Exam skills 2.1.1 · 2.3.3

Match each bootstrapping helper with what it does.

Log in to try this activity Interactive activities are free with an account.

Custom Resources

A custom resource runs custom provisioning logic during stack operations. It is declared with the type AWS::CloudFormation::CustomResource or Custom::Name, and its ServiceToken property is the ARN of a Lambda function or an SNS topic. On create, update and delete, CloudFormation sends a request containing the RequestType (Create, Update or Delete), the resource properties, the old properties on update, a PhysicalResourceId on update and delete, and a presigned S3 ResponseURL. The function performs its work and must upload a JSON response to the URL with Status SUCCESS or FAILED, a PhysicalResourceId and optional Data that other resources can read with Fn::GetAtt.

Typical uses include looking up values that no resource type exposes, emptying a bucket before deletion, seeding a database, calling a third-party API or configuring a service that lacks CloudFormation support. For Python and Node.js functions defined inline, the cfn-response module simplifies sending the response.

Failure modes

If the function never sends a response, because it raised an unhandled exception, timed out or ran out of memory, CloudFormation waits until the custom resource times out. The default is one hour, and the ServiceTimeout property can set a shorter limit. During a stack deletion or rollback, the same wait happens on the Delete request. The function should therefore wrap all logic in error handling that always sends a response, handle Delete requests (even if there is nothing to delete), and return the same physical ID on update unless replacement is intended, because a new physical ID makes CloudFormation send a Delete request for the old one.

The following diagram shows the request and response of a custom resource.

The custom resource protocol. On Create, Update or Delete, CloudFormation sends a request to the function named by ServiceToken, with the RequestType, the resource properties and a presigned S3 ResponseURL. The function does its work and uploads a JSON response with Status SUCCESS or FAILED, a PhysicalResourceId and optional Data, which other resources read with Fn::GetAtt. If no response arrives, CloudFormation waits until the timeout, one hour by default.
The function must always send a response, including for Delete requests.

Changing physical IDs

A custom resource function that returns a new PhysicalResourceId on every update causes CloudFormation to treat each update as a replacement and to send a Delete for the previous ID after the update. If the Delete handler removes something shared, the update deletes it.

True or false

Custom resources

Exam skills 2.1.1

Check four facts about custom resources and signals.

Log in to try this activity Interactive activities are free with an account.
Worked example

Emptying a Bucket on Stack Deletion

A test stack creates an S3 bucket for build outputs. Deleting the stack fails because CloudFormation cannot delete a bucket that contains objects. The team wants stack deletion to succeed automatically.

A Lambda-backed custom resource is added with the bucket name as a property and a dependency on the bucket, so it is deleted before the bucket. On Create and Update, the function sends SUCCESS without doing anything. On Delete, it deletes all object versions and delete markers, then sends SUCCESS; any exception results in FAILED with the error message, so the stack never waits for an hour. The function role has permission to list and delete objects in that bucket only. For a production bucket, the team would instead use DeletionPolicy Retain, because emptying it would destroy data.

Check yourself

A stack has been in CREATE_IN_PROGRESS for an hour on a custom resource. The Lambda function's logs show an unhandled KeyError. What happened, and how is it prevented?

Show answer

The function crashed before sending a response to the ResponseURL, so CloudFormation waits until the custom resource times out. Wrap the logic in error handling that always sends SUCCESS or FAILED, and set ServiceTimeout to a shorter value.

Exam Tips

Remember for the exam

  • cfn-init applies AWS::CloudFormation::Init metadata; cfn-signal reports success or failure; cfn-hup reapplies metadata changes during stack updates.
  • Use a CreationPolicy with ResourceSignal on instances and Auto Scaling groups; use wait conditions for signals from external processes. Timeouts can be up to 12 hours.
  • Pass cfn-init's exit code to cfn-signal (-e $?) so failures roll back immediately.
  • Custom resources must always send SUCCESS or FAILED to the ResponseURL, including for Delete requests; otherwise the stack waits until the timeout (default one hour, ServiceTimeout to shorten).