Lesson 219 · AWS Learning Path

AWS 219: CloudFormation templates and stacks

· Published · 7 min read

Labelled process diagram for AWS 219: Versioned template to CloudFormation validation and change to Stack resources to Events, outputs, drift, and lifecycle evidence, with decision, proof and rejection evidence.

Why this lesson matters

Clicking in a console records a result; a CloudFormation template records an intended system. CloudFormation resolves references into a dependency graph, calls AWS service APIs, records events, and attempts rollback when an operation fails. It does not make an unsafe design safe, protect every data resource automatically, or eliminate the need to understand replacement and deletion.

What you will be able to do

By the end, you can:

  • distinguish template, stack, stack instance, logical ID and physical ID;
  • explain every top-level template section and the resource dependency graph;
  • predict create, update, replacement, rollback and deletion behavior;
  • distinguish DeletionPolicy, UpdateReplacePolicy, termination protection and stack policy;
  • read stack events from the first failed resource rather than the final generic status;
  • explain execution-role and caller permissions plus IAM capability acknowledgements;
  • validate the P11 template locally and through AWS without deploying it;
  • identify retained resources that survive stack deletion.

Before you start

  • This lesson is no-create. Download and inspect the P11 template and runbook.
  • Use a normal federated/role identity, never root. Confirm account and ap-south-1.
  • Do not place passwords, tokens or private data in templates, parameter defaults, outputs, metadata or command history.
  • YAML parsing and validate-template are necessary but not sufficient security or deployment tests.
  • The P11 data resources intentionally use retention policies. That design prevents accidental stack deletion from erasing data but creates a separate cleanup responsibility.

The core objects

ObjectMeaning
TemplateVersioned JSON/YAML desired-state document. It is not a running environment.
StackRegional CloudFormation operation boundary containing resources, parameters, outputs, events and status.
Logical IDStable template key such as ArtifactBucket; references use it.
Physical IDActual service identifier such as a generated ARN/name. It can change during replacement.
Change setProposed API-level resource actions for a template/parameter update; it is not executed automatically unless requested.
Stack eventTime-ordered evidence for one resource operation and its reason.
Drift resultComparison of supported declared properties with current values; it is not a compliance verdict.

CloudFormation is Regional, although a template can create resources whose service scope is global or account-wide. A stack name is not ownership proof: verify account, Region, stack ID, tags and outputs.

Template anatomy

SectionPurposeP11 example
AWSTemplateFormatVersionTemplate language version2010-09-09; it is not the template's release date
DescriptionHuman purposesafe learning scope
MetadataOptional tooling/UI informationnever a secret store
ParametersDeployment-time input contractenvironment, retention, alarm choice
RulesParameter validation involving multiple valuesnot required by P11
MappingsStatic lookup tablesnot required by P11
ConditionsDecide whether resources/properties existoptional alarm
TransformMacro such as SAM; transforms template before deploymentabsent, so no macro review boundary
ResourcesRequired desired-state resource declarationsbucket, log group, optional alarm
OutputsNon-secret stack interface valuesphysical names/ARN and condition result

A template's file order is not deployment order. Ref, GetAtt, and many Sub references create implicit graph edges. Use DependsOn only for a real dependency CloudFormation cannot infer; unnecessary explicit edges reduce parallelism and can hide a design smell.

Lifecycle and data safety

template + parameters + identity
              |
              v
      dependency graph / API calls
              |
       +------+------+
       |             |
   success       first failure
       |             |
       v             v
CREATE_COMPLETE   rollback attempt
       |
template/property update
       |
in-place modify OR replacement
       |
old physical resource governed by UpdateReplacePolicy
  • DeletionPolicy applies when a resource is removed from the template or its stack is deleted.
  • UpdateReplacePolicy applies to the old physical resource when an update replaces it.
  • Retain removes the resource from CloudFormation's management but leaves it and its bill/data ownership behind.
  • Snapshot is supported only by resource types that implement it.
  • Termination protection blocks stack deletion; it does not block resource updates or deletion caused by an update.
  • A stack policy protects selected resources from updates; it is not an IAM policy and does not protect out-of-band service API changes.
  • Rollback is best effort. A failed rollback can require continue-update-rollback, resource repair or explicit resources-to-skip; skipped resources leave template/actual state inconsistency to reconcile.

Read each property in the CloudFormation resource specification for update behavior: No interruption, Some interruptions, or Replacement. Never infer replacement risk from the property name.

Identity and permission path

Without a CloudFormation service role, CloudFormation operates using a temporary session based on the initiating identity. With a service role, CloudFormation uses that role for stack operations and continues using it for future operations. The operator needs permission to call CloudFormation and, where applicable, pass the exact role; the execution role needs only the service actions required by the template.

