Prev Next

Cloud / AWS CloudFormation Interview questions

Last updated

1. What is AWS CloudFormation? 2. What is a CloudFormation template? 3. What are the sections of a CloudFormation template? 4. What is a CloudFormation stack? 5. What are parameters in CloudFormation? 6. What are resources in a CloudFormation template? 7. What are outputs in CloudFormation? 8. What is the purpose of the Mappings section? 9. What are the supported template formats in CloudFormation? 10. What is a StackSet? 11. Define intrinsic functions in CloudFormation? 12. What is the purpose of the Conditions section? 13. How do you create a CloudFormation stack? 14. What is drift detection in CloudFormation? 15. List common intrinsic functions used in CloudFormation? 16. What is the difference between CloudFormation and Terraform? 17. What is the difference between a nested stack and a StackSet? 18. Why do we use the DependsOn attribute? 19. How does CloudFormation handle rollback on failure? 20. What is the difference between an in-place Update and Replacement? 21. How do you pass values between stacks? 22. Why should you use change sets before updating a production stack? 23. What is the difference between CreationPolicy and UpdatePolicy? 24. When should you choose nested stacks over a single large template? 25. What is the difference between the Parameters and Mappings sections? 26. What happens when a CloudFormation stack update fails partway through? 27. How do you manage secrets in CloudFormation templates? 28. Why is DeletionPolicy important in CloudFormation? 29. How do you troubleshoot a CloudFormation stack that's stuck in progress? 30. How can you optimize CloudFormation templates for reusability? 31. What is a custom resource in CloudFormation? 32. What is the difference between Service-Managed and Self-Managed permissions in StackSets? 33. Explain the execution flow of a CloudFormation stack creation? 34. How do you troubleshoot a resource stuck in UPDATE_ROLLBACK_FAILED state? 35. Why doesn't CloudFormation delete an S3 bucket that still contains objects? 36. Explain the internal working of CloudFormation drift detection? 37. How does CloudFormation determine dependency order without explicit DependsOn? 38. Explain the lifecycle of a CloudFormation custom resource backed by Lambda? 39. How do you implement cross-account, cross-region deployment with StackSets? 40. Explain the internal working of rollback triggers based on CloudWatch alarms? 41. How do you handle circular dependencies in CloudFormation? 42. Explain how CloudFormation Hooks work? 43. How do you implement blue/green deployments using CloudFormation? 44. What are CloudFormation modules and how do they differ from nested stacks? 45. How does the CloudFormation Registry work for third-party resource types? 46. Explain the internal working of the resource provider framework (CRUDL model)? 47. How do you optimize CloudFormation templates that hit template size or resource count limits? 48. Explain how CloudFormation integrates with AWS Config for compliance and drift remediation? 49. Explain the execution flow of StackSets automatic deployment across an AWS Organization with drift detection enabled? 50. Explain the internal working of nested stack change propagation when a parent template updates?

1. What is AWS CloudFormation?

CloudFormation is AWS's native infrastructure-as-code service. Instead of clicking through the console or scripting individual API calls, you describe the resources you want in a JSON or YAML template, and CloudFormation figures out the order of operations needed to build them.

Every set of resources it creates from one template is called a stack, which becomes the single unit you use to update, monitor, or delete that infrastructure later. Because the whole environment is captured as versioned text, teams get repeatable, auditable deployments across accounts and regions without hand-maintained runbooks.

It integrates directly with IAM for permissions, CloudTrail for auditing changes, and CloudWatch for stack event monitoring, and there's no extra charge for using the service itself, you only pay for the resources it provisions.

Take quiz
CloudFormation primarily works by:
running ad-hoc AWS CLI scripts in sequence
declaring the desired resources in a template and letting CloudFormation build them
manually clicking through the console for every resource
compiling infrastructure into a binary
The collection of resources CloudFormation creates from one template is called a:
region
stack
fleet
organization

2. What is a CloudFormation template?

A template is the JSON or YAML file that lists exactly which AWS resources you want provisioned and how they should be configured. It's a static, declarative description; there's no sequence of imperative commands inside it, just resource definitions, their properties, and how they relate to each other.

Beyond resources, a template can define parameters for input values, mappings for static lookups, conditions for branching logic, and outputs for values you want to expose once the stack finishes. CloudFormation reads the whole file, resolves every reference and intrinsic function, and calculates a build plan from it.

Because the file is just text, the same template can be reused across dev, staging, and production by supplying different parameter values at deploy time, rather than maintaining separate copies per environment.

Take quiz
A CloudFormation template is best described as:
a declarative resource description
an imperative shell script
a compiled binary
a manual runbook
Reusing one template across environments is typically done by:
duplicating the whole file per environment
hardcoding environment values inside resources
supplying different parameter values at deploy time
editing resource names by hand each time

3. What are the sections of a CloudFormation template?

A template can contain up to nine top-level sections, though only Resources is mandatory; everything else is optional scaffolding around it.

Section Purpose
AWSTemplateFormatVersion Identifies the template's format version.
Description A short text note describing the template.
Metadata Extra data, such as console UI grouping hints.
Parameters Input values supplied at stack creation or update.
Mappings Static lookup tables, e.g. region-to-AMI maps.
Conditions Boolean logic that decides whether resources are created.
Transform Macros such as AWS::Serverless-2016-10-31 or Include.
Resources The actual AWS resources to provision (required).
Outputs Values exposed or exported once the stack completes.

Most day-to-day templates lean heavily on Parameters, Resources, and Outputs, while Mappings and Conditions tend to show up only once a template needs to behave differently depending on region or environment.

Take quiz
Which section is the only mandatory one in a template?
Outputs
Parameters
Resources
Metadata
Mappings are best suited for:
storing IAM policies
static lookup tables like region-to-AMI maps
running post-deploy scripts
holding secrets

4. What is a CloudFormation stack?

A stack is the live, deployed instance of a template: the actual collection of AWS resources CloudFormation created and now tracks together as one unit. Every resource in it is internally tagged with the stack's identity.

That grouping matters operationally: deleting the stack removes every resource it owns, unless a resource has a DeletionPolicy saying otherwise, and updating the stack reconciles the live resources to match a revised template rather than requiring you to touch each resource individually.

Stacks also carry their own lifecycle state, values like CREATE_COMPLETE, UPDATE_ROLLBACK_COMPLETE, or DELETE_FAILED, which tell you exactly where that reconciliation currently stands and whether it needs attention.

Take quiz
Deleting a stack will, by default:
leave all resources untouched
remove every resource it owns unless a DeletionPolicy says otherwise
only remove tags
pause all resources
A stack state like UPDATE_ROLLBACK_COMPLETE tells you:
the stack was deleted permanently
exactly where the reconciliation currently stands
that billing has stopped
that the template was invalid JSON

5. What are parameters in CloudFormation?

Parameters are the inputs a template accepts at stack creation or update time, letting one template produce different outcomes without editing its code, things like instance type, environment name, or a VPC ID.

Each parameter declares a Type, String, Number, or an AWS-specific type like AWS::EC2::KeyPair::KeyName, along with optional constraints such as AllowedValues, AllowedPattern, MinLength, or a Default value used when nothing is supplied.

