Skip to Content
Asterrr's Handbook
6 · Security foundations and governance

Secure CloudFormation templates, Guard and Hooks

Dynamic references, NoEcho, cfn-lint, CloudFormation Guard and Guard Hooks for shift-left compliance.

Exam tasks: 6.2 (skill 6.2.1 IaC across accounts with StackSets, Guard and cfn-lint)

The decision: where in the path from a developer's commit to a running resource should each security check sit, and which tool pushes the same secure baseline into every account?

Keep secrets out of templates and block non-compliant infrastructure before it exists. Dynamic references hide secrets. Guard checks policy client side. Guard Hooks enforce it server side.

Pipeline (client side)CloudFormation (server side)lint and testdeployrulespassresolveTemplatecfn-guardvalidateGuard HookRules in S3Secrets ManagerStack
Secrets resolve at deploy time. Guard validates in the pipeline, and a Hook re-checks on the CloudFormation service itself.
FAIL / WARN
The two Hook failure modes. WARN logs and continues, FAIL stops the operation.
OU targets
Only service-managed StackSets can target OUs and auto-deploy to new accounts.
iam:PassRole
The only extra permission a user needs to deploy with a CloudFormation service role.

Checks along the deployment path

block any path,including the consoleCommit templatePipeline cfn-lint, Guard,Checkov or cfn-nagChange set reviewCloudFormation Hooks andControl Tower proactivecontrolsStack runs with a serviceroleLive resourcesDrift detectionand Config rulesSCPs, RCPs,declarativepolicies
Diagram of checks along the deployment path
StageToolStops a bad resource?Covers console changes?
Pull request or buildcfn-lint (syntax, schema), CloudFormation Guard (your rules), third-party scannersYes, the pipeline failsNo
CloudFormation operationHooks (Guard, Lambda or custom), Control Tower proactive controlsYes, or warns onlyNo
API callSCP, RCP, declarative policy, IAMYesYes
After deploymentDrift detection, Config rules, Security Hub CSPMNo, it reports (Config can remediate)Yes

Exam signal

"Shift left" or "catch it in the pipeline before anything is deployed" means Guard or cfn-lint in CodeBuild. "Enforce it for every CloudFormation deployment in the account, even outside our pipeline" means a Hook.

Passing secrets

MethodBehavior
Dynamic reference{{resolve:service:reference-key}}. CloudFormation fetches the value during stack and change set operations. Best choice
ssmParameter Store plaintext string
ssm-secureParameter Store SecureString
secretsmanagerSecrets Manager secret, for example {{resolve:secretsmanager:DBcreds:SecretString:password}}
NoEcho: trueMasks the parameter in console and describe output only. Not encryption

Dynamic reference limits.

  • Up to 60 per template.

  • Not resolved before transforms such as AWS::Include or AWS::Serverless.

  • Not supported in AWS::CloudFormation::Init metadata or EC2 UserData.

  • Do not put them in a resource's primary identifier property, because the plaintext may leak into resource IDs and outputs.

  • Better still, let the service own the secret. RDS and Aurora can create and rotate the master password in Secrets Manager themselves (ManageMasterUserPassword), so nobody ever sees it.

  • NoEcho: true on a parameter masks it as asterisks in describe calls and the console. It doesn't mask a value you copy into Outputs, the Metadata section or a resource's own configuration, such as a Lambda environment variable anyone with lambda:GetFunctionConfiguration can read.

NoEcho is not a vault

NoEcho only hides the parameter in CloudFormation's own responses. The value still has to come from somewhere, and people still pass it on the command line or store it in a pipeline variable. When the question says "the password must never appear in the template or the pipeline", the answer is a dynamic reference to Secrets Manager.

Protect the stack itself

ControlProtects againstNote
Termination protectionSomeone deleting the whole stackOff by default. Nested stacks inherit it from the root stack
Stack policyUpdates that replace or delete named resources, such as a production databaseJSON policy on the stack. Once set, all resources are protected unless allowed. Can be overridden for one update
DeletionPolicy: Retain or SnapshotData loss when a resource is removed from the template or the stack is deletedPair with UpdateReplacePolicy for replacement updates
Service roleDevelopers needing broad permissions to deployCloudFormation uses the role's permissions. Users only need iam:PassRole on it plus CloudFormation actions
Change setsSurprise replacementsReview what will be added, modified or replaced before executing
  • A service role is how you give a team "deploy through CloudFormation only". Their own role has no EC2 or IAM write permissions, and an SCP or permissions boundary stops them passing a more powerful role.
  • Restrict which roles can be passed with iam:PassRole scoped to specific role ARNs and the iam:PassedToService condition set to cloudformation.amazonaws.com.

Policy as code