CAPABILITY_IAM and CAPABILITY_NAMED_IAM are explicit acknowledgements for templates that create IAM resources. They do not grant permission or make broad policies safe. CAPABILITY_AUTO_EXPAND acknowledges macros without reviewing an expanded change set. P11 creates no IAM resource and needs no capability flag.

Inspect P11 locally

curl -sS -o template.yaml \
  http://xupdate.nitwings.com/downloads/aws-academy/p11-cloudformation-automation/template.yaml
test -s template.yaml
rg -n '^(Parameters|Conditions|Resources|Outputs):|DeletionPolicy|UpdateReplacePolicy|!Ref|!GetAtt|!Sub|!If' template.yaml

Build a table for each logical resource: type, physical-name rule, dependencies, sensitive properties, replacement-sensitive properties, deletion behavior, cost dimensions and owner. P11 has an implicit alarm-to-log-group edge because the alarm dimension uses !Ref ApplicationLogGroup; the bucket has no dependency on the log group.

AWS semantic validation without creation

export AWS_DEFAULT_REGION="ap-south-1"
aws sts get-caller-identity --query Arn --output text
aws cloudformation validate-template \
  --template-body file://template.yaml --output json
aws cloudformation get-template-summary \
  --template-body file://template.yaml --output json
aws cloudformation list-stacks \
  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE ROLLBACK_COMPLETE \
  --query 'StackSummaries[].{Name:StackName,Status:StackStatus,Deleted:DeletionTime}' \
  --output table

validate-template sends the body to AWS and checks template syntax/structure. It does not call every target service, prove unique names, quotas, permissions, cost, policy quality, runtime behavior or deletion safety. get-template-summary exposes declared parameters, resource types and required capabilities without creating a stack.

Read stack evidence in the Console

Open CloudFormation > Stacks, confirm Region, and choose only an owned or instructor-supplied stack:

  1. Stack info: stack ID, status, role, termination protection and timestamps.
  2. Parameters: effective values, remembering that NoEcho masking is not complete secret protection.
  3. Resources: map logical to physical IDs and status reasons.
  4. Events: read oldest-to-newest around failure; find the first *_FAILED, not only rollback noise.
  5. Outputs: treat every value as visible, non-secret interface data.
  6. Template: distinguish original and processed template when transforms are used.
  7. Change sets/Drift: absence of a pending change or detected drift does not prove compliance.

Failure diagnosis

SymptomProve firstCorrect response
AlreadyExistsexact physical name, account/Region and ownershipchoose deterministic unique naming, import when supported, or remove conflicting owned resource
AccessDeniedfailed logical resource, API action, execution role and policiesadd only the required action/resource/condition; do not attach AdministratorAccess
Dependency failedearliest failed event and graphrepair root resource; downstream cancellations are symptoms
Update proposes replacementresource specification and data migration/retention planstop until backup, cutover and rollback are approved
Delete completes but resource remainsresource's deletion policy and recorded physical IDreconcile retained resource explicitly
ROLLBACK_FAILEDevent reason and externally changed/missing resourcerepair dependency, continue rollback carefully, then detect drift

Cost and cleanup

CloudFormation itself generally does not add a charge for ordinary AWS resource management, but provisioned resources and some extensions/features can. P11's bucket storage/requests/KMS requests, log ingestion/storage/query, alarm and data transfer remain service costs. Validation creates none of these.

This lesson does not deploy P11, so cleanup removes only the downloaded local copy if no longer needed. If an instructor authorizes later deployment, follow the runbook: capture outputs before deleting the stack, then separately empty/delete all retained bucket versions and delete the retained log group with owner approval.

Knowledge check

  1. Why is template order not resource order?

CloudFormation builds a graph from references and explicit dependencies.

  1. What survives P11 stack deletion?

The bucket and log group because both use DeletionPolicy: Retain.

  1. What controls an old resource during replacement?

UpdateReplacePolicy.

  1. Does CAPABILITY_NAMED_IAM grant IAM access?

No; it acknowledges named IAM creation while normal authorization still applies.

  1. Why is a successful validation not deployment proof?

It does not prove target API permissions, quotas, uniqueness, runtime behavior, security or cleanup.

Lesson acceptance

  • Template sections, logical/physical IDs and the dependency graph are explained from P11.
  • Create/update/replacement/delete and rollback paths are distinguished.
  • Both retention policies and their separate cleanup obligations are identified.
  • Caller, service-role and capability boundaries are stated correctly.
  • Local inspection plus validate-template/get-template-summary evidence is captured without creation.
  • At least three failure cases are diagnosed from the first failed event and exact logical resource.

Official sources

Advertisement