Because parameters are resolved before any resource is built, they can be referenced anywhere in the template through Ref, but they can't themselves depend on another resource's output; that kind of conditional logic belongs in Mappings or Conditions instead.

Take quiz
Parameters let a single template:
run in only one AWS account forever
produce different outcomes without editing the template code
skip the Resources section entirely
replace the need for IAM
A parameter's AllowedValues constraint is used to:
restrict input to a specific set of valid choices
encrypt the parameter automatically
set a default region
define resource dependencies

6. What are resources in a CloudFormation template?

Resources are the actual AWS objects you want provisioned, each declared with a logical ID you choose, an AWS resource Type like AWS::S3::Bucket or AWS::EC2::Instance, and a Properties block that configures it.

The Resources section is the only mandatory part of a template because a template with no resources has nothing to deploy. CloudFormation reads each Type to know which underlying service API to call, and fills that API's fields from Properties.

The logical ID isn't the resource's real AWS name, it's a template-local handle you use to reference that resource elsewhere via Ref or Fn::GetAtt, so other resources can point to it without knowing its physical ID in advance.

Take quiz
A resource's logical ID is used to:
set its billing tier
reference it elsewhere in the template via Ref or GetAtt
define its IAM role automatically
determine deployment region
Which section is required for a valid template because it holds what gets deployed?
Outputs
Parameters
Resources
Mappings

7. What are outputs in CloudFormation?

Outputs expose values from a stack once it finishes creating or updating, things like a load balancer's DNS name, an S3 bucket ARN, or a VPC ID that other people or systems need to reference.

Each output can optionally include an Export block with a Name, which makes that value importable by other stacks in the same account and region through Fn::ImportValue, enabling clean cross-stack references without hardcoding values.

Outputs only flow outward; you can't feed an output's value back into a resource inside that same stack. If a value needs to be reused internally, reference the resource directly instead.

Take quiz
An Output with an Export can be consumed by another stack using:
Fn::GetAtt
Fn::ImportValue
Ref
Fn::FindInMap
Outputs are best described as:
inputs collected before stack creation
values exposed after a stack finishes creating or updating
a place to store secrets
a required section in every template

8. What is the purpose of the Mappings section?

Mappings hold static, hardcoded lookup tables indexed by keys you control, most commonly a region name mapping to the correct AMI ID, so one template can behave correctly across regions without a pile of conditionals.

You retrieve a value with Fn::FindInMap, passing the map name, a top-level key, and a second-level key, for example looking up the AMI for "us-east-1" under a map named "RegionAMI".

Unlike Parameters, Mappings can't be overridden when you deploy; the values are baked into the template itself, which makes them the right tool for facts that are fixed about the AWS environment rather than choices the deployer should make.

Take quiz
A common use of Mappings is:
storing secrets securely
mapping regions to the correct AMI ID
defining IAM roles
holding user passwords
Mappings values are retrieved using:
Ref
Fn::ImportValue
Fn::FindInMap
Fn::GetAtt

9. What are the supported template formats in CloudFormation?

CloudFormation accepts templates written in either JSON or YAML, and both are functionally equivalent; the parser builds the same internal object model from either one.

YAML tends to be preferred for day-to-day authoring because it supports comments, is less noisy with brackets and quotes, and offers short-form intrinsic function syntax, !Ref and !GetAtt, instead of the longer Fn:: prefixed equivalents used in JSON.

JSON remains common for templates generated programmatically, for example by the AWS CDK or other tooling that emits structured output, since it's simpler for a program to produce reliably than hand-formatted YAML.

Take quiz
CloudFormation templates can be written in:
only JSON
only YAML
either JSON or YAML
XML
YAML's short-form function syntax, like !Ref, is:
invalid in CloudFormation
only usable in JSON templates
a shorthand for the longer Fn:: prefixed form
unrelated to intrinsic functions

10. What is a StackSet?

A StackSet lets you deploy the same CloudFormation template as consistent stacks across multiple AWS accounts and regions from one central place, instead of manually creating and syncing a stack in every account by hand.

Each deployed copy is called a stack instance, and StackSets track them individually while letting you push a single update out to all of them at once, governed by settings like max concurrent accounts and failure tolerance percentage.

This makes StackSets the standard tool for centrally managed, multi-account infrastructure: things like security guardrails, logging baselines, or IAM roles that every account in an organization needs consistently.

Take quiz
A StackSet is used to:
deploy one template as consistent stacks across many accounts/regions
nest one stack inside another
store secrets centrally
replace the Resources section
Each deployed copy managed by a StackSet is called a:
nested stack
stack instance
template fragment
stack export

11. Define intrinsic functions in CloudFormation?

Intrinsic functions are built-in template functions that compute values dynamically instead of requiring you to hardcode them: things like Ref to resolve a parameter or resource, Fn::GetAtt to read a resource's attribute, Fn::Join, Fn::Sub, Fn::FindInMap, and Fn::ImportValue.

They only work inside a CloudFormation template; they aren't a general-purpose scripting language, and they get resolved when CloudFormation processes the template, not beforehand.

YAML templates offer shorthand forms for the most common ones, !Ref and !Sub, in place of the longer Fn:: prefixed JSON syntax, which is one reason YAML templates tend to read more cleanly.

Take quiz
Intrinsic functions are resolved:
by a separate scripting engine outside CloudFormation
when CloudFormation processes the template
only after the stack is deleted
in the AWS billing console
Which is an example of an intrinsic function?
DependsOn
Fn::GetAtt
DeletionPolicy
CapabilityIAM

12. What is the purpose of the Conditions section?

Conditions define boolean expressions, usually built from Fn::Equals, Fn::And, Fn::Or, and Fn::Not, that you attach to a resource's Condition attribute to decide whether that resource gets created at all.

The same condition can also be used with Fn::If inside a property value to pick between two possible values, rather than controlling whole-resource creation.

This lets one template branch its behavior, for example creating a production-only CloudWatch alarm, or choosing a larger instance type when an "IsProd" parameter evaluates true, without maintaining a separate template per environment.

Take quiz
A Condition attached to a resource controls:
its billing tier
whether that resource gets created at all
its logical ID
its region
Fn::If inside a property value is used to:
delete a resource
pick between two possible values
import a value from another stack
define a parameter's default

13. How do you create a CloudFormation stack?

Creating a stack is a short, repeatable sequence whether you use the console, CLI, or an SDK.

  1. Author or obtain a template and validate its syntax.
  2. Decide on parameter values and check whether the template creates IAM resources, which requires acknowledging a capability like CAPABILITY_IAM or CAPABILITY_NAMED_IAM.
  3. Submit the create request, for example aws cloudformation create-stack --stack-name my-stack --template-body file://template.yaml --capabilities CAPABILITY_IAM.
  4. CloudFormation resolves the dependency graph and calls each underlying service's API in the right order.
  5. Monitor stack events until it reaches CREATE_COMPLETE, or investigate the failure reason if it rolls back.
Take quiz
Templates that create IAM resources typically require acknowledging:
a CAPABILITY_IAM or similar capability flag
a billing alert
a StackSet policy
a DeletionPolicy
The correct end state after a successful stack creation is:
ROLLBACK_COMPLETE
CREATE_COMPLETE
DELETE_COMPLETE
UPDATE_IN_PROGRESS

