Asterrr's Handbook

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

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.

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: 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.

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.

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:CreateResourceShare and ram:UpdateResourceShare when ram:RequestedAllowsExternalPrincipals is 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 typeWhat it enforces
AWS WAFA 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 AdvancedShield Advanced protection (and optional automatic application-layer DDoS mitigation) on chosen resource types
Security groupCommon security groups attached everywhere, content audit (no 0.0.0.0/0 on port 22), and usage audit (unused or redundant groups)
Network ACLA baseline set of network ACL rules on subnets
Network FirewallDeploys firewall endpoints and a firewall policy into VPCs
Route 53 Resolver DNS FirewallAssociates DNS Firewall rule groups with VPCs
Third-party firewallPalo 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, environment and data-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-tags to 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.
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.
AWS Config
Required in every in-scope account and Region before Firewall Manager can enforce policies.
iam:PassRole
The only extra permission a user needs to deploy with a CloudFormation service role.

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 media company has 60 accounts in AWS Organizations and adds new accounts every month. The security team must ensure every Application Load Balancer and API Gateway stage in every account, including future accounts, is protected by the company's WAF rule groups, while application teams can still add their own rules. What is the MOST operationally efficient solution?
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?

Further reading

On this page