AWS Builder Center
Detecting and Fixing Noncompliant Resources with AWS Config

Detecting and Fixing Noncompliant Resources with AWS Config

Use AWS Config to catch resource drift and react two ways: route risky findings to a human, auto-fix the safe ones with SSM Automation.

Developer Advocate @ AgilityFeat & WebRTC.ventures
Most cloud incidents don't start with a breach. They start with a small, routine change that quietly leaves something exposed. Picture a storage bucket that goes public at 2am, not through an attack but through a deploy script that flipped one setting, or a teammate loosening a policy "just to test something." By the time a quarterly audit finds it, the data has been exposed for weeks. It's not that no one cared about compliance, it's that compliance was a snapshot taken occasionally while your account changed continuously underneath it.
Closing that gap starts with noticing drift the moment it happens.  AWS Config  does that continuously: it records resource configurations, evaluates them against rules, and marks each resource compliant or not. The interesting question is what you do with a  NON_COMPLIANT  result, and there are two good answers. For risky or context-dependent problems, you route the finding to a human. For well-understood, low-risk problems, you let Config fix them automatically. This post builds both paths off the same detection engine.

The Resource That Drifts at 2am

The structural flaw in manual compliance is that it only checks your resources at single points in time. You audit on a schedule, but resources keep changing whenever someone deploys, clicks, or runs a script, so everything that happens between two audits is a blind spot:
  • A bucket's Block Public Access setting gets disabled and a public policy attached.
  • A security group opens SSH to the whole internet.
  • An EBS volume is created unencrypted.
Each is a window of exposure that lasts until the next audit catches it, if it ever does. What you want instead is a system that watches continuously and reacts the moment something drifts. That starts with understanding how Config observes your account in the first place.

How Config Sees Your Account

AWS Config uses a configuration recorder in each Region to capture configuration items (metadata about supported AWS resources) and delivers them to an S3 bucket through a delivery channel. It then evaluates those recorded resources with Config rules. ( AWS docs ) That's three pieces, and each one has a distinct job:
  • Configuration recorder: detects changes to resources and captures each as a configuration item.
  • Delivery channel: ships configuration history and snapshots to an S3 bucket (SNS notifications optional).
  • Rules: evaluate resources against desired state and mark each  COMPLIANT  or  NON_COMPLIANT . Rules come in two flavors: AWS managed rules (prebuilt, hundreds of them) and custom rules (your own logic).
A rule can evaluate in two ways:
  • A change-triggered evaluation runs the moment a resource's configuration changes, which is the fast path that reacts to drift as it happens.
  • A periodic evaluation runs on a schedule you set, which is the backstop that catches resources already sitting noncompliant.
You get the scheduled path by setting a snapshot delivery frequency on the delivery channel and an execution frequency on the rule; without those, a rule only reacts to changes.


Everything downstream hangs off that  NON_COMPLIANT  signal. The rest of this post wires both branches: an alert path for a security group that opens SSH to the world, and an auto-remediation path for a public S3 bucket.

Enable Config

Config needs an IAM service role (to read your resources) and an S3 bucket (to store history). Let's set up the role first. It trusts the Config service and carries the AWS managed  AWS_ConfigRole  policy.
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

# A bucket for Config to deliver configuration history/snapshots to
aws s3 mb s3://config-data-${ACCOUNT_ID}

# Trust policy: let the Config service take on this role
cat > config-trust.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Principal": { "Service": "config.amazonaws.com" }, "Action": "sts:AssumeRole" }
]
}
EOF

aws iam create-role --role-name ConfigServiceRole \
--assume-role-policy-document file://config-trust.json

# AWS_ConfigRole grants read access to describe your resources
aws iam attach-role-policy --role-name ConfigServiceRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AWS_ConfigRole

# Plus permission to write to the delivery bucket
aws iam put-role-policy --role-name ConfigServiceRole \
--policy-name S3Delivery \
--policy-document "{
\"Version\": \"2012-10-17\",
\"Statement\": [{
\"Effect\": \"Allow\",
\"Action\": [\"s3:PutObject\", \"s3:GetBucketAcl\"],
\"Resource\": [
\"arn:aws:s3:::config-data-${ACCOUNT_ID}\",
\"arn:aws:s3:::config-data-${ACCOUNT_ID}/*\"
]
}]
}"
Now create the recorder and delivery channel, then start recording. Config bills per configuration item recorded, so we scope the recorder to only the two resource types this lab uses: S3 buckets and EC2 security groups. In a real baseline you'd record all supported resources (with  includeGlobalResourceTypes=true  for global types like IAM), since drift can happen anywhere:
# Recorder: scope to the two resource types the lab uses, to keep costs down
aws configservice put-configuration-recorder \
--configuration-recorder name=default,roleARN=arn:aws:iam::${ACCOUNT_ID}:role/ConfigServiceRole \
--recording-group '{"allSupported":false,"resourceTypes":["AWS::S3::Bucket","AWS::EC2::SecurityGroup"]}'