14. What is drift detection in CloudFormation?

Drift detection compares the live, current configuration of a stack's resources against what the template says they should be, flagging anything that was manually changed outside of CloudFormation, like a security group rule edited directly in the console.

Running it returns a per-resource drift status: IN_SYNC, MODIFIED, DELETED, or NOT_CHECKED for resource types that don't support drift detection yet, along with a property-level diff showing exactly what differs.

It's a detection tool only, it reports drift, it doesn't automatically fix it. Remediation still means either updating the template to match the live change or reverting the manual change back to what the template expects.

Take quiz
A resource manually edited outside CloudFormation will typically show a drift status of:
IN_SYNC
MODIFIED
DELETED
NOT_CHECKED
Drift detection will:
automatically revert manual changes
only report drift, not fix it
delete drifted resources
block all future updates

15. List common intrinsic functions used in CloudFormation?

Beyond Ref and Fn::GetAtt, a handful of other intrinsic functions come up constantly in real templates.

Function Purpose
Ref Returns a parameter's value or a resource's primary identifier.
Fn::GetAtt Reads a specific attribute of a resource, like an ARN.
Fn::Sub Substitutes variables into a string template.
Fn::Join Concatenates a list of values with a delimiter.
Fn::FindInMap Looks up a value from the Mappings section.
Fn::ImportValue Imports a value exported by another stack's Output.
Fn::If Chooses between two values based on a Condition.
Fn::Select Picks a single item out of a list by index.

In practice, Fn::Sub tends to replace a lot of older Fn::Join usage because it reads closer to a plain string with placeholders, which makes templates easier to review.

Take quiz
Fn::Select is used to:
join strings with a delimiter
pick a single item from a list by index
import a cross-stack value
define a condition
Fn::Sub is often preferred over Fn::Join because:
it's the only function that works in JSON
it reads closer to a plain string with placeholders
it doesn't require any arguments
it replaces the Resources section

16. What is the difference between CloudFormation and Terraform?

Both are declarative infrastructure-as-code tools, but they differ in scope and state handling.

CloudFormation Terraform
AWS-native, free to use. Multi-cloud, works across AWS, Azure, GCP, and more.
State is managed by AWS itself, no state file to protect. State is tracked in a file you must store and lock yourself, or via Terraform Cloud.
Written in JSON or YAML. Written in HCL, a purpose-built configuration language.
Deep, immediate support for new AWS features on launch day. Provider updates can lag a service's initial AWS launch.

Teams standardized entirely on AWS often prefer CloudFormation for its tight IAM integration and zero extra tooling, while multi-cloud shops or teams wanting a larger community module ecosystem often reach for Terraform instead.

Take quiz
A key operational difference is that Terraform:
has no concept of state at all
requires you to manage a state file yourself
is AWS-only
cannot be version controlled
CloudFormation's main advantage for AWS-only shops is:
multi-cloud support
native, tight integration with IAM without extra tooling
a purpose-built configuration language called HCL
faster provider updates than AWS's own services

17. What is the difference between a nested stack and a StackSet?

A nested stack is a stack created and managed inside another parent stack, declared as a resource of type AWS::CloudFormation::Stack. It's used to break one large template into smaller, reusable pieces within a single deployment: one account, one region.

A StackSet, by contrast, deploys the same template as independent stacks across many accounts and regions. Those stack instances are peers managed centrally, not nested inside one another, and none of them has a parent-child relationship with the others.

In short, nested stacks solve template size and reuse within one deployment, while StackSets solve replicating one deployment consistently across a fleet of accounts.

Take quiz
A nested stack is declared using resource type:
AWS::CloudFormation::StackSet
AWS::CloudFormation::Stack
AWS::CloudFormation::Module
AWS::CloudFormation::Macro
Stack instances created by a StackSet are best described as:
children nested inside a single parent stack
peers deployed independently across accounts and regions
temporary and auto-deleted after 24 hours
only usable within one account

18. Why do we use the DependsOn attribute?

CloudFormation normally infers resource creation order automatically by reading Ref and Fn::GetAtt references inside a template, building an implicit dependency graph without you specifying anything.

DependsOn exists for the cases that graph can't see: when one resource must exist before another for a reason that isn't expressed through a property reference. A classic example is an EC2 instance that needs a VPC's internet gateway attached first, even though the instance's own properties never literally reference that gateway.

Without DependsOn in that situation, CloudFormation might try to create both resources in parallel, and the deployment could fail intermittently depending on timing rather than failing, or succeeding, consistently.

Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    DependsOn: GatewayAttachment

Take quiz
DependsOn is needed when:
CloudFormation's automatic Ref-based ordering already covers the dependency
a required order isn't expressed through any property reference
a resource has no properties at all
you want to delete a stack faster
Without a needed DependsOn, CloudFormation might:
always fail immediately with a clear error
try to create both resources in parallel, causing an intermittent failure
refuse to parse the template
automatically add it for you

19. How does CloudFormation handle rollback on failure?

By default, if any resource fails during stack creation, CloudFormation automatically rolls back by deleting every resource it already created in that same operation, rather than leaving a half-built stack sitting around. The stack ends in ROLLBACK_COMPLETE.

For updates, a failure triggers UPDATE_ROLLBACK_IN_PROGRESS, reverting changed resources back to their prior configuration, ending in UPDATE_ROLLBACK_COMPLETE if that reversal succeeds.

You can disable this behavior for debugging with --disable-rollback or --on-failure DO_NOTHING during create, which leaves the partially built resources in place so you can inspect the actual error before cleaning up manually.

Rollback triggers, based on CloudWatch alarms, add another layer: they can proactively cancel an update mid-flight if application health degrades, even when every individual resource technically finished successfully.

Take quiz
By default, a failed stack creation results in:
a half-built stack left for manual cleanup
automatic deletion of everything created in that operation
an immediate account suspension
a silent retry loop
Disabling rollback during creation is useful for:
production best practice
inspecting the actual error before manual cleanup
speeding up successful deployments
avoiding IAM capability checks

20. What is the difference between an in-place Update and Replacement?

When you change a resource's property, CloudFormation checks that specific property's documented update behavior for its resource type. Some properties support an in-place update, where AWS calls a modify API on the existing resource with no change to its identity.

Others are marked as requiring Replacement, meaning the only way to apply that change is to create a brand-new resource with the new configuration, then delete the old one, which usually means a new physical ID and potential downtime or data loss.

For example, changing an RDS instance's engine version is typically an in-place update, but changing its DBInstanceIdentifier forces a replacement. Change sets are the tool for previewing which behavior a given update will trigger before you commit to it.

Take quiz
A property marked Replacement means:
the update happens with zero risk of downtime
AWS must create a new resource and delete the old one
the change is rejected outright
the stack is deleted entirely
The recommended way to preview whether an update will replace a resource is:
deploying directly to production first
reading CloudTrail logs after the fact
using a change set
disabling rollback

21. How do you pass values between stacks?

