SkillSprout
Chapter 3 · Lesson 4
Advanced
6 min read

Custom Resources, Macros, Hooks and Template Governance

Overview

CloudFormation cannot natively express everything. Custom resources let a template call your own code (usually a Lambda function) during create, update and delete. Macros are template-preprocessing functions that rewrite a template before it is deployed. Hooks evaluate resources before provisioning and can warn or block non-compliant configuration.

Think of CloudFormation as a prefab-home factory. Custom resources are the special-order workshop for parts the factory does not stock, macros are the architect who rewrites the blueprint before building, and hooks are the building inspector who can stop construction at the door.

The exam asks you to pick the right extension point: a Lambda-backed custom resource for a one-off lookup or action, a macro or the AWS::Include/LanguageExtensions transform for template reuse, and Hooks or Guard for preventive governance.

Key Concepts

  • A Lambda-backed custom resource receives a request (Create/Update/Delete) with a pre-signed ResponseURL and must answer with SUCCESS or FAILED.
  • If the function never responds, the stack hangs until the custom resource timeout (default 1 hour); set ServiceTimeout to fail fast.
  • Always handle Delete gracefully and return success, or the stack gets stuck in DELETE_FAILED.
  • Macros (Transform) run a Lambda that returns a processed template; AWS::Serverless and AWS::LanguageExtensions are AWS-hosted transforms.
  • AWS::Include pulls snippets from S3; nested stacks are the preferred reuse mechanism for whole components.
  • CloudFormation Hooks run at PreCreate/PreUpdate/PreDelete and can be set to FAIL or WARN; they ship from the registry.
  • cfn-guard (policy-as-code) and cfn-lint validate templates in CI before deployment.
  • Stack policies and termination protection protect running stacks from accidental update or deletion.

Detailed Notes

Choosing an extension mechanism

NeedMechanismRuns when
Call an API with no native resource (e.g. look up latest AMI, empty a bucket on delete)Lambda-backed custom resourceStack create/update/delete
Rewrite or expand template syntaxMacro / transformBefore change set creation
Block non-compliant resources before they existCloudFormation HookPre-provisioning
Validate syntax and policy in CIcfn-lint, cfn-guardPipeline stage
Protect running resourcesStack policy, DeletionPolicy, termination protectionUpdate/delete time
Third-party or custom resource typesRegistry resource typesSame as native resources

Lambda-backed custom resource

yaml
Resources:
  EmptyBucketOnDelete:
    Type: Custom::EmptyBucket
    Properties:
      ServiceToken: !GetAtt CleanupFunction.Arn
      ServiceTimeout: 120
      BucketName: !Ref ArtifactBucket
  CleanupFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.12
      Handler: index.handler
      Timeout: 60
      Role: !GetAtt CleanupRole.Arn
      Code:
        ZipFile: |
          import boto3, cfnresponse
          def handler(event, context):
              try:
                  if event["RequestType"] == "Delete":
                      b = boto3.resource("s3").Bucket(event["ResourceProperties"]["BucketName"])
                      b.object_versions.delete()
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
              except Exception as e:
                  cfnresponse.send(event, context, cfnresponse.FAILED, {"Error": str(e)})

The incoming event contains RequestType, ResponseURL, StackId, RequestId, LogicalResourceId and ResourceProperties. The inline cfnresponse module exists only for inline (ZipFile) Node.js and Python code; packaged functions must send the HTTP PUT themselves or use the custom resource helper libraries. An SNS topic can also be the ServiceToken for non-Lambda handlers.

Common pitfalls: an uncaught exception without a response (stack waits for the timeout), forgetting the Delete branch, returning a different PhysicalResourceId on update (CloudFormation treats it as a replacement and issues a Delete for the old one), and returning more than 4 KB of response data.

Macros and transforms

A macro is registered with an AWS::CloudFormation::Macro resource pointing at a Lambda function. A template uses it with a top-level Transform or an inline Fn::Transform.

yaml
Transform:
  - AWS::LanguageExtensions
  - MyCompanyStandardTags

The Lambda receives the template fragment and returns { requestId, status: "success", fragment }. Macros run at change set creation, so reviewers see the expanded result. AWS::LanguageExtensions adds Fn::ForEach, Fn::Length, Fn::ToJsonString and default DeletionPolicy handling, covering many cases that once needed a macro.

Hooks and policy-as-code

CloudFormation Hooks are packaged with the CloudFormation CLI and activated from the registry in each account and Region. Managed hooks include the Guard hook (evaluates Guard rules stored in S3) and the Lambda hook (calls your function to approve or reject).

json
{
  "CloudFormationConfiguration": {
    "HookConfiguration": {
      "TargetStacks": "ALL",
      "FailureMode": "FAIL"
    }
  }
}

Use WARN while rolling out a new rule, then flip to FAIL. Hooks complement, not replace, AWS Config (detective) and SCPs (permission boundary): hooks catch the problem at deploy time for CloudFormation only.

A simple Guard rule:

text
rule s3_encrypted {
  Resources.*[ Type == "AWS::S3::Bucket" ] {
    Properties.BucketEncryption exists
  }
}

Protecting running stacks

  • Termination protection stops DeleteStack.
  • Stack policy (JSON) denies Update actions on named logical IDs unless explicitly overridden.
  • DeletionPolicy: Retain/Snapshot and UpdateReplacePolicy protect data resources.
  • Resource import and drift detection bring unmanaged or manually changed resources under control.
  • Restrict who can pass roles with a service role for CloudFormation and IAM conditions on cloudformation:RoleArn and template URL.

Debugging custom resources and Hooks

  1. Open the custom resource Lambda's CloudWatch Logs; the incoming event is the first thing to log.
  2. Confirm the function can reach the ResponseURL (a pre-signed S3 URL): functions in a VPC need NAT or an S3 gateway endpoint to respond, a frequent cause of hung stacks.
  3. For macros, view the processed template from the change set; errors appear as Transform ... failed with the Lambda message.
  4. Hook failures appear in stack events as HookStatusReason; the hook's invocation log is delivered to CloudWatch Logs.
  5. Prevent stuck stacks by setting a short ServiceTimeout and testing delete paths with a throwaway stack.

Pair CloudFormation with cdk-nag or Guard policies in the pipeline so non-compliant templates never reach the change set stage.

Real World Example

Scenario: a platform team must guarantee encrypted storage and standard tags in every stack. They publish a Guard hook in FAIL mode across all accounts through a StackSet, so any template that creates an unencrypted bucket is rejected at deploy time.

A Lambda-backed custom resource looks up the newest hardened AMI ID and another empties versioned buckets on stack delete, which removes the DELETE_FAILED tickets they used to receive. Pipelines run cfn-lint and cfn-guard before a change set is ever created.

Architecture Diagram

Template governance pipeline
Architecture
AWS Cloud
Templatecfn-lint + Guard
MacroTransform
Change setHooks PreCreate
Custom resourceResponseURL
Config / driftDetective

Validate early, expand predictably, block at provisioning and detect drift later.

  1. 1CI validates the template with cfn-lint and cfn-guard.
  2. 2The macro expands the template when the change set is created.
  3. 3Hooks evaluate each resource before provisioning and fail or warn.
  4. 4Custom resources invoke Lambda to do work CloudFormation cannot, then respond via the ResponseURL.
  5. 5Config rules and drift detection catch out-of-band changes afterwards.

Best Practices

  • ✓Wrap custom resource handlers in try/except that always responds, and set a short ServiceTimeout.
  • ✓Keep the PhysicalResourceId stable unless you really mean replacement.
  • ✓Prefer native resources, nested stacks and AWS::LanguageExtensions before writing a macro.
  • ✓Roll out Hooks in WARN mode first, then switch to FAIL.
  • ✓Combine preventive (hooks, SCPs) and detective (Config, drift) controls and enable termination protection on production stacks.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • "Run custom logic during stack create/delete" = Lambda-backed custom resource.
  • "Stack hangs on a custom resource" = the function did not respond to the ResponseURL.
  • "Block non-compliant resources before creation in CloudFormation" = CloudFormation Hook (Guard).
  • "Template-level reuse and rewriting" = macro/transform or nested stacks, not a custom resource.

Finished this lesson?

0 of 44 lessons done · 0% of the course