CloudFormation Guard

  • Open-source policy-as-code tool with a declarative DSL. It validates CloudFormation and Terraform plan JSON, Kubernetes manifests and other JSON or YAML against your rules.
  • Run cfn-guard validate in the pipeline. The Guard rules registry has ready-made rule sets mapped to common frameworks.
  • The same rule language runs in three places: the pipeline, Guard Hooks in CloudFormation, and AWS Config custom policy rules. Write once, check at every stage.

CloudFormation Hooks

  • Run inside CloudFormation before a resource, stack or change set operation (and for Cloud Control API operations). Implement them with Guard rules, a Lambda function, or a custom Hook from the registry.
  • Each Hook has a failure mode: FAIL blocks the operation, WARN lets it continue and records the result. Start with WARN to measure impact, then switch to FAIL.
  • Control Tower proactive controls are pre-built Hooks that you enable on OUs instead of writing your own.

Hooks and the console

Hooks and proactive controls only see resources created through CloudFormation (and Cloud Control API). An engineer creating a public bucket in the console bypasses them. If the requirement is "impossible to create", add an SCP, RCP or declarative policy. If it's "find it if it happens", add a Config rule.

Tool comparison

ToolWhere it runsChecks
cfn-lintDeveloper machine, CISyntax, property values and best practices against resource schemas. Not a policy engine
CloudFormation GuardDeveloper machine, CI, can also evaluate Config itemsYour policy rules as code over JSON or YAML: CloudFormation, change sets, Terraform JSON, Kubernetes manifests. No server-side enforcement
Guard HookCloudFormation serviceEvaluates stacks, resources, change sets and Cloud Control API calls. Blocks or warns
Config proactive ruleConfigEvaluates proposed resource properties. No blocking

Guard Hook settings

SettingDetail
RulesStored in S3 (.guard, .zip or .tar.gz). Fetched on every invocation, so use object versions
Execution roleNeeds s3:GetObject, s3:ListBucket and s3:GetObjectVersion on the rules bucket. Trust principal hooks.cloudformation.amazonaws.com
Failure modeFAIL blocks the operation. WARN allows it with a warning
TargetsSTACK, RESOURCE, CHANGE_SET, Cloud Control API
FiltersResource types, stack names, stack roles. Ignored for Cloud Control API
ScopeActivate per account and Region. CloudFormation resource AWS::CloudFormation::GuardHook

Roll out in WARN first, then move to FAIL.

Exam signal

"Stop developers deploying unencrypted resources through CloudFormation, enforced by the service": Guard Hook in FAIL mode. "Validate in the CI pipeline": cfn-guard validate in CodeBuild.

Drift detection

  • Drift is any difference between a stack's template and the live resources: a security group rule added in the console, a bucket policy loosened by hand, a resource deleted outside CloudFormation.
  • Run drift detection on a stack, a single resource, or a whole StackSet. It reports each resource as in sync, modified, deleted or not checked, with a property-level diff.
  • Drift detection doesn't run continuously on its own. Use the Config managed rule cloudformation-stack-drift-detection-check to evaluate stacks on a schedule and alert through EventBridge.
  • To fix drift, update the stack so the template wins again, or update the template to match reality and import the resource. Then remove the permission that let someone change it by hand.

Deploying across accounts with StackSets

Self-managed permissionsService-managed permissions
SetupYou create an administration role and an execution role in every target accountEnable trusted access with Organizations. StackSets creates the roles
TargetsAccount IDsOUs (or the whole organization)
New accountsAdd them yourselfAutomatic deployment when an account joins the target OU
Account leaves the OUNothing happensStack instances are deleted or retained, your choice
Who can run itAdmin accountManagement account or a delegated administrator
  • Use service-managed StackSets for security baselines: Config rules, IAM roles for incident response, GuardDuty export settings, the KMS key and vault that a backup policy needs.
  • Service-managed StackSets don't deploy to the management account, even if you target the root. Deploy there separately if you need to.
  • Control failure tolerance and concurrency so a bad template stops after a few accounts, not all of them.

Scenarios

Scenario
A fintech company deploys all infrastructure with CloudFormation from a CodePipeline pipeline. A security review found that one template passes a third-party API key as a plaintext parameter with a default value, and that the pipeline logs contain the key. The company needs the key out of the template and the logs, with rotation handled centrally. What should the team do?
Scenario
A platform team wants developers to create S3 buckets and SQS queues only through CloudFormation, and wants every stack to fail if a bucket lacks default encryption with a KMS key or blocks public access incorrectly. The team already has these checks written as CloudFormation Guard rules that run in its own pipeline, but some teams deploy from their own laptops. What should the platform team do?

Config proactive rules, Control Tower proactive controls. StackSets with Service Catalog, RAM and Firewall Manager, Config compliance.

Further reading

On this page