The standard mechanism is an Output with an Export in the producing stack, then Fn::ImportValue in the consuming stack referencing that export's name. CloudFormation prevents you from deleting or modifying an exported output while any other stack still imports it, which protects against silently breaking a dependent stack.

A looser-coupled alternative is writing the value to SSM Parameter Store from one stack and reading it in another with a parameter of type AWS::SSM::Parameter::Value<String>. That avoids the hard delete-protection lock Exports impose, but requires the parameter to already exist before the consuming stack runs.

Choosing between them usually comes down to coupling: Exports are tightly coupled but safer against silent breakage, SSM parameters are flexible but require careful sequencing.

Take quiz
Fn::ImportValue is used together with an Export to:
delete a stack safely
pass a value from one stack to another
define a Condition
validate a template's syntax
CloudFormation prevents you from removing an Export while:
the exporting stack is still CREATE_IN_PROGRESS
another stack still imports it
the template uses YAML instead of JSON
a StackSet references it

22. Why should you use change sets before updating a production stack?

A change set is a preview: you submit a proposed template or parameter update, and CloudFormation calculates exactly what it would do, without touching anything yet, listing each resource as Modify, Add, Remove, and critically, whether a modification would be an in-place update or a full Replacement.

On a production stack, that Replacement flag is the detail people most often miss when reading a diff by eye; a seemingly small property change can silently force a resource to be destroyed and recreated, which for something like an RDS instance means real downtime or data loss if you're not expecting it.

Reviewing the change set with a second engineer before executing it turns an update from a leap of faith into a reviewed, approved action, and it costs nothing extra to generate one.

Take quiz
A change set primarily helps by:
automatically fixing template errors
previewing exactly what an update would do before executing it
reducing AWS billing
replacing the need for IAM permissions
The detail engineers most often miss when eyeballing a template diff is:
parameter default values
whether a change forces Replacement instead of an in-place update
the template's file size
the AWSTemplateFormatVersion

23. What is the difference between CreationPolicy and UpdatePolicy?

CreationPolicy pauses a resource's creation status until a success signal arrives, most commonly used with an Auto Scaling group or EC2 instance where you want CloudFormation to wait until cfn-signal confirms the instance actually finished bootstrapping, not just that the API call to launch it returned.

UpdatePolicy governs how an existing resource, typically an Auto Scaling group, is updated, controlling behaviors like rolling updates, batch size, and pause time between batches so a fleet update doesn't take every instance down simultaneously.

The distinction is timing: CreationPolicy gates whether creation is considered successful in the first place, while UpdatePolicy shapes how a later update rolls out across an already-running resource.

Take quiz
CreationPolicy is used to:
control rolling update batch size
wait for a success signal before considering creation complete
import values from another stack
define IAM permissions
UpdatePolicy most commonly governs updates to:
S3 buckets
an Auto Scaling group's rolling update behavior
IAM roles
Route 53 records

24. When should you choose nested stacks over a single large template?

Nested stacks make sense once a single template becomes hard to review or hits practical limits; CloudFormation templates cap resource count and body size, and a monolithic template covering networking, compute, and data layers together tends to become unreviewable long before it hits those hard limits.

Splitting by logical boundary, a networking nested stack, an application nested stack, a database nested stack, lets each piece be owned, tested, and updated somewhat independently, while still deploying as one coordinated unit through the parent.

The tradeoff is added complexity: passing values between nested stacks means threading Parameters down and Outputs back up through the parent, and a change to a shared nested stack can trigger updates to everything that depends on it, so it's not free modularity, it's a genuine architectural decision.

Take quiz
Nested stacks are most useful when:
a template is small and simple
a template becomes hard to review or approaches size/resource limits
you need multi-account deployment
you want to avoid using Parameters
A tradeoff of splitting into nested stacks is:
values must be threaded through Parameters and Outputs between them
IAM is no longer needed
stacks can no longer be deleted
templates must be written in JSON only

25. What is the difference between the Parameters and Mappings sections?

Parameters are values supplied by whoever deploys the stack, at creation or update time, meant for choices the deployer should control: environment name, instance size, a VPC ID.

Mappings are static values baked directly into the template by whoever wrote it, meant for facts about the AWS environment that don't change per deployment but do vary by some fixed key, most commonly region.

A useful test: if the value should differ because someone typed something different at deploy time, it belongs in Parameters; if it should differ only because of a fixed fact like which region the stack runs in, it belongs in Mappings.

Take quiz
Parameters are supplied:
by the template author only, baked in permanently
by whoever deploys the stack, at deploy time
only through Mappings
through the Outputs section
A region-to-AMI lookup that never changes at deploy time belongs in:
Parameters
Outputs
Mappings
Conditions

26. What happens when a CloudFormation stack update fails partway through?

CloudFormation enters UPDATE_ROLLBACK_IN_PROGRESS and attempts to revert every resource it had already started changing back to its previous, working configuration, using the same dependency graph it used to apply the update in the first place, just in reverse.

If that reversal succeeds, the stack lands in UPDATE_ROLLBACK_COMPLETE, effectively as if the failed update never happened from the outside. If the rollback itself hits an error, the stack can get stuck in UPDATE_ROLLBACK_FAILED, which requires manual intervention, either fixing the underlying issue and continuing the rollback, or in stubborn cases, using the ContinueUpdateRollback API with resources explicitly skipped.

Because a failed rollback is the messier of the two outcomes, it's worth investigating the CloudFormation stack events immediately to see the specific resource and reason before attempting any remediation.

Take quiz
A successful rollback after a failed update lands the stack in:
DELETE_COMPLETE
UPDATE_ROLLBACK_COMPLETE
CREATE_COMPLETE
UPDATE_ROLLBACK_FAILED
If the rollback itself fails, the stack can get stuck in:
UPDATE_COMPLETE
UPDATE_ROLLBACK_FAILED
ROLLBACK_IN_PROGRESS
CREATE_FAILED

27. How do you manage secrets in CloudFormation templates?

Secrets should never be hardcoded as plain Parameters or Resource properties, since template bodies and parameter values can show up in CloudTrail events and stack descriptions. The standard approach is storing the secret in AWS Secrets Manager or SSM Parameter Store ahead of time, then referencing it dynamically from the template.

For SSM, a parameter of type AWS::SSM::Parameter::Value<String> (or the SecureString variant via a dynamic reference) pulls the value in at deploy time. For Secrets Manager, a dynamic reference like {{resolve:secretsmanager:MySecret:SecretString:password}} resolves the secret without it ever appearing in plain text in the template or its parameters.

Combined with resource-level IAM policies limiting who can read the underlying secret, this keeps the sensitive value out of the template, the stack's parameter history, and version control entirely.

Take quiz
Dynamic references like {{resolve:secretsmanager:...}} are used to:
hardcode secrets directly into a template
pull a secret's value in at deploy time without exposing it in plain text
disable IAM for that resource
replace the Parameters section
A key risk of putting a secret directly in a Parameter's default value is:
it improves performance
it can appear in stack descriptions and parameter history
it automatically encrypts the secret
it prevents stack deletion

28. Why is DeletionPolicy important in CloudFormation?

