Production AWS environments fail when infrastructure is shaped by console clicks, copy-pasted snippets, or shell scripts that drift the moment a teammate edits a setting. The discipline of infrastructure as code (IaC) forces every resource definition through a versioned source artifact, a deterministic synthesis step, and an idempotent provisioning engine. On AWS that engine is AWS CloudFormation, even when the author writes AWS CDK in TypeScript or AWS SAM in YAML: both layers synth down to CloudFormation templates that the CloudFormation service applies through change sets and stack events. The professional-level question is not whether to use IaC, it is how to express reusable, secure, multi-account environments inside that model without inviting the well-known failure modes of stuck stacks, drifted resources, and orphaned dependencies.
A reusable environment is one that can be re-instantiated in a new account, a new Region, or a new workload boundary by changing only parameters or a context configuration. Reusability lives at three levels. At the template level, parameters, mappings, and conditions let one file express development, staging, and production variants. At the composition level, nested stacks and CloudFormation modules let templates import building blocks instead of duplicating resource definitions. At the distribution level, StackSets push the same template to many accounts and Regions through one administrative action. Each level has explicit limits and failure modes that the exam tests.
The security baseline applied to a new account belongs in IaC for the same reason: the controls that protect a new workload account, AWS Config recorders, AWS CloudTrail trails, baseline IAM roles, Amazon GuardDuty detectors, and KMS keys for log encryption, are themselves resources that should be deployed deterministically, versioned, and verifiable. The pattern that emerges across DevOps Professional scenarios is a layered template stack: an account-baseline template (deployed automatically when an account is created), a workload-baseline template (deployed when an application is onboarded), and a workload template (deployed by application teams as part of CI/CD).
Authoring Layers: CloudFormation, AWS CDK, and AWS SAM
CloudFormation templates declare resources in JSON or YAML against a documented resource schema. The template is the source of truth; the stack is the provisioned manifestation; the change set is the preview of what an update will do. AWS CDK adds a higher-level programming model: constructs written in TypeScript, Python, Java, C#, or Go that compose into a Stack and synthesize to a CloudFormation template inside the cdk.out directory. AWS SAM is a CloudFormation transform (Transform: AWS::Serverless-2016-10-31) that expands compact serverless resource types (AWS::Serverless::Function, AWS::Serverless::Api, AWS::Serverless::StateMachine) into the underlying Lambda, API Gateway, IAM, and EventBridge resources.
# account-baseline.yaml: minimum security baseline for a new workload account
AWSTemplateFormatVersion: "2010-09-09"
Description: Baseline guardrails for a newly onboarded workload account
Parameters:
CentralLogBucketArn:
Type: String
Description: ARN of the central log archive bucket in the Log Archive account
OrganizationId:
Type: String
Resources:
AccountTrail:
Type: AWS::CloudTrail::Trail
Properties:
TrailName: account-baseline-trail
IsMultiRegionTrail: true
IncludeGlobalServiceEvents: true
EnableLogFileValidation: true
S3BucketName: !Select [5, !Split [":", !Ref CentralLogBucketArn]]
S3KeyPrefix: !Sub "AWSLogs/${AWS::AccountId}"
IsLogging: true
ConfigRecorderRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal: { Service: config.amazonaws.com }
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWS_ConfigRole
ConfigRecorder:
Type: AWS::Config::ConfigurationRecorder
Properties:
RoleARN: !GetAtt ConfigRecorderRole.Arn
RecordingGroup:
AllSupported: true
IncludeGlobalResourceTypes: true
GuardDutyDetector:
Type: AWS::GuardDuty::Detector
Properties:
Enable: true
FindingPublishingFrequency: FIFTEEN_MINUTES
The CDK equivalent expresses the same baseline as a Stack whose synth output is a CloudFormation template, then deploys it through cdk deploy --all. The professional-level decision is when each layer pays off: CloudFormation for control-plane services whose schema is stable and where every parameter must be visible in the YAML; AWS CDK when type checking, loops, and shared library abstractions reduce duplication across many similar resources; AWS SAM when the workload is primarily Lambda, API Gateway, Step Functions, and EventBridge and you want compact resource types with built-in deployment preferences.
# account_baseline.py: identical baseline expressed in AWS CDK
from aws_cdk import Stack, aws_cloudtrail as ct, aws_config as cfg, aws_guardduty as gd, aws_iam as iam
from constructs import Construct
class AccountBaselineStack(Stack):
def __init__(self, scope: Construct, cid: str, log_bucket_arn: str, **kw) -> None:
super().__init__(scope, cid, **kw)
trail = ct.CfnTrail(self, "AccountTrail",
trail_name="account-baseline-trail",
is_multi_region_trail=True,
include_global_service_events=True,
enable_log_file_validation=True,
s3_bucket_name=log_bucket_arn.split(":")[-1],
s3_key_prefix=f"AWSLogs/{self.account}",
is_logging=True,
)
role = iam.Role(self, "ConfigRole",
assumed_by=iam.ServicePrincipal("config.amazonaws.com"),
managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWS_ConfigRole")],
)
cfg.CfnConfigurationRecorder(self, "Recorder",
role_arn=role.role_arn,
recording_group=cfg.CfnConfigurationRecorder.RecordingGroupProperty(
all_supported=True, include_global_resource_types=True,
),
)
gd.CfnDetector(self, "Detector", enable=True, finding_publishing_frequency="FIFTEEN_MINUTES")
Reusable Environments Through Parameterization
Parameters, mappings, conditions, and pseudo-parameters keep one template usable across environments without forking. AWS::Region and AWS::AccountId are pseudo-parameters resolved at deploy time, eliminating hard-coded ARNs. Mappings carry per-Region or per-environment lookup tables (AMI IDs, log retention values, instance sizes). Conditions toggle resources on or off so that a development stack skips the multi-Region S3 replication that production requires. CDK expresses the same pattern through context (cdk.context.json) and environment-aware Stage constructs.
💡 Exam Trap: A
Conditionsblock can gate a Resource block but cannot gate an individual property of a resource. To toggle a property, define two separate resources withCondition: IsProdandCondition: IsNotProdand let CloudFormation create exactly one of them. Hiding this constraint behind a parameter substitution that resolves to an invalid value is the common wrong answer.
Applying Security Baselines and Compliance Configurations to New Accounts
The professional pattern for applying a security baseline to a newly onboarded account is to deploy the baseline template automatically through AWS CloudFormation StackSets with the service-managed permissions model, targeting the entire organization or a specific organizational unit (OU). The moment AWS Control Tower or AWS Organizations creates a new account inside an enrolled OU, the StackSet provisions the baseline resources without human intervention. Compliance configurations (AWS Config conformance packs, AWS Security Hub enablement, AWS GuardDuty member invitations) layer on top of that baseline through a second StackSet or a Control Tower customization pipeline.
The baseline must be defined as code in the same repository as the rest of the platform's IaC so that pull requests, peer review, and pipeline tests apply to security controls with the same discipline as application code. A common pattern is to keep baseline/ separate from workload/ in a Git monorepo, with a CodePipeline that deploys baseline changes to StackSet administration in the management account and a second pipeline that deploys workload changes per account.
⚠️ Anti-Pattern: Defining the account baseline imperatively (a one-off shell script that runs after account creation) and tracking compliance separately. The baseline must be a stack that you can re-apply, drift-detect, and audit. Imperative baselines drift the moment an engineer toggles a setting in the console.
🎯 Scenario: A platform team onboards three new workload accounts each week and must verify within fifteen minutes that AWS CloudTrail, AWS Config, GuardDuty, and a baseline IAM role for the central observability account exist in every Region. They author a single CloudFormation template, register it as a service-managed StackSet against the
WorkloadsOU, and setAutoDeployment.Enabled: true. New accounts inherit the baseline at creation; existing accounts receive updates the next time the StackSet is updated. Drift checks run on a Systems Manager scheduled Automation runbook each night.
Limits and Quotas
| Constraint | Value | Notes |
|---|---|---|
| Resources per CloudFormation stack | 500 | Nested stacks count as one resource in the parent. |
| Parameters per stack | 200 | Use mappings or SSM Parameter Store types for larger lookup tables. |
| Mappings per template | 200 | Each mapping limited to 64 attributes. |
| Outputs per stack | 200 | Cross-stack references via Fn::ImportValue use Outputs. |
| StackSet operations in progress per administrator account | 1 per StackSet | Concurrent operations across different StackSets are allowed. |
| CDK context entry size | No hard limit | But cdk.context.json is checked into source control; keep it small. |
📊 Limit: Template body size is 51,200 bytes (~51 KB) when uploaded inline through the API and 1 MB when uploaded through Amazon S3 (after expansion of any
AWS::Includetransforms). Templates that approach this limit are a forcing function to split into nested stacks.
💡 Exam Trap: AWS SAM templates that use the
AWS::Serverless-2016-10-31transform are expanded by CloudFormation BEFORE the stack is created. A SAM template that synthesizes to more than 500 resources fails the per-stack limit even though the YAML looks small. Watch forAWS::Serverless::Apiwith many path-and-method combinations: each route can expand to multiple underlying API Gateway resources.
Decision Anchor. Choose AWS CloudFormation when every property must be visible in version control, the team is comfortable with YAML or JSON, and the workload spans services without rich CDK constructs. Choose AWS CDK when a single team owns many similar stacks (per-tenant, per-account) and benefits from shared TypeScript or Python libraries that fail at compile time on misconfiguration. Choose AWS SAM when the workload is primarily AWS Lambda, Amazon API Gateway, AWS Step Functions, or Amazon EventBridge and you want DeploymentPreference blocks that integrate directly with AWS CodeDeploy for canary or linear traffic shifting.
