
Auditing Terraform Infrastructure For Security
- 220 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Have your agent systematically review Terraform for misconfigurations, overly permissive IAM, and common cloud security gaps before apply or merge.
About
Auditing Terraform Infrastructure for Security is an agent skill aimed at solo builders who manage their own cloud with Terraform and cannot afford a dedicated platform security team. Instead of hoping a generic linter catches everything, the skill steers the agent through a security-oriented pass over modules, variables, IAM bindings, network exposure, secrets handling, and state/backend choices— the places AI-generated infra often drifts toward convenience over least privilege. Use it in the Ship phase when a PR touches .tf files, before terraform apply in staging, or when onboarding a new environment copied from a tutorial. Outputs are findings and remediation guidance you can turn into tasks or policy checks. It is a checker-style skill, not a live scanner replacement; you still own account guardrails and the Security Audits panel on Prism for package trust. Pair with your existing CI plan review for defense in depth.
- Security-focused audit workflow for Terraform-defined infrastructure
- Targets misconfiguration and policy-risk patterns common in solo-builder cloud stacks
- Fits pre-merge and pre-apply review gates in CI or agent-driven ship workflows
- Complements generic code review with infrastructure-as-code threat modeling
- Aligned with Anthropic cybersecurity skill collection patterns for agent execution
Auditing Terraform Infrastructure For Security by the numbers
- 220 all-time installs (skills.sh)
- +8 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #738 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill auditing-terraform-infrastructure-for-securityAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 220 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Have your agent systematically review Terraform for misconfigurations, overly permissive IAM, and common cloud security gaps before apply or merge.
Files
Auditing Terraform Infrastructure for Security
When to Use
- When integrating security scanning into CI/CD pipelines for Terraform deployments
- When reviewing Terraform plans and modules for security best practices before applying
- When building policy-as-code guardrails for cloud infrastructure provisioning
- When auditing existing Terraform state files to identify deployed misconfigurations
- When enforcing organizational security standards across multiple Terraform projects
Do not use for runtime security monitoring (use CSPM tools), for application security testing (use SAST/DAST tools), or for cloud configuration drift detection (use AWS Config or Azure Policy after deployment).
Prerequisites
- Checkov installed (
pip install checkov) - tfsec installed (
brew install tfsecor binary from GitHub) - Terrascan installed (
brew install terrascan) - Terraform v1.0+ for plan generation
- OPA (Open Policy Agent) for custom policy enforcement
- Git repository with Terraform code to audit
Workflow
Step 1: Scan Terraform Code with Checkov
Run Checkov for comprehensive IaC security scanning with built-in and custom policies.
# Scan a Terraform directory
checkov -d ./terraform/ --framework terraform
# Scan with specific check categories
checkov -d ./terraform/ --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20,CKV_AWS_21
# Scan and output results in JSON
checkov -d ./terraform/ --output json > checkov-results.json
# Scan a Terraform plan file for more accurate analysis
terraform init && terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan
# Skip specific checks with justification
checkov -d ./terraform/ --skip-check CKV_AWS_145 \
--bc-api-key $BRIDGECREW_API_KEY
# Scan Terraform modules
checkov -d ./modules/ --framework terraform --compact
# List all available checks
checkov --list --framework terraform | grep CKV_AWSStep 2: Scan with tfsec for Terraform-Specific Issues
Use tfsec for Terraform-native security analysis with detailed remediation guidance.
# Scan a Terraform directory
tfsec ./terraform/
# Scan with minimum severity threshold
tfsec ./terraform/ --minimum-severity HIGH
# Output in JSON for CI/CD processing
tfsec ./terraform/ --format json > tfsec-results.json
# Scan with custom checks
tfsec ./terraform/ --custom-check-dir ./custom-checks/
# Exclude specific rules
tfsec ./terraform/ --exclude-downloaded-modules \
--exclude aws-s3-enable-bucket-logging
# Scan and fail on specific severity
tfsec ./terraform/ --minimum-severity CRITICAL --soft-fail
# Generate SARIF output for GitHub Security tab
tfsec ./terraform/ --format sarif > tfsec.sarifStep 3: Run Terrascan for Multi-Framework Compliance
Execute Terrascan for compliance checking against CIS, NIST, and SOC 2 frameworks.
# Scan Terraform against CIS AWS benchmark
terrascan scan -t aws -i terraform -d ./terraform/ \
--policy-type aws --verbose
# Scan against specific compliance frameworks
terrascan scan -t aws -i terraform -d ./terraform/ \
--policy-type aws \
--categories "Compliance Validation"
# Output in JSON
terrascan scan -t aws -i terraform -d ./terraform/ \
--output json > terrascan-results.json
# Scan a Terraform plan
terrascan scan -t aws -i terraform \
--iac-file tfplan.json \
--iac-type tfplan
# List available policies
terrascan scan --list-policies -t awsStep 4: Create Custom OPA Policies for Organization Standards
Write Rego policies for organization-specific security requirements.
# policy/aws_s3_encryption.rego
package terraform.aws.s3
deny[msg] {
resource := input.resource.aws_s3_bucket[name]
not resource.server_side_encryption_configuration
msg := sprintf("S3 bucket '%s' must have server-side encryption enabled", [name])
}
# policy/aws_iam_no_wildcards.rego
package terraform.aws.iam
deny[msg] {
resource := input.resource.aws_iam_policy[name]
statement := resource.policy.Statement[_]
statement.Action == "*"
statement.Effect == "Allow"
msg := sprintf("IAM policy '%s' must not use wildcard (*) actions", [name])
}
deny[msg] {
resource := input.resource.aws_iam_policy[name]
statement := resource.policy.Statement[_]
statement.Resource == "*"
statement.Effect == "Allow"
contains(statement.Action[_], "*")
msg := sprintf("IAM policy '%s' has overly permissive actions on wildcard resources", [name])
}
# policy/aws_no_public_ingress.rego
package terraform.aws.security_group
deny[msg] {
resource := input.resource.aws_security_group_rule[name]
resource.type == "ingress"
resource.cidr_blocks[_] == "0.0.0.0/0"
resource.from_port <= 22
resource.to_port >= 22
msg := sprintf("Security group rule '%s' allows SSH from 0.0.0.0/0", [name])
}# Evaluate Terraform plan against OPA policies
terraform show -json tfplan | opa eval \
--data ./policy/ \
--input /dev/stdin \
"data.terraform.aws" \
--format pretty
# Run Conftest for easier OPA policy testing
conftest test tfplan.json --policy ./policy/ --output jsonStep 5: Integrate Security Scanning into CI/CD Pipeline
Add IaC security scanning as a mandatory CI/CD gate.
# GitHub Actions: Terraform security pipeline
name: Terraform Security Scan
on:
pull_request:
paths: ['terraform/**']
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
- name: Terraform Init & Plan
run: |
cd terraform/
terraform init
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
- name: Checkov Scan
uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
framework: terraform
output_format: sarif
output_file_path: checkov.sarif
soft_fail: false
- name: tfsec Scan
uses: aquasecurity/tfsec-action@v1.0.0
with:
working_directory: terraform/
soft_fail: false
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: checkov.sarif
- name: OPA Policy Check
run: |
conftest test terraform/tfplan.json \
--policy ./policy/ \
--output jsonStep 6: Scan Terraform State for Deployed Misconfigurations
Audit the current Terraform state to identify already-deployed security issues.
# Export current state as JSON
terraform show -json > terraform-state.json
# Scan the state with Checkov
checkov -f terraform-state.json --framework terraform_plan
# Query state for specific security issues
terraform state list | while read resource; do
terraform state show "$resource" 2>/dev/null | grep -i "public\|0.0.0.0\|encrypt.*false\|password"
done
# Find resources without required tags
terraform state list | grep aws_instance | while read resource; do
tags=$(terraform state show "$resource" | grep -A20 "tags")
if ! echo "$tags" | grep -q "Environment"; then
echo "MISSING TAG: $resource lacks 'Environment' tag"
fi
doneKey Concepts
| Term | Definition |
|---|---|
| Infrastructure as Code | Practice of managing cloud infrastructure through declarative configuration files (Terraform, CloudFormation) rather than manual console operations |
| Policy as Code | Expressing security and compliance policies as executable code (Rego, Python) that can be automatically evaluated against infrastructure definitions |
| Shift Left Security | Moving security checks earlier in the development lifecycle by scanning IaC before deployment rather than auditing after provisioning |
| Terraform Plan | Preview of changes Terraform will make, which can be exported as JSON for security scanning before applying changes |
| Checkov | Open-source static analysis tool for IaC supporting Terraform, CloudFormation, Kubernetes, and Docker with 1000+ built-in policies |
| OPA/Rego | Open Policy Agent and its policy language Rego for defining custom security rules that evaluate against structured data inputs |
Tools & Systems
- Checkov: Comprehensive IaC scanner with 1000+ policies for Terraform, CloudFormation, Kubernetes, ARM, and Dockerfile
- tfsec: Terraform-specific static analysis tool with detailed remediation guidance and SARIF output
- Terrascan: Multi-IaC scanner supporting compliance frameworks (CIS, NIST, SOC 2) with policy-as-code
- OPA/Conftest: Custom policy engine for defining organization-specific security rules using Rego language
- Bridgecrew: Commercial platform built on Checkov providing drift detection and supply chain security
Common Scenarios
Scenario: Adding Security Gates to an Existing Terraform CI/CD Pipeline
Context: A DevOps team deploys infrastructure via Terraform in GitHub Actions but has no security scanning. Recent audit findings show multiple S3 buckets without encryption and security groups allowing SSH from the internet.
Approach: 1. Add Checkov as the first security gate in the GitHub Actions workflow 2. Run checkov -d ./terraform/ to establish the current baseline of findings 3. Triage existing findings: fix CRITICAL issues, create tickets for HIGH, suppress accepted risks 4. Add tfsec as a secondary scanner for Terraform-specific checks 5. Write custom OPA policies for organization standards (required tags, naming conventions) 6. Configure the pipeline to block PRs with CRITICAL or HIGH findings 7. Generate SARIF reports for GitHub Security tab integration
Pitfalls: Adding security scanning to an existing project will initially produce hundreds of findings. Implement gradually by starting with CRITICAL-only blocking, then expanding to HIGH. Use inline suppression comments (#checkov:skip=CKV_AWS_18:Public bucket for static website) for intentional exceptions with documented justification.
Output Format
Terraform Security Audit Report
==================================
Repository: acme-corp/infrastructure
Branch: main
Scan Date: 2026-02-23
Tools: Checkov 3.x, tfsec 1.x, OPA custom policies
SCAN RESULTS:
Checkov checks passed: 187
Checkov checks failed: 34
tfsec checks passed: 156
tfsec checks failed: 28
OPA custom policies: 12 passed, 3 failed
CRITICAL FINDINGS:
[TF-001] S3 Bucket Without Encryption
File: modules/storage/main.tf:24
Resource: aws_s3_bucket.data_lake
Check: CKV_AWS_19
Fix: Add server_side_encryption_configuration block
[TF-002] Security Group Allows SSH from 0.0.0.0/0
File: modules/network/security.tf:45
Resource: aws_security_group_rule.ssh_access
Check: CKV_AWS_24
Fix: Restrict cidr_blocks to bastion subnet
[TF-003] IAM Policy with Wildcard Actions
File: modules/iam/policies.tf:12
Resource: aws_iam_policy.developer_policy
Check: CKV_AWS_1
Fix: Scope actions to specific services required
SUMMARY BY SEVERITY:
Critical: 6 findings
High: 14 findings
Medium: 28 findings
Low: 18 findings
Info: 12 findings
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Auditing Terraform Infrastructure for Security
Checkov CLI
# Scan directory
checkov -d ./terraform/ --framework terraform --output json
# Scan plan file
terraform plan -out=tfplan && terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan
# Skip specific checks
checkov -d ./terraform/ --skip-check CKV_AWS_145
# List all checks
checkov --list --framework terraform | grep CKV_AWStfsec CLI
# Scan with minimum severity
tfsec ./terraform/ --minimum-severity HIGH --format json
# Generate SARIF for GitHub
tfsec ./terraform/ --format sarif > tfsec.sarifCheckov Python API
from checkov.runner_registry import RunnerRegistry
from checkov.terraform.runner import Runner
runner = Runner()
report = runner.run(root_folder="./terraform/")
for check in report.failed_checks:
print(check.check_id, check.resource, check.file_path)Common CKV Check IDs
| Check ID | Description |
|---|---|
| CKV_AWS_18 | S3 access logging |
| CKV_AWS_19 | S3 server-side encryption |
| CKV_AWS_20 | S3 Block Public Access |
| CKV_AWS_24 | Security group allows SSH from 0.0.0.0/0 |
| CKV_AWS_1 | IAM policy with wildcard actions |
| CKV_AWS_145 | RDS encryption |
| CKV_AWS_41 | Secrets in Lambda environment variables |
OPA/Conftest
# Evaluate plan against Rego policies
conftest test tfplan.json --policy ./policy/ --output jsonpackage terraform.aws.s3
deny[msg] {
resource := input.resource.aws_s3_bucket[name]
not resource.server_side_encryption_configuration
msg := sprintf("S3 bucket '%s' missing encryption", [name])
}References
- Checkov: https://www.checkov.io/
- tfsec: https://aquasecurity.github.io/tfsec/
- Terrascan: https://runterrascan.io/
- Conftest: https://www.conftest.dev/
#!/usr/bin/env python3
"""Agent for auditing Terraform infrastructure for security misconfigurations."""
import json
import argparse
import subprocess
from datetime import datetime
def run_checkov(terraform_dir, output_format="json"):
"""Run Checkov static analysis on Terraform code."""
cmd = ["checkov", "-d", terraform_dir, "--framework", "terraform", "--output", output_format, "--compact"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if output_format == "json":
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
return {"raw_output": result.stdout, "error": result.stderr}
return result.stdout
def run_checkov_on_plan(plan_json_path):
"""Run Checkov on a Terraform plan JSON file for accurate analysis."""
cmd = ["checkov", "-f", plan_json_path, "--framework", "terraform_plan", "--output", "json"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
return {"raw_output": result.stdout}
def run_tfsec(terraform_dir, min_severity="HIGH"):
"""Run tfsec Terraform security scanner."""
cmd = ["tfsec", terraform_dir, "--format", "json", "--minimum-severity", min_severity]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
return {"raw_output": result.stdout}
def parse_checkov_results(checkov_output):
"""Parse Checkov output and extract failed checks with details."""
findings = []
if isinstance(checkov_output, list):
checks = checkov_output
elif isinstance(checkov_output, dict):
checks = checkov_output.get("results", {}).get("failed_checks", [])
else:
return findings
for check in checks:
if isinstance(check, dict):
findings.append({
"check_id": check.get("check_id", ""),
"check_name": check.get("check_result", {}).get("check", {}).get("name", check.get("name", "")),
"resource": check.get("resource", ""),
"file": check.get("file_path", ""),
"line": check.get("file_line_range", []),
"severity": check.get("severity", "UNKNOWN"),
"guideline": check.get("guideline", ""),
})
return findings
def parse_tfsec_results(tfsec_output):
"""Parse tfsec output and extract findings."""
findings = []
results = tfsec_output.get("results", [])
if results is None:
return findings
for r in results:
findings.append({
"rule_id": r.get("rule_id", ""),
"description": r.get("description", ""),
"severity": r.get("severity", ""),
"resource": r.get("resource", ""),
"location": f"{r.get('location', {}).get('filename', '')}:{r.get('location', {}).get('start_line', '')}",
"resolution": r.get("resolution", ""),
})
return findings
def scan_tf_plan_for_issues(plan_json_path):
"""Directly scan a Terraform plan JSON for common security issues."""
with open(plan_json_path) as f:
plan = json.load(f)
issues = []
for change in plan.get("resource_changes", []):
after = change.get("change", {}).get("after", {})
resource_type = change.get("type", "")
address = change.get("address", "")
if resource_type == "aws_s3_bucket":
if not after.get("server_side_encryption_configuration"):
issues.append({"resource": address, "issue": "S3 bucket without encryption", "severity": "HIGH"})
if resource_type == "aws_security_group_rule":
for cidr in after.get("cidr_blocks", []):
if cidr == "0.0.0.0/0" and after.get("from_port", 0) <= 22 <= after.get("to_port", 0):
issues.append({"resource": address, "issue": "SSH open to 0.0.0.0/0", "severity": "CRITICAL"})
if resource_type == "aws_iam_policy":
policy_doc = after.get("policy", "{}")
if isinstance(policy_doc, str):
try:
doc = json.loads(policy_doc)
for stmt in doc.get("Statement", []):
if stmt.get("Action") == "*" and stmt.get("Effect") == "Allow":
issues.append({"resource": address, "issue": "IAM wildcard actions", "severity": "CRITICAL"})
except json.JSONDecodeError:
pass
return issues
def generate_report(checkov_findings, tfsec_findings, plan_issues):
"""Generate combined audit report."""
all_findings = []
for f in checkov_findings:
f["source"] = "checkov"
all_findings.append(f)
for f in tfsec_findings:
f["source"] = "tfsec"
all_findings.append(f)
for f in plan_issues:
f["source"] = "plan_scan"
all_findings.append(f)
severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
all_findings.sort(key=lambda x: severity_order.get(x.get("severity", "LOW"), 4))
return {
"audit_date": datetime.utcnow().isoformat(),
"total_findings": len(all_findings),
"critical": sum(1 for f in all_findings if f.get("severity") == "CRITICAL"),
"high": sum(1 for f in all_findings if f.get("severity") == "HIGH"),
"findings": all_findings,
}
def main():
parser = argparse.ArgumentParser(description="Terraform Security Audit Agent")
parser.add_argument("--terraform-dir", help="Directory with Terraform code")
parser.add_argument("--plan-json", help="Terraform plan JSON file")
parser.add_argument("--output", default="terraform_audit.json")
parser.add_argument("--tool", choices=["checkov", "tfsec", "both", "plan_only"], default="both")
args = parser.parse_args()
checkov_findings = []
tfsec_findings = []
plan_issues = []
if args.terraform_dir:
if args.tool in ("checkov", "both"):
print("[+] Running Checkov...")
raw = run_checkov(args.terraform_dir)
checkov_findings = parse_checkov_results(raw)
print(f" Found {len(checkov_findings)} issues")
if args.tool in ("tfsec", "both"):
print("[+] Running tfsec...")
raw = run_tfsec(args.terraform_dir)
tfsec_findings = parse_tfsec_results(raw)
print(f" Found {len(tfsec_findings)} issues")
if args.plan_json:
print("[+] Scanning Terraform plan...")
plan_issues = scan_tf_plan_for_issues(args.plan_json)
print(f" Found {len(plan_issues)} issues")
report = generate_report(checkov_findings, tfsec_findings, plan_issues)
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] {report['critical']} critical, {report['high']} high out of {report['total_findings']} total")
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
FAQ
Is Auditing Terraform Infrastructure For Security safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.