By default, deleting a stack deletes every resource it created, which is convenient for throwaway environments but dangerous for anything holding state you can't easily recreate, like a production database or an S3 bucket full of customer data.

DeletionPolicy overrides that default per resource: Retain leaves the resource in place, orphaned from the stack, when the stack is deleted; Snapshot takes a final snapshot before deletion, supported for resources like RDS instances and EBS volumes; Delete is the implicit default.

Setting Retain or Snapshot on stateful resources is one of the simplest, cheapest safeguards available against an accidental delete-stack call wiping out data that took months to accumulate.

Take quiz
DeletionPolicy: Retain means:
the resource is deleted along with the stack
the resource is left in place, orphaned from the deleted stack
a snapshot is taken automatically
the stack cannot be deleted at all
DeletionPolicy: Snapshot is commonly applied to:
IAM roles
RDS instances and EBS volumes
Route 53 hosted zones
CloudFormation StackSets

29. How do you troubleshoot a CloudFormation stack that's stuck in progress?

A stack stuck in *_IN_PROGRESS for far longer than expected usually points to one specific resource, not the whole stack, so the goal is isolating which one.

  1. Open the stack's Events tab and read chronologically; the last resource to start without a completed status is almost always the blocker.
  2. Check whether that resource type has a CreationPolicy or WaitCondition expecting a signal, e.g. cfn-signal, that never arrived, which is a common cause of a stack that just sits without erroring.
  3. Cross-check the underlying service's own console or logs for that resource; CloudFormation sometimes just relays a generic wait state while the real issue is visible in, say, an EC2 instance's system log.
  4. If it's genuinely hung with no progress, CloudFormation eventually times out that resource and rolls back on its own; you generally shouldn't force-cancel unless you understand exactly what state that leaves behind.
Take quiz
The best first step when a stack seems stuck is:
immediately deleting the stack
reading the stack's Events tab chronologically
disabling rollback
changing the template's format from YAML to JSON
A stack that sits without erroring is often caused by:
a missing AWSTemplateFormatVersion
a CreationPolicy or WaitCondition waiting for a signal that never arrived
too many Outputs
an unused Mappings section

30. How can you optimize CloudFormation templates for reusability?

Reusability mostly comes down to pulling repeated patterns out of individual templates and into shared building blocks rather than copy-pasting resource blocks across projects.

  • Nested stacks or CloudFormation modules for common resource groupings, like a standard VPC layout, used across many projects.
  • Parameters with sensible Defaults and AllowedValues so a template is safe to reuse without every consumer needing to understand every knob.
  • Mappings for environment-specific facts, so branching logic doesn't need to be duplicated per template.
  • Consistent naming conventions for logical IDs and exported Output names, so cross-stack references stay predictable as templates multiply.

The underlying discipline is treating templates like shared code: version them, review changes to shared nested stacks carefully since many consumers depend on them, and avoid one-off exceptions that make a "reusable" template secretly project-specific.

Take quiz
A key building block for reusable resource groupings is:
Metadata
nested stacks or CloudFormation modules
the Description section
AWSTemplateFormatVersion
Treating templates like shared code mainly means:
never updating them once written
versioning them and reviewing changes carefully
avoiding Parameters entirely
hardcoding every value

31. What is a custom resource in CloudFormation?

A custom resource lets CloudFormation manage something that has no native resource type, by delegating the actual create, update, and delete logic to your own code, typically a Lambda function, instead of a built-in AWS API call.

You declare it as AWS::CloudFormation::CustomResource (or the shorthand Custom::YourName), pointing at a ServiceToken, usually a Lambda ARN. CloudFormation sends that function a request describing the lifecycle event, Create, Update, or Delete, along with any properties you defined, and waits for a response signaling success or failure before continuing the stack operation.

Common uses include looking up a value from a third-party API, generating a random value at deploy time, or performing cleanup steps AWS itself has no native resource for, like emptying an S3 bucket before it's deleted.

Take quiz
A custom resource delegates its create/update/delete logic to:
a built-in AWS API only
your own code, typically a Lambda function
the AWS Config service
IAM policy documents
A custom resource is commonly used to:
replace the Resources section entirely
perform logic AWS has no native resource for, like emptying a bucket before deletion
disable rollback
import values from Mappings

32. What is the difference between Service-Managed and Self-Managed permissions in StackSets?

Self-Managed permissions require you to manually create two IAM roles yourself, an administration role in the account running the StackSet and an execution role in every target account, and manage the trust relationship between them by hand.

Service-Managed permissions instead rely on AWS Organizations integration: CloudFormation creates and manages the necessary roles automatically, and you can target deployment by Organizational Unit rather than listing individual account IDs, with new accounts added to that OU picking up the StackSet automatically.

Service-Managed is generally the better fit for organizations already using AWS Organizations, since it removes the manual role bookkeeping and scales cleanly as accounts are added or removed; Self-Managed remains relevant for accounts outside an Organization or with custom cross-account IAM setups already in place.

Take quiz
Service-Managed permissions rely on integration with:
AWS Config
AWS Organizations
Amazon GuardDuty
AWS Systems Manager
Self-Managed permissions require you to:
do nothing, AWS handles everything automatically
manually create and trust admin/execution IAM roles yourself
use only a single AWS account
avoid Organizational Units entirely

33. Explain the execution flow of a CloudFormation stack creation?

Stack creation moves through a consistent sequence regardless of how many resources are involved.

flowchart TD
A["Submit template and parameters"] --> B["CloudFormation validates syntax"]
B --> C["Build dependency graph from Refs, GetAtt, DependsOn"]
C --> D["Call each service API in dependency order"]
D --> E{All resources succeed?}
E -- Yes --> F["Stack reaches CREATE_COMPLETE"]
E -- No --> G["Automatic rollback deletes created resources"]
G --> H["Stack reaches ROLLBACK_COMPLETE"]

The key detail is that step C, building the dependency graph, happens entirely before any API calls fire, so CloudFormation already knows the full creation order upfront rather than discovering it reactively as resources succeed or fail.

Independent resources within that graph, ones with no dependency on each other, are created in parallel, which is part of why CloudFormation can deploy faster than a purely sequential script would for a template with many unrelated resources.

Take quiz
CloudFormation builds its dependency graph:
reactively, as each resource succeeds or fails
entirely before any API calls fire
only after a failure occurs
only when DependsOn is used
Resources with no dependency on each other are created:
always sequentially, one at a time
in parallel
in random, unpredictable order with no logic
only during updates, never during creation

34. How do you troubleshoot a resource stuck in UPDATE_ROLLBACK_FAILED state?

UPDATE_ROLLBACK_FAILED means CloudFormation tried to revert a failed update and hit an error partway through the rollback itself, leaving the stack in a state where it won't accept normal updates until resolved.

  1. Check the stack events to find the specific resource the rollback failed on and the reported reason, often a permissions issue or a resource that changed outside CloudFormation mid-update.
  2. If the underlying issue is fixable, for example a missing IAM permission the rollback needed, fix it directly, then call ContinueUpdateRollback to resume.
  3. If the resource genuinely can't be rolled back, for instance it was deleted manually, call ContinueUpdateRollback with that resource's logical ID listed in ResourcesToSkip, which tells CloudFormation to treat it as already handled and continue rolling back everything else.
  4. Once the stack reaches UPDATE_ROLLBACK_COMPLETE, verify the skipped resource's actual state manually, since CloudFormation's view of it may now be out of sync with reality.
