Secure and consistent deployment
Hardening CloudFormation templates, policy as code with Guard and Hooks, drift detection, StackSets, Service Catalog and AWS RAM for sharing, Firewall Manager for central network policy, and tagging strategy.
Exam tasks: 6.2 (skills 6.2.1 IaC across accounts with StackSets, Guard and cfn-lint, 6.2.2 tagging, 6.2.3 central policy with Firewall Manager, 6.2.4 sharing with Service Catalog and AWS RAM)
The decision: where in the path from a developer's commit to a running resource should each security check sit, and which central service pushes the same secure baseline into every account without someone doing it by hand?
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.
Hardening CloudFormation templates
Keep secrets out of templates
- Dynamic references pull values at deploy time, so the template never contains them:
{{resolve:secretsmanager:prod/orders/db:SecretString:password}}for a Secrets Manager secret.{{resolve:ssm-secure:/prod/orders/api-key}}for an SSM SecureString (only supported on some resource properties).{{resolve:ssm:/golden/ami-id}}for a plain parameter.
- 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.
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.
Sharing approved resources
AWS Service Catalog
- Portfolios of products (CloudFormation templates or Terraform configurations) that users can launch without having permissions for the underlying services.
- A launch constraint names the IAM role Service Catalog uses to provision the product. The end user only needs
Service Catalog permissions, which is how you let developers create a compliant, encrypted database without
giving them
rds:*. - Template constraints limit parameter values (only these instance types). TagOptions apply mandatory tags.
- Share portfolios across the organization or to specific OUs from the management account or a delegated admin. Imported portfolios keep the admin's products and constraints.
AWS Resource Access Manager
- Shares resources (subnets, Transit Gateways, Route 53 Resolver rules, Network Firewall policies, License Manager configurations and more) with other accounts, OUs or the whole organization. The owner keeps control.
- Enable sharing with AWS Organizations so shares inside the org apply without invitations.
- Block sharing outside the organization with an SCP that denies
ram:CreateResourceShareandram:UpdateResourceSharewhenram:RequestedAllowsExternalPrincipalsis true. - Managed permissions define what consumers can do with a shared resource. Use customer managed permissions for least privilege.
Firewall Manager
Firewall Manager pushes network and edge security policies to every in-scope account and resource from one administrator account, and reapplies them when new accounts or resources appear.
| Policy type | What it enforces |
|---|---|
| AWS WAF | A web ACL with your first and last rule groups on ALBs, API Gateway stages, CloudFront and more. Accounts can add their own rules in between |
| Shield Advanced | Shield Advanced protection (and optional automatic application-layer DDoS mitigation) on chosen resource types |
| Security group | Common security groups attached everywhere, content audit (no 0.0.0.0/0 on port 22), and usage audit (unused or redundant groups) |
| Network ACL | A baseline set of network ACL rules on subnets |
| Network Firewall | Deploys firewall endpoints and a firewall policy into VPCs |
| Route 53 Resolver DNS Firewall | Associates DNS Firewall rule groups with VPCs |
| Third-party firewall | Palo Alto Networks Cloud NGFW or Fortinet FortiGate CNF from Marketplace |
- Prerequisites: Organizations with all features, a Firewall Manager administrator account (you can have several, each scoped to OUs, accounts, Regions or policy types), and AWS Config enabled in every account and Region in scope.
- Scope each policy by account, OU and resource tags. Choose auto remediate to fix non-compliant resources, or report only.
- Firewall Manager is regional for most policy types. Create the policy in each Region you use (and in us-east-1 for CloudFront).
Exam signal
"Every new ALB in any account must get the corporate WAF rules automatically" is Firewall Manager. A StackSet or a Lambda that attaches web ACLs is the more-work distractor.
Tagging strategy
- Decide a small set of mandatory tags up front, for example
owner,cost-center,environmentanddata-classification. Keep keys lowercase and values from a fixed list. - Tags drive security, not just billing: ABAC conditions (
aws:ResourceTag,aws:PrincipalTag), Firewall Manager scope, Config rule scope, Backup plan selection, and Security Hub CSPM finding context. - Enforcement stack:
- Tag policy for allowed keys, case and values.
- SCP denying create calls without the required tag (
aws:RequestTag), and denying tag changes on security-relevant tags except by an admin role (aws:TagKeys). - Config managed rule
required-tagsto find what slipped through. - Service Catalog TagOptions and CloudFormation stack-level tags so approved paths tag automatically.
- Use Resource Groups and Tag Editor to find and fix resources in bulk.
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.
Firewall Manager applies the web ACL to existing and new in-scope resources in every account, and its first and last rule groups leave room for team rules in the middle. The StackSet creates the web ACL but relies on teams to associate it. Per-account Lambda automation is the high-effort option and easy to miss in new accounts. An SCP can't check web ACL association on the create call.
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.
Further reading
Multi-account strategy
Designing an AWS Organizations OU structure for security, running Control Tower controls, delegating security services and centrally managing root access for member accounts.
Evaluating compliance
AWS Config rules, conformance packs, aggregators and automatic remediation, Security Hub CSPM standards, audit evidence with Audit Manager and AWS Artifact, Well-Architected security reviews, Trusted Advisor and the shared responsibility model.