# Delivery channel: where configuration items land. The snapshot delivery
# frequency also sets how often Config evaluates rules on a schedule.
aws configservice put-delivery-channel --delivery-channel '{
"name": "default",
"s3BucketName": "config-data-'${ACCOUNT_ID}'",
"configSnapshotDeliveryProperties": { "deliveryFrequency": "One_Hour" }
}'

# Recording is off until you explicitly start it
aws configservice start-configuration-recorder --configuration-recorder-name default
Config is now watching S3 buckets and security groups in the Region. Next we give each one a rule and a reaction, starting with the path where a human stays in the loop.

Path 1: Detect and Alert

Some drift you don't want a machine to fix on its own. A security group opening SSH to the world might be a genuine mistake, or it might be a temporary rule a teammate added for a legitimate reason. Automatically deleting it could break someone's access mid-task. This is a case for detect-and-alert: Config flags the problem and routes it to a person who has the context to decide.
We'll use the AWS managed rule  restricted-ssh  (identifier  INCOMING_SSH_DISABLED ), which is  COMPLIANT  when no security group allows inbound SSH from  0.0.0.0/0  or  ::/0 , and  NON_COMPLIANT  otherwise. ( AWS docs )
aws configservice put-config-rule \
--config-rule '{
"ConfigRuleName": "restricted-ssh",
"Source": {
"Owner": "AWS",
"SourceIdentifier": "INCOMING_SSH_DISABLED"
},
"Scope": { "ComplianceResourceTypes": ["AWS::EC2::SecurityGroup"] }
}'
The alert itself travels over two services: Amazon SNS carries the notification to your email, and Amazon EventBridge listens for the compliance event and forwards it to SNS. Create the topic first and subscribe your email. SNS sends a confirmation message; open it and click the link, or the topic won't deliver anything:
# Create the topic and capture its ARN
TOPIC_ARN=$(aws sns create-topic --name config-compliance-alerts \
--query TopicArn --output text)

# Subscribe your email (replace with your address)
aws sns subscribe \
--topic-arn ${TOPIC_ARN} \
--protocol email \
--notification-endpoint you@example.com

# Check your inbox and click the confirmation link before continuing
EventBridge needs permission to publish to the topic. Add a topic policy that lets the EventBridge service principal call  sns:Publish :
aws sns set-topic-attributes \
--topic-arn ${TOPIC_ARN} \
--attribute-name Policy \
--attribute-value '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowEventBridgePublish",
"Effect": "Allow",
"Principal": { "Service": "events.amazonaws.com" },
"Action": "sns:Publish",
"Resource": "'${TOPIC_ARN}'"
}]
}'
Now the EventBridge rule. Config emits a  Config Rules Compliance Change  event every time a resource's compliance status changes. The event pattern below matches only our SSH rule flipping to  NON_COMPLIANT , so you're paged for the thing you care about and nothing else:
# Rule: match our SSH rule turning NON_COMPLIANT
aws events put-rule \
--name config-ssh-noncompliant \
--event-pattern '{
"source": ["aws.config"],
"detail-type": ["Config Rules Compliance Change"],
"detail": {
"messageType": ["ComplianceChangeNotification"],
"configRuleName": ["restricted-ssh"],
"newEvaluationResult": { "complianceType": ["NON_COMPLIANT"] }
}
}'

# Target: send matching events to the SNS topic
aws events put-targets \
--rule config-ssh-noncompliant \
--targets "Id"="sns","Arn"="${TOPIC_ARN}"
With the wiring in place, trip it. Create a security group and add an SSH rule open to the internet, which is exactly the drift the rule watches for:
# A security group in your default VPC
VPC_ID=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true \
--query 'Vpcs[0].VpcId' --output text)
SG_ID=$(aws ec2 create-security-group \
--group-name demo-open-ssh \
--description "Demo: SSH open to the world" \
--vpc-id ${VPC_ID} \
--query GroupId --output text)

# Open SSH (port 22) to 0.0.0.0/0, the noncompliant change
aws ec2 authorize-security-group-ingress \
--group-id ${SG_ID} \
--protocol tcp --port 22 --cidr 0.0.0.0/0
Within a few minutes, the change-triggered evaluation marks the security group  NON_COMPLIANT , EventBridge catches the compliance event, and SNS emails you. You can confirm the evaluation independent of the email:
aws configservice get-compliance-details-by-config-rule \
--config-rule-name restricted-ssh \
--compliance-types NON_COMPLIANT \
--query 'EvaluationResults[*].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId'