Take quiz
The API used to resume a failed rollback is:
ContinueUpdateRollback
RetryStackUpdate
ResumeStack
ForceRollback
A resource that can't be rolled back can be handled by:
deleting the entire stack immediately
listing it in ResourcesToSkip when calling ContinueUpdateRollback
ignoring the stack permanently
switching the template to JSON

35. Why doesn't CloudFormation delete an S3 bucket that still contains objects?

CloudFormation's delete operation for an S3 bucket calls the underlying DeleteBucket API, and S3 itself refuses to delete a bucket that still has objects in it. That's an S3 safety rule, not a CloudFormation-specific one, so the stack deletion for that resource fails and the whole stack can end up in DELETE_FAILED.

To make a bucket genuinely deletable through CloudFormation, you either need to empty it beforehand, manually, through a lifecycle rule, or via a custom resource backed by Lambda that empties it during the Delete event, or you accept DeletionPolicy: Retain and empty the orphaned bucket separately afterward.

Some teams solve this permanently with a small custom resource pattern that always empties a bucket as part of stack deletion, so no manual step is needed even for one-off environments.

Take quiz
The reason CloudFormation can't delete a non-empty S3 bucket is:
a CloudFormation-specific bug
S3's own DeleteBucket API refuses non-empty buckets
IAM permissions are always missing
the bucket must be renamed first
A common pattern to handle this automatically is:
setting DeletionPolicy: Snapshot on the bucket
a custom resource that empties the bucket during the Delete event
disabling the Resources section
using Fn::ImportValue

36. Explain the internal working of CloudFormation drift detection?

When you trigger drift detection, CloudFormation doesn't compare against its own historical record of what it last set; it calls each resource's current-state read API directly against the live AWS service, the same kind of describe/get call you'd make yourself, then compares that fresh snapshot against the resource's expected configuration as computed from the template plus resolved parameters and intrinsic functions.

For each property CloudFormation is capable of checking (support varies by resource type; not every property of every type is drift-checkable), it produces an EXPECTED value and an ACTUAL value; any mismatch marks that property, and the resource overall, as MODIFIED. A resource that no longer exists at all is reported DELETED.

Because it's a live read against the actual service, detection at the stack level runs a check per resource and can take noticeably longer for stacks with many resources; that's also why some resource types return NOT_CHECKED, AWS hasn't implemented a comparable state-read capability for every single resource type across every service yet.

Take quiz
Drift detection compares live resource state against:
a cached copy from the last deployment only
the expected configuration computed from the template, parameters, and intrinsic functions
a snapshot taken a year prior
nothing, it only checks tags
Some resources return NOT_CHECKED because:
they were deleted
AWS hasn't implemented comparable state-read support for that resource type yet
the stack has too many parameters
drift detection is disabled by default

37. How does CloudFormation determine dependency order without explicit DependsOn?

CloudFormation parses every resource's Properties block looking for Ref and Fn::GetAtt calls that point at other logical resource IDs within the same template. Each one of those references becomes an edge in an implicit directed graph: if ResourceB's properties contain Ref: ResourceA, then A must be created (or already exist) before B.

Once the full graph is built across every resource, CloudFormation performs a topological sort to produce a valid creation order, one where every resource appears after everything it depends on. Where the graph allows multiple valid orderings, independent branches, it can execute those branches concurrently rather than picking one arbitrary linear sequence.

This inference only sees references CloudFormation itself can parse in the template; it cannot detect an ordering requirement that exists purely at the AWS API level with no corresponding Ref or GetAtt in the template, which is exactly the gap DependsOn is designed to fill manually.

Take quiz
The implicit dependency graph is built primarily from:
comments in the template
Ref and Fn::GetAtt references between resources
the order resources are listed in the file
the Description section
CloudFormation uses this graph to compute order via:
random shuffling
a topological sort
alphabetical sorting of logical IDs
reverse file order

38. Explain the lifecycle of a CloudFormation custom resource backed by Lambda?

A custom resource's lifecycle is really a request/response protocol between CloudFormation and your Lambda function, mediated through a pre-signed S3 URL rather than a direct return value.

sequenceDiagram
participant CFN as CloudFormation
participant L as Lambda Function
participant S3 as Response S3 URL
CFN->>L: Invoke with RequestType (Create/Update/Delete) plus ResourceProperties
L->>L: Execute custom logic
L->>S3: PUT response JSON (Status, Data, PhysicalResourceId)
CFN->>S3: Poll and read response
CFN->>CFN: Continue stack operation based on status

On Create, the function runs its logic and returns a PhysicalResourceId it invents, which CloudFormation then remembers and passes back on every subsequent Update or Delete invocation for that same resource, so the function knows which underlying thing it's operating on.

Critically, if the function doesn't respond within the configured timeout (or fails to signal at all), CloudFormation eventually times out waiting and treats it as a failure, triggering rollback, which is why production custom resources almost always wrap the handler in a try/except that guarantees a FAILED response gets sent rather than letting the Lambda's own timeout silently strand the stack.

Take quiz
The response from a custom resource's Lambda is delivered via:
a direct Lambda return value read by CloudFormation
a PUT to a pre-signed S3 response URL
an SNS topic only
a DynamoDB table
If a custom resource's Lambda never responds, CloudFormation:
completes the stack anyway
eventually times out and treats it as a failure, triggering rollback
retries indefinitely with no timeout
deletes the Lambda function

39. How do you implement cross-account, cross-region deployment with StackSets?

Cross-account, cross-region deployment starts with choosing a permission model, Service-Managed if the target accounts are inside an AWS Organization, Self-Managed if not, since that decision shapes how the administration and execution roles get set up.

  1. Create the StackSet in the management (or a delegated administrator) account, pointing at the template.
  2. Define deployment targets: specific account IDs or, with Service-Managed, entire Organizational Units, plus the list of target regions.
  3. Configure deployment operation preferences: max concurrent accounts/percentage, failure tolerance, and region concurrency (sequential or parallel), which control blast radius if something goes wrong partway through the rollout.
  4. CloudFormation creates one stack instance per account/region combination, each an independent stack that can be inspected individually even though it was launched centrally.
  5. Optionally enable automatic deployment so new accounts added to a targeted OU pick up the StackSet without any manual step.

Because each instance is a real independent stack, drift detection, individual stack events, and per-instance troubleshooting all still work exactly as they would for a manually created stack.

Take quiz
Failure tolerance and max concurrent accounts settings primarily control:
billing alerts
the blast radius if a rollout fails partway through
which template format is used
IAM policy syntax
With automatic deployment enabled on an OU-targeted StackSet:
new accounts must be added manually every time
new accounts added to that OU pick up the StackSet automatically
only the management account receives updates
drift detection is disabled

40. Explain the internal working of rollback triggers based on CloudWatch alarms?

