Production-grade guide to cloud security scanning covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Cloud security scanning is the automated process of identifying, assessing, and reporting security risks in cloud infrastructure and services. It matters most during continuous integration, deployment, and runtime monitoring—particularly when provisioning new cloud environments, rolling out new services, or responding to security incidents. It is the backbone of proactive cloud security, catching misconfigurations, vulnerabilities, and compliance gaps before they become breaches.
Before deploying cloud resources, validate the configuration code using tools that analyze infrastructure-as-code templates. The scanning phase begins at the code commit, ensuring that every change to terraform/ or cloudformation/ directories is vetted for security best practices and compliance.
Use tfsec to analyze Terraform configurations for common security misconfigurations and best practices. The tool runs as a pre-commit hook and CI step.
tfsec --config-path .tfsec.json --enable-aws-iam-policy-optimization --output json --format github
The configuration file .tfsec.json defines rules, thresholds, and custom checks:
{
"rules": {
"AWS-001": {
"enabled": true,
"severity": "high",
"description": "Ensure all S3 buckets are encrypted"
},
"AWS-004": {
"enabled": true,
"severity": "medium",
"description": "Enable logging for S3 buckets"
}
},
"outputs": {
"json": true,
"github": true,
"sarif": false
},
"thresholds": {
"critical": 5,
"high": 10,
"medium": 20
}
}
A failed scan produces a GitHub check with annotations and a summary:
{
"check": "cloud-security-scan",
"status": "failure",
"summary": "2 critical, 5 high, 3 medium findings",
"annotations": [
{
"path": "modules/s3/main.tf",
"start_line": 12,
"end_line": 12,
"message": "S3 bucket should have versioning enabled",
"annotation_level": "warning"
},
{
"path": "environments/prod/main.tf",
"start_line": 20,
"end_line": 20,
"message": "Bucket 'logs-prod' is not encrypted at rest",
"annotation_level": "error"
}
]
}
For AWS CloudFormation, use cfn-lint to validate templates against a schema and custom rules:
cfn-lint -t templates/app.yaml -f json --config-file .cfnlintrc
The configuration file .cfnlintrc defines rule sets and custom checks:
rules:
E2001: # Bucket should have public access blocked
severity: error
description: "Block public access on all S3 buckets"
params:
public_access: true
W2003: # Ensure all parameters are documented
severity: warning
description: "Missing description for parameter"
params:
required: true
min_length: 5
A common failure is misaligned AWS::S3::Bucket declarations: PublicAccessBlock is a nested object, but the linting tool reports PublicAccessBlock: true, which is incorrect. The actual structure must be:
Resources:
LogBucket:
Type: AWS::S3::Bucket
Properties:
PublicAccessBlock:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
Cloud environments change over time. Scanning must detect drift from expected configurations, especially in production.
Use opa to evaluate live cloud resources against expected policies derived from IaC. Run OPA as a scheduled job or on-demand.
opa run --server --set=plugins.kubernetes.config.file=/etc/opa/k8s.yaml
Define a policy in policies/cloud-security.rego:
package cloud.security
import data.aws
# Ensure all EKS clusters have at least one worker node group
aws.eks_cluster_with_min_nodes[cluster] {
cluster = input.aws.eks.clusters[_]
count(cluster.node_groups) >= 2
}
# Validate all EC2 instances have a specific tag
aws.ec2.instance.has_required_tags[instance] {
instance = input.aws.ec2.instances[_]
instance.tags["Environment"] == "production"
instance.tags["Owner"] != ""
}
# Check if all S3 buckets use server-side encryption
aws.s3.bucket.has_sse[bucket] {
bucket = input.aws.s3.buckets[_]
bucket.server_side_encryption_configuration != null
bucket.server_side_encryption_configuration.rules[0].apply_server_side_encryption_by_default.sse_algorithm == "AES256"
}
The OPA server exposes an API endpoint that accepts a JSON payload:
{
"aws": {
"ec2": {
"instances": [
{
"id": "i-12345678",
"tags": {
"Environment": "production",
"Owner": "engineering"
}
}
]
},
"eks": {
"clusters": [
{
"name": "prod-cluster",
"node_groups": []
}
]
},
"s3": {
"buckets": [
{
"name": "logs-prod",
"server_side_encryption_configuration": {
"rules": [
{
"apply_server_side_encryption_by_default": {
"sse_algorithm": "AES256"
}
}
]
}
}
]
}
}
}
An evaluation request returns:
{
"result": {
"aws.eks_cluster_with_min_nodes": [],
"aws.ec2.instance.has_required_tags": [
"i-12345678"
],
"aws.s3.bucket.has_sse": [
"logs-prod"
]
},
"errors": [
{
"message": "Missing server-side encryption configuration for bucket 'backup-data'",
"code": "S3-001"
}
]
}
In a GitLab CI pipeline, use opa to evaluate drift after a deployment:
cloud-drift-check:
image: openpolicyagent/opa
script:
- |
opa eval --format json \
--data policies/cloud-security.rego \
--input <(curl -s "https://api.aws.com/v1/resources?region=us-east-1") \
--output-file drift-results.json
- |
jq -r '.result | to_entries | .[] | select(.value == false) | .key' drift-results.json
# Output: aws.eks_cluster_with_min_nodes
artifacts:
paths:
- drift-results.json
expire_in: 1 week
only:
- main
A missed node_groups field in the EKS cluster definition leads to an unhandled null value, causing the rule to fail silently. The error unexpected type null for array appears in logs, revealing that cluster.node_groups is null instead of [].
Continuous scanning of running cloud resources ensures that security policies are enforced and observed in real time.
Use a cron job to scrape cloud APIs and detect new or misconfigured resources.
# daily-cloud-scan.sh
#!/bin/bash
set -euo pipefail
LOGFILE="/var/log/cloud-scan/$(date +%Y-%m-%d).log"
exec > "$LOGFILE" 2>&1
# List all S3 buckets and check for encryption
aws s3api list-buckets \
--query 'Buckets[*].[Name, Tags]' \
--output json \
| jq -r '
.[] |
select(.[] | .[] | select(.Key == "Environment" and .Value == "production")) |
.[0] as $name |
[ $name,
(aws s3api get-bucket-encryption --bucket $name --query "ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm" --output text) ] |
@csv
' \
> /var/tmp/encryption-missing.csv
# Identify untagged EC2 instances
aws ec2 describe-instances \
--query 'Reservations[*].Instances[*].[InstanceId, Tags[?Key==`Environment`].Value]' \
--output json \
| jq -r '
.[] |
select(.[1] == null) |
[ .[0], "missing-environment-tag" ] |
@csv
' \
>> /var/tmp/untagged-instances.csv
The script runs hourly and uploads findings to a central data store:
# Upload results to a PostgreSQL table
psql -c "
COPY cloud_scan_results (resource_type, resource_id, status, check, detected_at)
FROM '/var/tmp/encryption-missing.csv'
WITH (FORMAT csv, HEADER true, DELIMITER ',');
"
Use a simple watch-based alerting system to monitor scan output:
# monitor-cloud-scan.sh
#!/bin/bash
LOGFILE="/var/log/cloud-scan/alerts.log"
while true; do
# Run scan and check for new issues
./daily-cloud-scan.sh
# Compare current results with previous
diff -u /var/tmp/previous-results.csv /var/tmp/encryption-missing.csv \
| grep '^+' \
| while IFS= read -r line; do
echo "$(date): New unencrypted S3 bucket: $line" >> "$LOGFILE"
# Send alert via HTTP
curl -X POST https://alerts.cloud.example.com/api/v1/alert \
-H "Content-Type: application/json" \
-d '{
"title": "Unencrypted S3 Bucket Detected",
"message": "'"$line"'",
"severity": "critical",
"source": "cloud-security-scan"
}'
done
sleep 300
done
A common failure: the diff command fails silently when the file is empty, leading to missed alerts. The root cause is that diff -u produces no output when files are identical, but the while loop reads from stdin and exits early. The fix is to wrap the diff output in a grep and head check:
diff -u /var/tmp/previous-results.csv /var/tmp/encryption-missing.csv \
| grep '^+' \
| while IFS= read -r line; do
# ... alerting logic
done
Cloud security scanning must enforce policies across multiple environments.
Use a standardized format for security policies, shared across teams and platforms.
# policies/cloud-compliance.yaml
version: 1
policies:
- id: s3-encryption
title: "S3 Bucket Encryption"
description: "All S3 buckets must use server-side encryption with AES256"
severity: high
rules:
- field: "ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm"
expected: "AES256"
condition: "eq"
message: "Bucket encryption algorithm must be AES256"
- field: "ServerSideEncryptionConfiguration"
expected: "not null"
condition: "exists"
message: "S3 bucket must have server-side encryption configuration"
- id: eks-node-group-count
title: "Minimum Node Groups in EKS"
description: "EKS clusters must have at least two node groups"
severity: medium
rules:
- field: "NodeGroups"
expected: ">= 2"
condition: "length"
message: "EKS cluster must have at least two node groups"
Apply these policies using a policy-engine script:
# apply-policies.sh
#!/bin/bash
POLICY_FILE="policies/cloud-compliance.yaml"
OUTPUT_DIR="/var/cloud-scan/reports"
for region in us-east-1 us-west-2 eu-west-1; do
aws ec2 describe-instances --region "$region" \
--query 'Reservations[*].Instances[*].[InstanceId, Tags]' \
--output json \
> "$OUTPUT_DIR/$region-instances.json"
# Evaluate policies against each resource
for resource in $(find "$OUTPUT_DIR" -name "*.json"); do
echo "Evaluating $resource..."
opa eval \
--data "$POLICY_FILE" \
--input "$resource" \
--format json \
--output "$OUTPUT_DIR/results/$(basename "$resource").results"
done
done
A subtle failure: when a policy expects a length condition, the expected value is a string ("2"), but the length function returns an integer. The evaluation fails because "2" ≠ 2. The fix is to ensure that expected values are properly typed in the YAML.
Use a simple REST API to publish scan results and build a centralized cloud security dashboard.
# publish-scan-result.sh
#!/bin/bash
SCAN_ID=$(uuidgen)
TIMESTAMP=$(date -Iseconds)
curl -X POST https://dashboard.cloud.example.com/api/v1/scans \
-H "Content-Type: application/json" \
-d '{
"scan_id": "'"$SCAN_ID"'",
"timestamp": "'"$TIMESTAMP"'",
"environment": "production",
"results": [
{
"resource_type": "S3",
"resource_id": "logs-prod",
"status": "failed",
"checks": [
{
"name": "Encryption Algorithm",
"result": false,
"message": "Expected AES256, got SSE256"
}
]
}
]
}'
The dashboard consumes these payloads and displays real-time security health, with filters by environment, service, and severity. A common failure: status is failed but the dashboard expects failure. The error appears in logs: Unexpected status value: failed (expected: failure). The solution is to normalize status values in the publishing pipeline.
cfn-lint expects PublicAccessBlock as a nested object, not a boolean; tfsec reports S3 bucket not encrypted but the bucket uses SSE-KMS, not SSE-S3.git pull step leads to stale data.expected: "2" in a length rule fails because "2" ≠ 2. The fix is to use expected: 2 or add a parse-number step.watch-based systems miss alerts when diff produces no output; the fix is to add grep '^+' and head -n 1 to detect new entries.status: "failure" but publish-scan-result.sh sends status: "failed". The error is silent until a user notices the discrepancy.This page was rewritten on 14 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy