Lesson 3 of 5 AWS CloudFormation

Composing Templates with Nested Stacks, Exports, Modules, Macros and Hooks

Large environments cannot be described in a single template. CloudFormation offers several ways to divide templates, share values and reuse components, and to run checks before resources are provisioned. This lesson explains nested stacks, cross-stack references, modules, macros and transforms, the CloudFormation registry and hooks, and how to choose between them.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish between nested stacks and cross-stack references and explain the limits of exports.
  • Explain how CloudFormation modules package reusable resource configurations.
  • Describe macros and transforms, including AWS::Include and AWS::LanguageExtensions.
  • Explain how the CloudFormation registry and hooks extend and govern provisioning.

Nested Stacks

A nested stack is a stack created as a resource of another stack with the AWS::CloudFormation::Stack type, whose TemplateURL points to a template in S3. The parent passes parameters to the child, and the child's outputs are available to the parent through Fn::GetAtt ChildStack.Outputs.Name. The parent and all children form one hierarchy that is created, updated and deleted together, and an update to the root stack updates every changed child.

Nested stacks are suited to reusing common components, such as a standard load balancer configuration, within the same application, and to working around the per-stack resource quota. Because the hierarchy is deployed as a unit, nested stacks do not suit components with different owners or lifecycles. Updates must always start from the root stack, not the nested stacks directly.

Cross-Stack References

A stack can export an output value with an Export name, and another stack in the same account and Region can import it with Fn::ImportValue. This suits sharing values between independently managed stacks, such as a network stack owned by a platform team exporting VPC and subnet IDs to many application stacks.

Exports have constraints that appear in exam scenarios. Export names must be unique per account and Region. An exported value cannot be changed or deleted while any stack imports it, so the exporting stack's update fails until the importers stop using it, which tightly couples the stacks. Exports do not cross Regions or accounts. For values that must cross accounts or Regions, or that change often, writing them to Systems Manager Parameter Store and reading them with SSM parameter types or dynamic references provides looser coupling.

Nested stacks
RelationshipParent and children deployed as one unit
ScopeSame deployment
Changing a shared valueUpdate the root stack
Choose when Reusable components within one application's lifecycle.
Cross-stack references
RelationshipIndependent stacks; importer depends on exporter
ScopeSame account and Region
Changing a shared valueBlocked while imported
Choose when Stable values shared between stacks with different owners.
Parameter Store values
RelationshipIndependent stacks; no CloudFormation coupling
ScopeAny stack that can read the parameter
Changing a shared valueUpdate the parameter; consumers read it on their next update
Choose when Values shared loosely, across stacks or deployment tools.

CloudFormation Modules

A module packages a set of resources and their configuration as a reusable building block registered in the CloudFormation registry with a type name ending in ::MODULE, such as Acme::Storage::SecureBucket::MODULE. A template uses the module like a resource type and passes parameters; at deployment, CloudFormation expands the module into its resources in the same stack. Modules let a platform team encode best practices, for example a bucket with encryption, versioning, access logging and a TLS-only policy, so that application teams cannot forget a setting. Unlike nested stacks, module resources are part of the consuming stack, so there is no separate stack to manage. Modules can be shared with other accounts by registering them in each account, often through StackSets.

Macros and Transforms

A macro processes a template before CloudFormation deploys it. A transform declared in the template's Transform section processes the whole template, and Fn::Transform processes part of it. Custom macros are backed by Lambda functions that receive the template fragment and return a modified one, which allows custom shorthand syntax. Templates that use macros must be deployed with CAPABILITY_AUTO_EXPAND, usually through a change set so the expanded template can be reviewed.

AWS provides several transforms. AWS::Serverless-2016-10-31 is the AWS SAM transform. AWS::Include inserts a template snippet stored in S3. AWS::LanguageExtensions adds language features, including Fn::ForEach to generate repeated resources from a list, Fn::Length, Fn::ToJsonString and intrinsic functions in more places such as DeletionPolicy, which reduces repetition without custom macros.

Transform: AWS::LanguageExtensions
Parameters:
  QueueNames:
    Type: CommaDelimitedList
    Default: orders,payments,shipping
Resources:
  Fn::ForEach::Queues:
    - Name
    - !Ref QueueNames
    - "${Name}Queue":
        Type: AWS::SQS::Queue
        Properties:
          QueueName: !Sub "${Name}-${AWS::StackName}"

The Registry and Hooks

The CloudFormation registry lists the extensions available in an account and Region: AWS resource types, third-party public extensions that can be activated, and private extensions that an organisation registers itself. Private resource types let CloudFormation manage resources that have no native type, such as an external SaaS configuration, using handlers written with the CloudFormation CLI. Custom resources, described in the next lesson, are a simpler alternative for one-off logic.

Hooks are registry extensions that CloudFormation invokes before creating, updating or deleting resources, stacks or change sets. A hook inspects the proposed configuration and returns success or failure. In FAIL mode, a failure stops the operation; in WARN mode, it is reported but allowed. Hooks can be written with AWS CloudFormation Guard rules (Guard hooks), as Lambda functions (Lambda hooks) or as custom handlers, and AWS provides managed proactive controls through AWS Control Tower that are implemented as hooks. Hooks enforce standards for every stack in an account, regardless of who wrote the template, for example rejecting S3 buckets without encryption or security groups that allow SSH from anywhere.

Sort into groups

Choose the composition feature

Exam skills 2.1.4 · 2.1.1

Choose the CloudFormation feature for each reuse or governance requirement.

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

Structuring a Platform

A platform team provides a shared network, a secure bucket standard and a standard service layout to 30 application teams in many accounts. Application teams deploy independently, and a security rule requires that no stack may create an unencrypted bucket.

  1. Network

    A network stack per account writes VPC and subnet IDs to Parameter Store; application templates read them with SSM parameter types, avoiding export coupling.

  2. Bucket standard

    A SecureBucket module, registered in every account with StackSets, encapsulates encryption, versioning, logging and a TLS-only policy.

  3. Service layout

    Each application template uses nested stacks for its own load balancer and service components, deployed as one unit.

  4. Enforcement

    A Guard hook in FAIL mode rejects any AWS::S3::Bucket without server-side encryption, covering teams that do not use the module.

Check yourself

An update to a network stack fails because it changes an exported subnet ID that ten application stacks import. What are the options?

Show answer

Update the importing stacks to stop using the export first, then change the export; or redesign to share the value through Parameter Store, which does not block updates. CloudFormation never allows an imported export to change.

Exam Tips

Remember for the exam

  • Nested stacks reuse components within one deployment unit; update them through the root stack.
  • Exports are Region- and account-scoped, must be unique, and cannot change while imported; use Parameter Store for loosely coupled or cross-account values.
  • Modules (::MODULE types) expand into the consuming stack and encode standards for reuse.
  • Macros need CAPABILITY_AUTO_EXPAND; AWS::LanguageExtensions adds Fn::ForEach; AWS::Include inserts snippets from S3.
  • Hooks evaluate resources, stacks or change sets before provisioning and can block non-compliant changes (FAIL mode) for every stack in the account.