Drift detection and StackSets
Find out when someone has changed a deployed resource outside code, report it with a tested C# tool, fix it safely with drift-aware change sets, and design a StackSet that rolls a security baseline out to every account and Region.
Assumes: CloudFormation drift detection and StackSets · AWS CLI v2 · .NET 10 LTS (DriftReport tool from lab m10-environment-two-tools) · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Define drift and name its common causes, including the ones that are legitimate.
- Run CloudFormation drift detection from the CLI, read the property-level result, and say what it cannot see.
- Turn raw drift output into a short report with exit codes using the lab's tested C# tool.
- Choose between three remedies: revert the resource, accept the change into code, or use a drift-aware change set.
- Compare drift handling in CloudFormation, the CDK (
cdk drift) and Terraform (plan -refresh-only). - Design a StackSet with service-managed permissions, auto-deployment and safe operation preferences to deploy a baseline across accounts and Regions.
Prerequisites
- AWS CloudFormation fundamentals: stacks, change sets and the
audit-bucket.yamltemplate. You deploy that stack again here. - Terraform state helps for the Terraform comparison, but is not required.
- Tools: AWS CLI v2 with the
learn-sandboxprofile, .NET 10 SDK or Docker, the lab folderlabs/m10-environment-two-tools.
Why this matters in banking
An engineer on call at 02:10 sees that the Accounts API is slow and sets the ECS service desired count from 2 to 6 in the console. The incident ends and nobody changes it back. A week later the pipeline deploys, the stack says "desired count 2", and half the capacity vanishes in the morning peak.
That is operational drift. The dangerous kind is security drift: a security group rule opened "for five minutes", an encryption setting switched off for a test, a bucket policy widened. A bank needs to find these within hours, not at the annual audit, and needs a recorded decision for each: reverted, or approved and written into code.
Drift detection is also the answer to a question regulators like to ask: "How do you know production still matches what you approved?"
The idea in plain language
Drift is any difference between what your code says exists and what actually exists in the account. Drift detection compares the two and lists differences.
Analogy: the template is the approved floor plan. Drift detection is the building inspector walking the floors with the plan in hand: "This door is not on the plan. That wall moved." The inspector does not fix anything; the owner decides whether to restore the plan or amend it.
There are two honest sources of drift:
| Source | Example | Right response |
|---|---|---|
| A person | Console edit, CLI one-off | Revert or approve, then fix the access model |
| Another automation | Auto Scaling changes desired count; an AWS service adds a tag | Remove that property from code (leave it to the automation) or ignore it |
What problem the feature solves
CloudFormation drift detection reads the live configuration of each resource in a stack and compares the properties you declared in the template with the real values. It reports each resource as:
| Resource drift status | Meaning |
|---|---|
IN_SYNC | Matches the template |
MODIFIED | At least one property differs |
DELETED | The resource no longer exists |
NOT_CHECKED | Resource type not supported, or not checked |
and the stack as IN_SYNC, DRIFTED, NOT_CHECKED or UNKNOWN. For MODIFIED resources it returns property differences with the expected value, the actual value and a difference type: ADD, REMOVE or NOT_EQUAL.
Limits to know
- Not every resource type is supported. The documentation lists the supported types ⚠ VERIFY the list before you depend on coverage for a control.
- Only properties in the template are compared. If a property is not in your template, CloudFormation has no expectation for it. This is why a security group rule added by hand can slip through, depending on how the rules are modelled. ⚠ VERIFY the exact treatment of unspecified properties for each resource type you rely on.
- Detection is a point-in-time snapshot you trigger. It does not alert by itself. You must schedule it.
- It needs read permissions for every resource type in the stack, in addition to
cloudformation:DetectStackDrift. - Write-only values (for example a password) cannot be compared with the live value. ⚠ VERIFY behaviour for your resource types.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure Resource Graph + Policy compliance | CloudFormation drift detection, AWS Config rules | Drift compares to your template; Config compares to rules you write |
ARM what-if before redeploy | Drift-aware change set (REVERT_DRIFT) | A change set that also considers the live state |
| Azure Policy remediation tasks | Revert via change set, or SSM Automation, or Config remediation | Remediation is explicit and permissioned |
| Deployment stacks across subscriptions | CloudFormation StackSets | One template, many accounts and Regions, with Organizations integration |
| Management group policy assignment | StackSet with service-managed permissions targeting OUs | New accounts in the OU get the baseline automatically |
Architecture
Security-boundary view. The identity that runs detection should be a read-only role with cloudformation:DetectStackDrift and the describe permissions of the resource types involved. It must not be able to fix what it finds. Fixing goes through the normal pipeline so that the fix is reviewed like any other change.
StackSet shape
Step-by-step implementation
You will reuse the stack from the previous lesson, change it behind CloudFormation's back, and detect the change.
Deploy the stack from the previous lesson
If hl-m10-cfn-dev-audit no longer exists, recreate it with the commands in CloudFormation fundamentals. Confirm CREATE_COMPLETE.
Detect a clean baseline
Run detection once. Expect IN_SYNC. A baseline you have never measured proves nothing.
Cause drift "from the console"
You will do it with the CLI to keep the lab scriptable. Suspend versioning on the audit bucket, which is a plausible "just for a test" change.
Detect, read and report
Detect again, read the property difference, and run the C# report on the JSON.
Fix it
Revert with a drift-aware change set, then confirm IN_SYNC.
AWS Console instructions
Console → CloudFormation → Stacks → select the stack → Stack actions → Detect drift. When it finishes, open Stack actions → View drift results. The table lists each resource with its drift status; select a drifted resource and choose View drift details to see expected and actual values side by side. In the stack list, the Drift status column shows DRIFTED or IN_SYNC. For StackSets: CloudFormation → StackSets. Navigation labels change over time ⚠ VERIFY against the current console.
AWS CLI
# 1. Baseline detection. detect-stack-drift returns an ID; detection runs asynchronously.
DETECT_ID=$(aws cloudformation detect-stack-drift --stack-name hl-m10-cfn-dev-audit \
--profile learn-sandbox --query StackDriftDetectionId --output text)
# 2. Poll until DetectionStatus is DETECTION_COMPLETE, then read StackDriftStatus
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id "$DETECT_ID" \
--profile learn-sandbox --query "[DetectionStatus,StackDriftStatus,DriftedStackResourceCount]"
# 3. Cause drift: suspend versioning on the audit bucket (an "out of band" change)
ACCOUNT=$(aws sts get-caller-identity --profile learn-sandbox --query Account --output text)
aws s3api put-bucket-versioning --bucket "hl-m10-cfn-dev-audit-$ACCOUNT-us-east-1" \
--versioning-configuration Status=Suspended --profile learn-sandbox
# 4. Detect again (repeat steps 1 and 2), then save the details of every drifted resource
aws cloudformation describe-stack-resource-drifts --stack-name hl-m10-cfn-dev-audit \
--stack-resource-drift-status-filters MODIFIED DELETED \
--profile learn-sandbox --output json > cfn-drift.jsonThe output has this shape (trimmed):
{
"StackResourceDrifts": [
{
"LogicalResourceId": "AuditBucket",
"ResourceType": "AWS::S3::Bucket",
"StackResourceDriftStatus": "MODIFIED",
"PropertyDifferences": [
{
"PropertyPath": "/VersioningConfiguration/Status",
"ExpectedValue": "Enabled",
"ActualValue": "Suspended",
"DifferenceType": "NOT_EQUAL"
}
]
}
]
}Now run the report. It lives in the lab you already have:
cd labs/m10-environment-two-tools
dotnet run --project src/Harbourline.Environment.DriftReport -- --env dev --cfn ../../cfn-drift.json
echo "exit code: $?"Expected: a Markdown table with one row for AuditBucket, and exit code 2 (operational) or 3 (security-relevant). The tool classes a change as security-relevant when the resource type or property path mentions encryption, policies, ingress or egress rules, KMS, logging, public access, deletion protection or retention, or when a resource was deleted. Versioning is not on that list, so this particular drift reports as operational (2). Extending the list is exercise 🟡.
Fixing drift
There are three honest remedies. Decide per finding, with a recorded reason.
| Remedy | Use when | How |
|---|---|---|
| Revert the resource | The change was not approved | Reverse it by hand, or deploy through a drift-aware change set |
| Accept the change | The change is right and was missing from code | Edit the template so it says the new value, review, deploy |
| Stop managing the property | Another automation owns it (Auto Scaling, for example) | Remove the property from the template and document the owner |
Drift-aware change sets (announced November 2025) add a third input to the change set: the actual state. A normal change set compares the new template with the last deployed template and ignores drift, so if your template has not changed it reports "no changes" while the bucket is still suspended. With the deployment mode REVERT_DRIFT the change set compares template, last deployment and live state, and plans the modifications needed to put the resource back as the template says.
aws cloudformation create-change-set --profile learn-sandbox --region us-east-1 \
--stack-name hl-m10-cfn-dev-audit --change-set-name revert-drift --change-set-type UPDATE \
--use-previous-template --deployment-mode REVERT_DRIFT \
--parameters ParameterKey=Environment,UsePreviousValue=true ParameterKey=NoncurrentVersionDays,UsePreviousValue=true
aws cloudformation wait change-set-create-complete --profile learn-sandbox \
--stack-name hl-m10-cfn-dev-audit --change-set-name revert-drift
aws cloudformation describe-change-set --profile learn-sandbox \
--stack-name hl-m10-cfn-dev-audit --change-set-name revert-drift \
--query "Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]" --output table
aws cloudformation execute-change-set --profile learn-sandbox \
--stack-name hl-m10-cfn-dev-audit --change-set-name revert-drift⚠ VERIFY the --deployment-mode option name and whether --use-previous-template may be combined with it in your CLI version (aws cloudformation create-change-set help). Known limits from the announcement: immutable properties cannot be reconciled this way, and write-only properties such as passwords are compared with the previous deployment value, not the live value.
If your CLI does not have the option, revert by hand and re-detect:
aws s3api put-bucket-versioning --bucket "hl-m10-cfn-dev-audit-$ACCOUNT-us-east-1" \
--versioning-configuration Status=Enabled --profile learn-sandboxInfrastructure as Code
The CDK deploys CloudFormation stacks, so everything above applies. The CDK CLI also has a cdk drift command that runs drift detection for the stacks of your app and prints the result (it appears in the CDK CLI command reference; ⚠ VERIFY its options and output for your CLI version):
cd infra/cdk
cdk drift hl-m10-cdk-dev-app -c owner=<you> -c imageTag=<tag> -c allowedIngressCidr=<your-ip>/32 --profile learn-sandboxA StackSet can itself be declared in the CDK with the L1 construct CfnStackSet (the snippet was compiled with Amazon.CDK.Lib 2.277.0; note that CfnStackSet exists in two namespaces, Amazon.CDK and Amazon.CDK.AWS.CloudFormation, so import only one). The StackSet below deploys the audit role template to an organizational unit, one account at a time, stopping at the first failure. IAM is global, so the role goes to one Region (for a regional baseline, list several Regions and keep RegionConcurrencyType sequential):
using Amazon.CDK;
using Constructs;
public sealed class BaselineStackSetStack : Stack
{
public BaselineStackSetStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
_ = new CfnStackSet(this, "AuditRoleStackSet", new CfnStackSetProps
{
StackSetName = "hl-baseline-audit-role",
PermissionModel = "SERVICE_MANAGED",
Capabilities = ["CAPABILITY_NAMED_IAM"],
TemplateBody = File.ReadAllText("cfn/audit-role.yaml"),
AutoDeployment = new CfnStackSet.AutoDeploymentProperty
{
Enabled = true,
RetainStacksOnAccountRemoval = false,
},
// These two properties are typed object (a list or a token), so use an explicit object[].
Parameters = new object[]
{
new CfnStackSet.ParameterProperty { ParameterKey = "SecurityAccountId", ParameterValue = "111122223333" },
new CfnStackSet.ParameterProperty { ParameterKey = "OrganizationId", ParameterValue = "o-exampleorgid" },
},
StackInstancesGroup = new object[]
{
new CfnStackSet.StackInstancesProperty
{
DeploymentTargets = new CfnStackSet.DeploymentTargetsProperty
{
OrganizationalUnitIds = ["ou-ab12-cd34ef56"],
},
Regions = ["us-east-1"],
},
},
OperationPreferences = new CfnStackSet.OperationPreferencesProperty
{
RegionConcurrencyType = "SEQUENTIAL",
FailureToleranceCount = 0,
MaxConcurrentCount = 1,
},
});
}
}The account ID, organization ID and OU ID above are fictional placeholders. This stack would be deployed in the management or delegated administrator account, never in a member account.
StackSets in depth
A StackSet is one template plus parameters that CloudFormation deploys as many stack instances: one per account and Region pair. You manage it from an administrator account.
| Choice | Self-managed permissions | Service-managed permissions |
|---|---|---|
| Who sets up trust | You create an administration role in the admin account and an execution role in each target account | AWS Organizations trusted access for StackSets does it |
| Targets | Individual account IDs | Organizational units (OUs) or the whole organization |
| New accounts | Not automatic | Auto-deployment deploys to new accounts in the OU and can remove stacks when an account leaves |
| Typical use | A few accounts outside Organizations | A bank's multi-account landing zone |
For service-managed permissions, enable trusted access once from the Organizations management account (aws cloudformation activate-organizations-access, ⚠ VERIFY the exact command and prerequisites), and prefer a delegated administrator account so that day-to-day StackSet work does not happen in the management account. Calls from a delegated administrator use --call-as DELEGATED_ADMIN.
Operation preferences protect you from pushing a bad change everywhere at once:
| Setting | Effect |
|---|---|
MaxConcurrentCount / MaxConcurrentPercentage | How many accounts in a Region are updated at the same time |
FailureToleranceCount / FailureTolerancePercentage | How many failures are allowed before the operation stops in that Region |
RegionConcurrencyType | SEQUENTIAL finishes a Region before starting the next; PARALLEL runs Regions together |
RegionOrder | The sequence of Regions, so a canary Region goes first |
Concurrency mode (STRICT_FAILURE_TOLERANCE or SOFT_FAILURE_TOLERANCE) | Whether the concurrent-account count shrinks as failures accumulate ⚠ VERIFY the exact behaviour |
The CLI form for a first rollout to a canary OU, one account at a time, stopping at the first failure:
aws cloudformation create-stack-set --stack-set-name hl-baseline-audit-role \
--template-body file://audit-role.yaml --permission-model SERVICE_MANAGED \
--auto-deployment Enabled=true,RetainStacksOnAccountRemoval=false \
--capabilities CAPABILITY_NAMED_IAM \
--parameters ParameterKey=SecurityAccountId,ParameterValue=111122223333 ParameterKey=OrganizationId,ParameterValue=o-exampleorgid \
--call-as DELEGATED_ADMIN --profile security-admin
aws cloudformation create-stack-instances --stack-set-name hl-baseline-audit-role \
--deployment-targets OrganizationalUnitIds=ou-ab12-cd34ef56 --regions us-east-1 \
--operation-preferences FailureToleranceCount=0,MaxConcurrentCount=1,RegionConcurrencyType=SEQUENTIAL \
--call-as DELEGATED_ADMIN --profile security-adminThis is design only in the course sandbox: a single learning account cannot be an Organizations management account. ⚠ VERIFY the shorthand syntax with aws cloudformation create-stack-instances help before use. Drift detection exists for StackSets as well: aws cloudformation detect-stack-set-drift --stack-set-name ... --call-as DELEGATED_ADMIN, which checks every stack instance.
Limits and gotchas (quotas verified 2026-11-18): 1,000 StackSets per administrator account; 100,000 stack instances per StackSet; and StackSets with service-managed permissions do not support templates that contain macros or transforms.
Complete code
The baseline template that the StackSet deploys. Save as audit-role.yaml. It passes cfn-lint 1.60.1 with no findings.
AWSTemplateFormatVersion: "2010-09-09"
Description: >-
Harbourline security baseline: a read-only audit role that the security account can assume.
Deployed to every member account and Region as a StackSet. Module 10, lesson 3.
Parameters:
SecurityAccountId:
Type: String
AllowedPattern: "^[0-9]{12}$"
Description: 12-digit ID of the central security account that may assume the role.
OrganizationId:
Type: String
AllowedPattern: "^o-[a-z0-9]{10,32}$"
Description: AWS Organizations ID. The caller must belong to this organization.
Resources:
AuditRole:
Type: AWS::IAM::Role
Properties:
RoleName: HarbourlineSecurityAudit
Description: Read-only security audit access for the Harbourline security team
MaxSessionDuration: 3600
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/SecurityAudit"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
AWS: !Sub "arn:${AWS::Partition}:iam::${SecurityAccountId}:root"
Action: "sts:AssumeRole"
Condition:
StringEquals:
"aws:PrincipalOrgID": !Ref OrganizationId
Outputs:
AuditRoleArn:
Description: ARN of the audit role in this account
Value: !GetAtt AuditRole.ArnFor the drift part, the complete code is the lab's DriftReport tool: labs/m10-environment-two-tools/src/Harbourline.Environment.DriftReport/. Its core is below. The parser reads the exact JSON the CLI prints and maps it into one shape that both tools can share.
using System.Text.Json;
namespace Harbourline.Environment.DriftReport;
public static class CloudFormationDriftParser
{
public static IReadOnlyList<DriftItem> Parse(string json)
{
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("StackResourceDrifts", out var drifts))
throw new FormatException("Expected a StackResourceDrifts array (output of describe-stack-resource-drifts).");
var items = new List<DriftItem>();
foreach (var d in drifts.EnumerateArray())
{
DriftKind? kind = d.GetProperty("StackResourceDriftStatus").GetString() switch
{
"MODIFIED" => DriftKind.Modified,
"DELETED" => DriftKind.Deleted,
_ => null, // IN_SYNC, NOT_CHECKED
};
if (kind is null) continue;
// ... read PropertyDifferences into PropertyDrift records, then build the DriftItem
}
return items;
}
}Code explained line by line
audit-role.yamlparameters.AllowedPatternrejects a mistyped account ID before CloudFormation creates anything in hundreds of accounts. A StackSet should validate hard because a mistake is multiplied.ManagedPolicyArnsusesAWS::Partitionand the AWS managed policySecurityAudit, a read-only set of permissions for security review.- The trust policy names the security account root as the principal (any identity in that account that is itself allowed
sts:AssumeRoleon this role can use it) and requiresaws:PrincipalOrgIDto equal your organization. Both checks must pass. RoleNameis fixed. A fixed name is what lets your audit tooling find the role in every account, but it means the template can be deployed only once per account. IAM is global, so a second Region would fail withAlreadyExists. That is why the examples target a single Region. For regional baselines (flow logs, Config recorders) you list several Regions and let the operation preferences order them.DriftReportparser.GetPropertythrows if the JSON lacks a field, which is what you want for a security tool: a surprise should be loud. Resources that areIN_SYNCorNOT_CHECKEDare skipped; onlyMODIFIEDandDELETEDbecome findings.- Exit codes.
0no drift,2operational,3security-relevant. A pipeline step can fail the build on3and open a ticket on2.
Security considerations
⚠ Learning shortcut — not for production
You detect and fix drift with your own SSO session and a CLI command that changes the bucket "by hand". In production, scheduled detection runs under a read-only role, results go to a central store (S3 with Object Lock, or Security Hub), and fixing is a pull request, not a hand edit. Console write access in production is removed or limited to a monitored break-glass role.
- Drift is a security signal. A security group rule that appears outside code deserves the same attention as a CloudTrail alert. Join the two: CloudTrail says who, drift detection says what is now different. See Audit logging and evidence collection.
- Complement drift detection with preventive guardrails. Service Control Policies and permission boundaries stop the change; drift detection catches what slips through. See Boundaries, SCPs, RCPs and resource policies.
- AWS Config can also check configuration continuously with managed rules, including a rule that reports stacks whose drift status is
DRIFTED(⚠ VERIFY the managed rule namecloudformation-stack-drift-detection-check), and gives you a timeline of every configuration change. See AWS Config and conformance packs. - StackSets are powerful. The administrator role can create IAM roles in every account. Restrict who can run StackSet operations, require reviews for template changes, and roll out to a canary OU first.
- Do not claim compliance. A clean drift report says the deployment matches your template. It does not say the template meets a control. Your compliance team decides that.
Banking use case
Harbourline runs drift detection on every production stack daily at 06:00 UTC. A scheduled job calls the three CLI commands, runs the DriftReport tool, and uses the exit code: 0 is silent, 2 opens a ticket for the owning team within a business day, 3 pages the security on-call. Each finding must be closed with one of three recorded decisions: reverted, accepted by pull request, or "owned by another automation" with a code change that removes the property. The same weekly job reports the drift count per team on the engineering dashboard. The audit baseline (the role in this lesson) is a StackSet applied to the "Workloads" OU, so a newly vended account is auditable within minutes.
Common mistakes
- Running drift detection once and calling the environment verified. Schedule it.
- Treating
IN_SYNCas "secure". Drift only compares declared properties of supported types. - Reverting automatically without review. An automatic revert can undo an emergency fix that is keeping production up. Human decision first; automate only the safest classes.
- Letting Auto Scaling and the template fight. Do not declare
DesiredCountfor a service with Auto Scaling, or declare it and accept the noise. - Pushing a StackSet to all accounts at once. Use a canary OU, sequential Regions and
FailureToleranceCount=0for the first rollout. - Deploying IAM roles with fixed names to several Regions. IAM is global; the second Region fails.
- Forgetting that deleting an account's stack instance can delete its resources.
RetainStacksandRetainStacksOnAccountRemovalexist; decide deliberately.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
DETECTION_FAILED | The detecting identity lacks read permission for a resource type | Grant the matching Describe* or Get* permissions, then retry |
Resource shows NOT_CHECKED | Resource type not supported for drift detection | Check the supported-types list; cover it with an AWS Config rule |
Change was made but drift shows IN_SYNC | The property is not in the template, or the type does not compare it | Add the property to the template so it is compared |
describe-stack-resource-drifts returns an empty list | Detection has not run or the filter excludes everything | Run detect-stack-drift, wait for completion, drop the filter |
| Normal change set says "no changes" while a resource drifted | A standard change set ignores live state | Use a drift-aware change set (REVERT_DRIFT) or revert manually |
StackSet instance OUTDATED or FAILED | The target account's execution failed (permission, quota, name clash) | list-stack-set-operation-results shows the per-account reason |
AlreadyExists for the IAM role in the second Region | IAM is global | Deploy IAM baselines to one Region only |
Trusted access not enabled | Organizations trusted access for StackSets is off | Enable it from the management account, then retry |
Cost and cleanup
Cost: credits. Drift detection and StackSets themselves are free. The only charges are the resources you deploy (cents for an empty bucket and a short-lived key). The StackSet part is design-only.
Tear down the stack as described in CloudFormation fundamentals: delete the stack, empty and delete the two buckets, schedule the key for deletion. Remove your local cfn-drift.json; it contains resource IDs.
rm -f cfn-drift.json
aws resourcegroupstaggingapi get-resources --profile learn-sandbox --region us-east-1 \
--tag-filters Key=Lab,Values=m10-cfn --query "ResourceTagMappingList[].ResourceARN"Exercises
- 🟢 Guided: deploy the stack, detect a clean baseline, suspend versioning, detect again, save the JSON and run the DriftReport tool. Note the exit code. Restore versioning and detect again to confirm
IN_SYNC. - 🟡 Challenge: extend
DriftItem.SecurityPropertiesin the lab so that a change under/VersioningConfigurationcounts as security-relevant, and add an xUnit test that fails before your change. Rundotnet test --solution EnvironmentTwoTools.slnx. - 🔴 Live problem: the daily drift job reports 14 findings across 6 production stacks on Monday morning: 9 are ECS desired counts changed by Auto Scaling, 3 are tags added by an AWS service, 1 is a security group rule opened by a vendor, and 1 is a deleted CloudWatch alarm. Write the triage plan: what you do for each class, in what order, who decides, how you stop the noise, and what you change so the vendor rule cannot happen again.
Assignment
Add a drift/ folder to your portfolio repository with a scheduled GitHub Actions workflow (or a design document if you do not use Actions) that runs detection, uses the DriftReport exit code, and posts the Markdown report as a job summary. Include the three recorded decisions as a template for the closing comment on each finding.
Solutions
The baseline describe-stack-drift-detection-status shows DETECTION_COMPLETE and IN_SYNC. After suspending versioning, the second run shows DRIFTED with DriftedStackResourceCount: 1, and describe-stack-resource-drifts lists AuditBucket with /VersioningConfiguration/Status expected Enabled, actual Suspended, type NOT_EQUAL. The report exits with 2 (operational) because versioning is not in the tool's security list. After restoring versioning the stack returns to IN_SYNC. The important lesson is that detection is a measurement: baseline, change, measure, restore, measure.
Add "VersioningConfiguration" to the SecurityProperties array in DriftItem.cs. In DriftReportTests, build a DriftItem with a PropertyDrift("/VersioningConfiguration/Status", "Enabled", "Suspended", "NOT_EQUAL") for an AWS::S3::Bucket and assert IsSecurityRelevant is true. Run the test first without the change to see it fail (a test that never failed proves nothing), then make the change. Versioning protects against overwrites and deletes, so turning it off on an evidence bucket is a security-relevant change in a bank.
Triage by risk. First the security group rule: find out who opened it and why (CloudTrail), revert it through the pipeline unless the vendor test is still approved and recorded, then close the process gap (SCP or permission boundary that blocks 0.0.0.0/0 rules; vendor access through a bastion or a time-boxed approved rule). Second the deleted alarm: recreate it by redeploying, because a missing alarm means blind production. Third the 9 desired counts: remove DesiredCount from the templates and let Auto Scaling own it, which ends the noise. Fourth the 3 tags: add the service's tag keys to an ignore list or manage them in code. Decisions belong to the stack owner; security reviews the group rule. Report the closure rate to the engineering leadership weekly.
Knowledge check
Answer: Not necessarily. A standard change set compares the new template with the last deployed template, so if the template did not change, the rule stays. You need drift detection to see it and a drift-aware change set (or a manual revert) to undo it.
Answer: The live properties of supported resources with the properties declared in the stack's template. It does not judge whether the template itself is secure.
Answer: Trust is created through Organizations, targets are OUs, and auto-deployment applies the baseline to new accounts. You avoid hand-building execution roles in every account.
Answer: A low failure tolerance (for example zero), a low maximum concurrency, and sequential Region deployment with a canary Region first.
Answer: Accept it with terraform apply -refresh-only (state now matches reality, and you then update the code to match), or revert reality with a normal terraform apply so it matches the configuration.
Interview questions
- "How do you detect and handle configuration drift in a regulated environment?" Scheduled detection under a read-only role, classification of findings by risk, recorded decisions (revert, accept, hand over to another automation), remediation through pull requests, and preventive guardrails (SCPs, restricted console access) so the same drift cannot recur.
- "What is the difference between drift detection and AWS Config?" Drift detection compares live resources to your template for stack-managed resources. Config records configuration history for all supported resources and evaluates rules you choose; it knows nothing about your templates.
- "How would you roll a baseline out to 300 accounts?" A service-managed StackSet targeting OUs, auto-deployment for new accounts, a canary OU first, sequential Regions, zero failure tolerance for the first wave, and drift detection for the StackSet afterwards.
- "Can IaC and Auto Scaling coexist?" Yes, if the template does not declare the property Auto Scaling controls (such as desired count).
Certification practice
A company must deploy an IAM baseline role to all current and future accounts in an organizational unit across two Regions, with minimal manual setup. Which approach meets this?
A. Create a stack manually in each account. B. A CloudFormation StackSet with service-managed permissions and auto-deployment enabled for the OU. C. A StackSet with self-managed permissions and a list of account IDs maintained by a spreadsheet. D. A Lambda function that creates the role through the console API.
Answer: B. Service-managed permissions with auto-deployment deploy to existing accounts and to accounts added later. A and C are manual and miss new accounts. D is unnecessary custom code. (Remember that IAM is global, so the IAM role itself should be deployed in one Region.)
An operator suspects someone changed an S3 bucket in a stack through the console. Which action shows exactly which properties differ from the template?
A. aws cloudformation describe-stacks
B. Run drift detection on the stack and view the resource drift details.
C. aws cloudformation get-template
D. Execute the last change set again.
Answer: B. Drift detection returns expected and actual property values. A shows stack metadata, C the stored template, and D does nothing if the template is unchanged.
A security team wants production resources that were changed manually to be detected daily and, only after approval, restored to the template's state. Which design fits best?
A. Enable automatic remediation that reverts every drifted resource immediately. B. A scheduled drift detection job with notifications, plus a drift-aware change set reviewed and executed through the pipeline after approval. C. Disable the console for all engineers permanently with no break-glass access. D. Delete and recreate the stack nightly.
Answer: B. Detection is automated, the revert is reviewed. A can undo emergency fixes. C removes the ability to respond to incidents. D destroys data and availability.
Completion checklist
- I measured a clean baseline, caused drift, detected it and read the property difference
- I ran the DriftReport tool and understand its exit codes
- I can name the three remedies and when to use each
- I can design a StackSet with safe operation preferences
- I tore down the stack and confirmed nothing is billing
Key takeaways
- Drift is the gap between code and reality; detect it on a schedule and decide per finding.
- CloudFormation compares declared properties of supported resource types; it is a measurement, not a guard.
- A standard change set ignores drift; a drift-aware change set (
REVERT_DRIFT) does not. - Terraform uses
plan -refresh-only; the CDK hascdk drift. - StackSets with service-managed permissions and sensible operation preferences are how a bank deploys a baseline to many accounts safely.
Related lessons and next steps
- Previous: AWS CloudFormation fundamentals
- Next: AWS CDK in C#: first stack
- Later: Landing-zone automation overview and Module 15
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
AWS CloudFormation fundamentals
Write a CloudFormation template for a private, KMS-encrypted audit bucket, lint it locally, deploy it through a reviewed change set, read what happens on rollback, and protect data with deletion policies.
AWS CDK in C#: your first stack
Create a CDK app in C#, understand the construct tree, and use cdk synth, cdk diff, cdk deploy and cdk destroy to build the audit-evidence bucket from the CloudFormation lesson as typed, testable code.