Rollback triggers let you attach one or more existing CloudWatch alarms to a stack update operation; unlike CloudFormation's default rollback, which only reacts to a resource's own creation/update API call failing, rollback triggers react to application-level health signals you define, error rate, latency, custom metrics, that a resource can report as "succeeded" from the API's perspective while actually being unhealthy.

During the monitoring period you configure, CloudFormation watches the specified alarms' state. If any of them transitions to ALARM within that window, CloudFormation treats the entire update as failed, even though every individual resource technically finished its own creation or modification successfully, and begins the standard automatic rollback for the update.

If the monitoring period elapses with no alarm firing, the update is considered successful and finalized normally. This makes rollback triggers a way to gate a deployment on real, observed application behavior rather than purely on whether the AWS API calls themselves returned success.

Take quiz
Rollback triggers react to:
only resource-level API call failures
CloudWatch alarms reflecting application health, even if resources succeeded individually
billing thresholds
IAM permission errors only
If the monitoring period ends with no alarm firing:
the stack rolls back automatically anyway
the update is considered successful and finalized
CloudFormation waits indefinitely
the stack is deleted

41. How do you handle circular dependencies in CloudFormation?

A circular dependency happens when Resource A's properties reference Resource B, and Resource B's properties reference Resource A back, which CloudFormation's topological sort can't resolve into any valid order, and it fails template validation with an explicit circular dependency error before ever attempting to create anything.

The most common real case is a pair of security groups that each need to allow ingress from the other. The standard fix is separating the resource creation from the rule attachment: create both security groups bare, with no ingress rules inline, then add each ingress rule as its own separate AWS::EC2::SecurityGroupIngress resource referencing the other group's ID, which breaks the cycle because the rule resources depend on both groups but the groups no longer depend on each other.

The general pattern extends beyond security groups: whenever two resources seem to need each other's identifiers, look for a way to express the relationship as a third, separate resource that references both, rather than trying to make the two original resources reference each other directly.

Take quiz
A circular dependency between two resources causes CloudFormation to:
silently pick an arbitrary order
fail template validation before creating anything
create both resources in parallel with no issue
automatically insert a DependsOn
The standard fix for two security groups needing mutual ingress is:
deleting one of the security groups
separating the ingress rules into their own SecurityGroupIngress resources
using Fn::ImportValue instead
adding both to the same Mappings entry

42. Explain how CloudFormation Hooks work?

Hooks let you run custom validation logic before CloudFormation actually provisions or updates a resource, invoked at specific points, before create, before update, before delete, rather than after the fact like drift detection.

A hook is registered in the CloudFormation Registry (much like a custom resource type) and implemented as code, often via the Hooks CLI which scaffolds a Lambda-backed handler, that receives the target resource's properties and returns one of a few outcomes: PASS to let the operation continue, FAIL to block it outright, or, depending on configuration, a warning that doesn't block but gets logged.

Hooks can be scoped to run as a mandatory blocking check across an entire account or organization, which makes them the mechanism for enforcing policy at provisioning time, for example rejecting any S3 bucket resource that doesn't have encryption enabled in its properties, before that non-compliant bucket is ever actually created, rather than catching it afterward through drift or Config rules.

Take quiz
A key difference between Hooks and drift detection is that Hooks:
run after resources are already live
run before a resource is actually provisioned or updated, and can block it
only work with nested stacks
cannot be scoped to an organization
A hook returning FAIL will:
log a warning but allow the operation to continue
block the resource operation outright
delete the entire stack
trigger drift detection automatically

43. How do you implement blue/green deployments using CloudFormation?

CloudFormation doesn't have a single built-in "blue/green" resource, so it's typically achieved by combining a couple of patterns rather than one feature.

One common approach uses an Auto Scaling group's UpdatePolicy with a full replacement update strategy: CloudFormation stands up an entirely new ASG (green) alongside the existing one (blue), waits for it to pass health checks, shifts traffic over via the update policy's configuration, then terminates the old ASG, all within a single stack update.

A more explicit pattern deploys blue and green as two separate stacks (or one stack per environment behind a shared Route 53 or ALB layer managed outside either stack), then cuts traffic over by updating a weighted Route 53 record or an ALB listener rule, which is more manual to orchestrate but gives cleaner rollback: reverting is just repointing the record back, not another CloudFormation deployment.

For fully managed blue/green at the deployment-orchestration layer, teams often layer CodeDeploy on top of CloudFormation-managed infrastructure rather than trying to make CloudFormation itself own the traffic-shifting logic end to end.

Take quiz
A common CloudFormation-native approach to blue/green uses:
the Mappings section exclusively
an Auto Scaling group's UpdatePolicy with replacement update behavior
Fn::FindInMap
DeletionPolicy: Retain
For fully managed traffic-shifting orchestration, teams often layer:
AWS Config on top of CloudFormation
CodeDeploy on top of CloudFormation-managed infrastructure
StackSets exclusively
Fn::ImportValue only

44. What are CloudFormation modules and how do they differ from nested stacks?

A module is a packaged, reusable unit of one or more resources that gets registered in the CloudFormation Registry and then used inside a template as if it were a native resource type, with its own schema for the properties it accepts.

The key difference from a nested stack is architectural: a module's resources are inlined directly into the parent stack's own resource set at deployment, there's no separate child stack created, no separate ARN, no separate set of stack events to check. A nested stack, by contrast, is a genuinely distinct stack resource with its own lifecycle, visible independently in the console and CLI.

Practically, modules feel lighter-weight for small, frequently reused patterns, a standard set of three tagged S3 buckets, say, because there's no extra stack to manage, while nested stacks remain the better fit when the reusable piece is large enough that you want its own independent stack-level visibility, events, and outputs.

Take quiz
Modules differ from nested stacks because module resources are:
deployed as a fully separate child stack
inlined directly into the parent stack's own resources
only usable with StackSets
stored exclusively in S3
Nested stacks are a better fit than modules when:
the reusable unit is tiny and rarely changes
you want independent stack-level visibility, events, and outputs
you want to avoid the CloudFormation Registry entirely
only JSON templates are allowed

45. How does the CloudFormation Registry work for third-party resource types?

The Registry is where CloudFormation keeps the schema and handler code for every resource type it can provision, not just AWS's own (AWS::*) types but third-party and private types too, registered under a namespace like ThirdParty::Vendor::ResourceType or a private Private::* namespace for your own custom types.

A third-party provider publishes a resource provider package implementing the standard CRUDL model, Create, Read, Update, Delete, List handlers, usually backed by Lambda, along with a JSON schema describing the resource's properties, required fields, and read-only attributes. Once activated in your account (from the Registry's public listing or a private submission), CloudFormation treats that type exactly like a native AWS resource type in a template, including support for drift detection if the provider implements the Read handler correctly.

This is what lets templates manage resources in tools like Datadog, PagerDuty, or MongoDB Atlas directly alongside native AWS resources, in the same template, the same stack, and the same dependency graph, rather than needing a separate provisioning step outside CloudFormation entirely.

Take quiz
Third-party resource providers implement handlers following the model:
Create, Read, Update, Delete, List
Build, Ship, Deploy
Init, Plan, Apply
Start, Stop, Restart
Activating a third-party type lets CloudFormation:
treat it exactly like a native AWS resource type in a template
only use it inside nested stacks
skip dependency resolution for it
disable drift detection for the whole stack

