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.
Checks along the deployment path
| Stage | Tool | Stops a bad resource? | Covers console changes? |
|---|---|---|---|
| Pull request or build | cfn-lint (syntax, schema), CloudFormation Guard (your rules), third-party scanners | Yes, the pipeline fails | No |
| CloudFormation operation | Hooks (Guard, Lambda or custom), Control Tower proactive controls | Yes, or warns only | No |
| API call | SCP, RCP, declarative policy, IAM | Yes | Yes |
| After deployment | Drift detection, Config rules, Security Hub CSPM | No, 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
| Method | Behavior |
|---|---|
| Dynamic reference | {{resolve:service:reference-key}}. CloudFormation fetches the value during stack and change set operations. Best choice |
ssm | Parameter Store plaintext string |
ssm-secure | Parameter Store SecureString |
secretsmanager | Secrets Manager secret, for example {{resolve:secretsmanager:DBcreds:SecretString:password}} |
NoEcho: true | Masks 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::IncludeorAWS::Serverless. -
Not supported in
AWS::CloudFormation::Initmetadata or EC2UserData. -
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: trueon a parameter masks it as asterisks in describe calls and the console. It doesn't mask a value you copy intoOutputs, theMetadatasection or a resource's own configuration, such as a Lambda environment variable anyone withlambda:GetFunctionConfigurationcan 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
| Control | Protects against | Note |
|---|---|---|
| Termination protection | Someone deleting the whole stack | Off by default. Nested stacks inherit it from the root stack |
| Stack policy | Updates that replace or delete named resources, such as a production database | JSON policy on the stack. Once set, all resources are protected unless allowed. Can be overridden for one update |
DeletionPolicy: Retain or Snapshot | Data loss when a resource is removed from the template or the stack is deleted | Pair with UpdateReplacePolicy for replacement updates |
| Service role | Developers needing broad permissions to deploy | CloudFormation uses the role's permissions. Users only need iam:PassRole on it plus CloudFormation actions |
| Change sets | Surprise replacements | Review 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:PassRolescoped to specific role ARNs and theiam:PassedToServicecondition set tocloudformation.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 validatein 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:
FAILblocks the operation,WARNlets it continue and records the result. Start withWARNto measure impact, then switch toFAIL. - 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
| Tool | Where it runs | Checks |
|---|---|---|
| cfn-lint | Developer machine, CI | Syntax, property values and best practices against resource schemas. Not a policy engine |
| CloudFormation Guard | Developer machine, CI, can also evaluate Config items | Your policy rules as code over JSON or YAML: CloudFormation, change sets, Terraform JSON, Kubernetes manifests. No server-side enforcement |
| Guard Hook | CloudFormation service | Evaluates stacks, resources, change sets and Cloud Control API calls. Blocks or warns |
| Config proactive rule | Config | Evaluates proposed resource properties. No blocking |
Guard Hook settings
| Setting | Detail |
|---|---|
| Rules | Stored in S3 (.guard, .zip or .tar.gz). Fetched on every invocation, so use object versions |
| Execution role | Needs s3:GetObject, s3:ListBucket and s3:GetObjectVersion on the rules bucket. Trust principal hooks.cloudformation.amazonaws.com |
| Failure mode | FAIL blocks the operation. WARN allows it with a warning |
| Targets | STACK, RESOURCE, CHANGE_SET, Cloud Control API |
| Filters | Resource types, stack names, stack roles. Ignored for Cloud Control API |
| Scope | Activate 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-checkto 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 permissions | Service-managed permissions | |
|---|---|---|
| Setup | You create an administration role and an execution role in every target account | Enable trusted access with Organizations. StackSets creates the roles |
| Targets | Account IDs | OUs (or the whole organization) |
| New accounts | Add them yourself | Automatic deployment when an account joins the target OU |
| Account leaves the OU | Nothing happens | Stack instances are deleted or retained, your choice |
| Who can run it | Admin account | Management 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
A dynamic reference resolves the secret during the deployment, so the value never appears in the template, the parameters or the pipeline logs, and Secrets Manager can rotate it. NoEcho only masks the parameter in CloudFormation's responses; the pipeline still has to supply the plaintext value. Encrypting the template file leaves the key inside it, and Metadata isn't masked at all.
A Guard Hook runs inside CloudFormation itself, so it evaluates every stack no matter where the deployment was started, and FAIL mode stops the non-compliant resource. Local checks depend on each developer. A Config rule that deletes buckets acts after creation and risks data loss. Termination protection only stops stack deletion.
Related
Config proactive rules, Control Tower proactive controls. StackSets with Service Catalog, RAM and Firewall Manager, Config compliance.
Further reading
- CloudFormation: Dynamic references
- CloudFormation Guard: What is guard
- CloudFormation Hooks: Guard hooks
- CloudFormation Hooks: Guard hooks activate hooks
- CloudFormation Hooks: Guard hooks prepare to create hook
- Security best practices for CloudFormation
- What are CloudFormation Hooks?
- StackSets with service-managed permissions
Central security management and root access
Trusted access, delegated administrators, centralized root access and break-glass design across an organization.
Service Catalog, RAM and Firewall Manager
Sharing approved resources with Service Catalog and AWS RAM, and pushing central network policy with Firewall Manager.