# expect an array containing your security group id:
# [ "sg-0abc123..." ]
A human now has the finding and the context to act, which is the whole point of this path. Next we handle the other kind of problem, the one safe enough to fix without waiting for anyone

Path 2: Detect and Auto-Remediate

A public S3 bucket is the opposite case. The fix is unambiguous (re-enable Block Public Access), reversible, and almost never something you'd leave in place on purpose. That makes it a good candidate for auto-remediation, where Config corrects the resource with no human in the path.
Let's add the rule first.  s3-bucket-public-read-prohibited  checks a bucket's Block Public Access settings, policy, and ACL. ( AWS docs ) It supports both trigger types, so we set  MaximumExecutionFrequency  to add scheduled evaluation on top of the change-triggered one. That pairs with the delivery channel's snapshot frequency to make the periodic backstop work:
aws configservice put-config-rule \
--config-rule '{
"ConfigRuleName": "s3-no-public-read",
"Source": {
"Owner": "AWS",
"SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED"
},
"Scope": { "ComplianceResourceTypes": ["AWS::S3::Bucket"] },
"MaximumExecutionFrequency": "One_Hour"
}'
Create the bucket now, but leave it locked down. S3 blocks public access by default, so a fresh bucket is already compliant:
BUCKET="config-demo-public-${ACCOUNT_ID}"
aws s3 mb s3://${BUCKET}
Auto-remediation links a remediation action (an SSM Automation document) with the rule and runs it automatically when a resource is noncompliant. ( AWS docs ) AWS provides the Config-specific document  AWSConfigRemediation-ConfigureS3BucketPublicAccessBlock , which lets you set all four Block Public Access flags explicitly. That matters here: we're about to expose the bucket through a bucket policy, so the fix needs  BlockPublicPolicy  and  RestrictPublicBuckets  on, not just the ACL-related flags.
The remediation needs an IAM role that SSM Automation can take on. SSM must be able to adopt it, and it should carry only the permissions the document calls:
# Trust policy: let SSM take on this remediation role
cat > remediation-trust.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Action": "sts:AssumeRole" }
]
}
EOF

aws iam create-role --role-name ConfigRemediationRole \
--assume-role-policy-document file://remediation-trust.json

# Least privilege: only the S3 public-access-block actions the document calls
aws iam put-role-policy --role-name ConfigRemediationRole \
--policy-name S3PublicAccessBlock \
--policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:PutBucketPublicAccessBlock", "s3:GetBucketPublicAccessBlock"],
"Resource": "*"
}]
}'

# let the role propagate
Now wire the remediation to the rule, guardrail first.  TargetId  names the SSM document,  BucketName  is populated from the noncompliant resource via  RESOURCE_ID , the four  StaticValue  flags force every Block Public Access setting on, and  Automatic: true  makes it fire without a human:
aws configservice put-remediation-configurations \
--remediation-configurations '[{
"ConfigRuleName": "s3-no-public-read",
"TargetType": "SSM_DOCUMENT",
"TargetId": "AWSConfigRemediation-ConfigureS3BucketPublicAccessBlock",
"Parameters": {
"BucketName": { "ResourceValue": { "Value": "RESOURCE_ID" } },
"AutomationAssumeRole": {
"StaticValue": { "Values": ["arn:aws:iam::'${ACCOUNT_ID}':role/ConfigRemediationRole"] }
},
"BlockPublicAcls": { "StaticValue": { "Values": ["true"] } },
"IgnorePublicAcls": { "StaticValue": { "Values": ["true"] } },
"BlockPublicPolicy": { "StaticValue": { "Values": ["true"] } },
"RestrictPublicBuckets": { "StaticValue": { "Values": ["true"] } }
},
"Automatic": true,
"MaximumAutomaticAttempts": 3,
"RetryAttemptSeconds": 60
}]'
With the remediation armed, create the drift. Make the bucket publicly readable, which takes two steps since we first turn off the default Block Public Access and then attach a public-read policy:
# 1. Disable Block Public Access so a public policy can take effect
aws s3api put-public-access-block \
--bucket ${BUCKET} \
--public-access-block-configuration \
"BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

# 2. Attach a policy granting public read on all objects
aws s3api put-bucket-policy --bucket ${BUCKET} --policy "{
\"Version\": \"2012-10-17\",
\"Statement\": [{
\"Sid\": \"PublicRead\",
\"Effect\": \"Allow\",
\"Principal\": \"*\",
\"Action\": \"s3:GetObject\",
\"Resource\": \"arn:aws:s3:::${BUCKET}/*\"
}]
}"
Because the remediation was already wired, that change is a fresh drift event the change-triggered evaluation picks up right away. Config records it, marks the bucket  NON_COMPLIANT , and launches the SSM document on its own, usually within a few minutes.
Give it a few minutes, then read the bucket's public access block. All four flags should be back to  true , set by Config rather than by you:
# No trigger command; Config runs the remediation on its own
aws s3api get-public-access-block --bucket ${BUCKET} \
--query 'PublicAccessBlockConfiguration'