46. Explain the internal working of the resource provider framework (CRUDL model)?

Every resource type CloudFormation manages, native AWS types included, is backed by a provider implementing up to five handlers: Create, Read, Update, Delete, and List, each a discrete operation CloudFormation invokes at the appropriate moment in a stack's lifecycle rather than one monolithic "apply" function.

Create runs once when the resource is first added to a template; Update runs when a template change affects that resource's properties (with the provider itself deciding, per property, whether the change can be handled in-place or requires signaling Replacement back to CloudFormation); Delete runs when the resource is removed from the template or the stack is deleted; Read is what actually powers drift detection, since it's the handler that fetches current, live state for comparison; List enables resource import and certain discovery scenarios.

Because each handler is independent and explicitly scoped, a provider can, for instance, support drift detection (Read implemented) while still lacking full import support (List not implemented), which is exactly why capability varies resource type by resource type rather than being all-or-nothing.

Take quiz
The handler that powers drift detection is:
Create
Update
Read
Delete
A provider deciding whether an Update can happen in-place happens in:
the List handler
the Update handler itself
the Delete handler
a separate Hooks-only process

47. How do you optimize CloudFormation templates that hit template size or resource count limits?

CloudFormation enforces hard limits, a template body capped when submitted inline (larger via an S3-hosted template), and a maximum of 500 resources per stack, so large environments eventually need a strategy beyond just adding more resources to one file.

  1. Split by logical domain into nested stacks, networking, IAM, compute, data, each independently under the resource limit, coordinated through a parent stack.
  2. Move large or repeated JSON/YAML fragments (like IAM policy documents) into Fn::Transform macros or CloudFormation modules, reducing duplicated bytes across the template.
  3. Host the template in S3 rather than submitting it inline, which raises the size ceiling and is required anyway once a template exceeds the inline limit.
  4. Consider StackSets rather than one enormous single-account stack when the actual driver is deploying the same pattern to many accounts/regions, since that's a replication problem, not a single-template size problem.

The underlying judgment call is recognizing when the real issue is architectural, too much unrelated infrastructure crammed into one stack, versus purely a byte-size problem solvable by hosting the template in S3.

Take quiz
CloudFormation's per-stack resource limit is:
50
500
5,000
unlimited
Hosting a template in S3 instead of submitting it inline:
reduces the resource limit further
raises the size ceiling and is required once the inline limit is exceeded
disables drift detection
is only allowed for StackSets

48. Explain how CloudFormation integrates with AWS Config for compliance and drift remediation?

AWS Config continuously records configuration changes to supported resources independent of how those changes happened, whether through CloudFormation, the console, or another tool entirely, and evaluates them against Config rules that express compliance requirements, encryption enabled, specific tags present, and so on.

Where this connects to CloudFormation is twofold. First, Config's own change history can corroborate what CloudFormation's drift detection reports, since Config was watching that resource continuously rather than only at the moment you ran a drift check, which helps pinpoint exactly when an out-of-band change happened. Second, a non-compliant resource flagged by Config can trigger an automated remediation action, and one common remediation pattern is invoking a Systems Manager Automation document that itself calls back into CloudFormation, either updating the owning stack to re-assert the template's intended configuration, or in stricter setups, alerting a team rather than auto-remediating resources that CloudFormation manages, to avoid two systems fighting over the same resource.

The practical governance pattern is Config for continuous, real-time compliance monitoring across all resources, and CloudFormation drift detection plus scheduled checks for confirming that AWS-managed infrastructure specifically still matches its source-of-truth template.

Take quiz
AWS Config records changes to resources:
only if made through CloudFormation
regardless of how the change was made, console, CLI, or CloudFormation
only for S3 buckets
only once per day
A common governance pattern combines:
Config for continuous compliance monitoring and CloudFormation drift detection for template-source-of-truth checks
only Config, ignoring CloudFormation entirely
only CloudFormation, ignoring Config entirely
StackSets replacing both tools

49. Explain the execution flow of StackSets automatic deployment across an AWS Organization with drift detection enabled?

With Service-Managed permissions and automatic deployment enabled, a StackSet stays synchronized with an Organizational Unit's actual membership over time, not just at the moment you first configure it.

flowchart TD
A["Account added to targeted OU"] --> B["Organizations event detected by StackSets"]
B --> C["StackSets auto-creates a stack instance in new account"]
C --> D["Template deployed per configured operation preferences"]
D --> E["Scheduled or manual drift detection runs across all instances"]
E --> F{Instance's live resources match template?}
F -- Yes --> G["Reported IN_SYNC"]
F -- No --> H["Reported MODIFIED or DELETED per resource"]

Symmetrically, when an account is removed from the OU (or the OU itself is deregistered), automatic deployment removes the corresponding stack instance, deleting the resources it created there, which is why automatic deployment needs deliberate scoping, an overly broad OU can mean unexpected deletions when accounts get reorganized for unrelated reasons.

Drift detection at the StackSet level runs per stack instance individually and aggregates results back up, so you can see at a glance which specific accounts have drifted without manually checking each one, but it still doesn't remediate anything itself, the operational response to drifted instances at scale is the same manual or automated-remediation decision as for any single stack.

Take quiz
When an account is removed from the targeted OU:
nothing happens until manually deleted
automatic deployment removes the corresponding stack instance and its resources
the entire StackSet is deleted
drift detection is disabled account-wide
StackSet-level drift detection:
automatically remediates drifted instances
runs per instance and aggregates results, without remediating anything itself
only works with Self-Managed permissions
disables automatic deployment

50. Explain the internal working of nested stack change propagation when a parent template updates?

A nested stack is just a resource, of type AWS::CloudFormation::Stack, inside its parent's own dependency graph, so from the parent's perspective, updating a nested stack's template or parameters is handled exactly like updating any other resource: CloudFormation computes whether that resource needs to change, and if so, issues an update to it in dependency order alongside everything else in the parent.

Underneath, "updating" a nested stack resource actually triggers a genuine UpdateStack call against that child stack, which then runs its own full update lifecycle, its own change calculation, its own resource-level updates or replacements, and its own potential rollback, entirely independent of the parent's rollback mechanics at that inner layer.

The critical detail is propagation direction and rollback scope: if the nested stack's update fails and it rolls back internally, that failure bubbles back up and fails the parent's overall update too, triggering the parent's own rollback across every other resource it touched in that same operation, so a single nested stack failure can cascade into reverting sibling resources that had nothing to do with the actual problem.

This is also why passing only the minimal necessary Parameters into a nested stack, rather than reusing one giant shared parameter set, reduces how often an unrelated parent-level change triggers a nested stack update at all.

Take quiz
Updating a nested stack from its parent actually triggers:
a direct resource property edit with no separate stack lifecycle
a genuine UpdateStack call against the child stack, with its own lifecycle
a StackSet operation
a Fn::ImportValue call
If a nested stack's internal update fails and rolls back:
only that nested stack is affected, the parent is untouched
it bubbles up and fails the parent's update too, rolling back other resources
the parent stack is automatically deleted
drift detection is triggered instead
«
»

Comments & Discussions