# expect every flag true:
#{
# "BlockPublicAcls": true,
# "IgnorePublicAcls": true,
# "BlockPublicPolicy": true,
# "RestrictPublicBuckets": true
#}
Confirm the rule agrees, which should now read  COMPLIANT :
aws configservice describe-compliance-by-config-rule \
--config-rule-names s3-no-public-read \
--query 'ComplianceByConfigRules[0].Compliance.ComplianceType' \
--output text
Config detected the drift, SSM Automation fixed it, and the bucket is back to  COMPLIANT , with nobody in the path.

Auto-Remediation Best Practices

  • Know which path you're on, and expect a delay. Change-triggered remediation follows a drift event by minutes, because Config has to record the change and evaluate it first ( AWS docs ). The scheduled path runs only as often as the frequency you set (down to one hour) and only fixes an already-noncompliant resource if you configured both the delivery channel snapshot frequency and the rule's  MaximumExecutionFrequency . Either way the exposure window is short but never zero. For a hard guarantee, pair Config with a preventive control like a  Service Control Policy , which stops the drift from happening rather than correcting it afterward.
  • Keep the  AutomationAssumeRole  least-privilege. The role should grant only the specific actions the remediation document calls. A broad role turns a remediation into a lateral-movement path if the document is ever misused.
  • Cap retries with  MaximumAutomaticAttempts  and  RetryAttemptSeconds . If a resource can't be fixed, you want Config to raise a remediation exception, not hammer it forever. The default is 5 attempts; set it deliberately.
  • Scope rules tightly. Use  ComplianceResourceTypes  (and resource tags where supported) so a rule evaluates only what it should, keeping evaluation cost and noise down.
  • Group rules with conformance packs. For a real baseline, deploy a conformance pack (a collection of rules and remediations as one unit) rather than wiring rules one at a time. AWS publishes packs mapped to frameworks like CIS and PCI DSS.

Cleanup

Config bills per rule evaluation and per configuration item recorded, so leave this lab running and the costs add up quietly. Tear it down in reverse order of how you built it, stopping the recorder before you delete the delivery channel:
# 1. Alert path: EventBridge target and rule, then the SNS topic
aws events remove-targets --rule config-ssh-noncompliant --ids sns
aws events delete-rule --name config-ssh-noncompliant
aws sns delete-topic --topic-arn ${TOPIC_ARN}

# 2. Remediation path: the remediation wiring, then the rule.
# Note the CLI asymmetry: you create with the plural
# put-remediation-configurations but delete with the singular command below.
aws configservice delete-remediation-configuration \
--config-rule-name s3-no-public-read
aws configservice delete-config-rule --config-rule-name s3-no-public-read
aws configservice delete-config-rule --config-rule-name restricted-ssh

# 3. Stop recording, then tear down the delivery channel and recorder
aws configservice stop-configuration-recorder --configuration-recorder-name default
aws configservice delete-delivery-channel --delivery-channel-name default
aws configservice delete-configuration-recorder --configuration-recorder-name default

# 4. Remove the IAM roles (inline policies must go first)
aws iam delete-role-policy --role-name ConfigServiceRole --policy-name S3Delivery
aws iam detach-role-policy --role-name ConfigServiceRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AWS_ConfigRole
aws iam delete-role --role-name ConfigServiceRole

aws iam delete-role-policy --role-name ConfigRemediationRole --policy-name S3PublicAccessBlock
aws iam delete-role --role-name ConfigRemediationRole

# 5. Delete the demo security group and both buckets
aws ec2 delete-security-group --group-id ${SG_ID}
aws s3 rb s3://config-demo-public-${ACCOUNT_ID} --force
aws s3 rb s3://config-data-${ACCOUNT_ID} --force

Wrapping Up

AWS Config turns compliance from an occasional snapshot into a continuous signal, and that signal is the foundation for two complementary reactions. Route the risky, context-dependent findings to a human through EventBridge and SNS. Hand the safe, mechanical ones to SSM Automation and let them fix themselves. You built both: an SSH-open security group that pages an operator, and a public bucket that quietly pulls itself back to compliant.
The next step is to stop wiring rules one at a time. Pick a conformance pack that matches a framework you care about, such as  Operational Best Practices for Amazon S3 , CIS, or PCI DSS. Deploy it with remediations and alerts attached, and you have a compliance baseline that detects, notifies, and self-heals across every resource it covers.
Interested on keeping your AWS resources compliant with your standards?  Let's talk! 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article