Comprehensive Guide to TFSec: Terraform Security Scanning
1. What is TFSec?
TFSec is a static analysis security scanner designed to identify security vulnerabilities in Terraform Infrastructure-as-Code (IaC) configurations before they are applied to cloud environments.
TFSec helps DevSecOps teams shift left by detecting misconfigurations, enforcing best security practices, and ensuring compliance with security policies.
TFSec works by analyzing Terraform configuration files (.tf
and .tfvars
) without requiring access to cloud provider APIs, making it a fast and efficient security tool.
2. TFSec Features
TFSec is a feature-rich tool designed for Terraform security scanning. Here are its key features:
✔ Deep Security Analysis – Detects insecure configurations in Terraform files before deployment.
✔ Supports Multiple Cloud Providers – Works with AWS, Azure, GCP, Kubernetes, and DigitalOcean.
✔ Built-in Compliance Policies – Checks against CIS Benchmarks, NIST, PCI-DSS, and ISO27001.
✔ Custom Rule Support – Allows organizations to create custom security policies.
✔ Automatic Module Discovery – Scans Terraform modules automatically.
✔ Context-Aware Scanning – Detects dynamic issues such as publicly exposed resources, weak IAM permissions, and unencrypted data storage.
✔ Fast & Offline Execution – Does not require Terraform state files or cloud API access.
✔ CI/CD Integration – Works with GitHub Actions, GitLab CI/CD, Jenkins, CircleCI, and Azure DevOps.
✔ Flexible Output Formats – Generates reports in JSON, CSV, SARIF, and JUnit for security reporting.
3. TFSec Benefits
Using TFSec in a DevOps or SecOps workflow offers several advantages:
✅ Security Benefits
- Prevents misconfigurations before they reach production.
- Enforces cloud security best practices (e.g., encrypting S3 buckets, restricting IAM policies).
- Identifies public exposure risks (e.g., open security groups, unencrypted databases).
- Improves compliance with CIS, NIST, SOC 2, PCI-DSS, and ISO27001 standards.
✅ Operational Benefits
- Faster security reviews – Detects issues in Terraform code early in the development process.
- Lightweight and fast – Runs without requiring Terraform state or cloud access.
- Easy CI/CD integration – Automates security checks in GitHub Actions, GitLab CI, Jenkins, etc.
- Custom security checks – Organizations can define their own security policies.
4. How to Install TFSec?
TFSec supports multiple installation methods across various operating systems.
🔹 Install TFSec on macOS
brew install tfsec
🔹 Install TFSec on Linux
curl -s https://raw.githubusercontent.com/aquasecurity/tfsec/master/scripts/install_linux.sh | bash
🔹 Install TFSec on Windows
choco install tfsec
🔹 Install via Docker
docker run --rm -v "$(pwd):/src" aquasec/tfsec /src
🔹 Install via Go (for developers)
go install github.com/aquasecurity/tfsec/cmd/tfsec@latest
After installation, verify TFSec is working:
tfsec --version
5. How to Use TFSec?
Once installed, TFSec is easy to use. Navigate to your Terraform project directory and run:
tfsec .
🔹 Example Output
[HIGH] AWS S3 bucket allows public access (aws-s3-enable-bucket-logging)
[aws_s3_bucket.public]
./s3.tf:15 14 | resource “aws_s3_bucket” “public” { 15 | acl = “public-read” 16 | } Fix: Change `acl` to “private” or “log-delivery-write”
Common TFSec Commands
Command | Description |
---|---|
tfsec . | Scan current Terraform directory. |
tfsec --exclude aws-s3-enable-bucket-logging | Ignore specific checks. |
tfsec --soft-fail | Run without failing CI pipelines. |
tfsec --format json | Output results in JSON format. |
tfsec --minimum-severity HIGH | Show only HIGH severity issues. |
6. Working with TFSec Locally
To scan a Terraform project locally, follow these steps:
Step 1: Initialize Terraform (Optional)
terraform init
Step 2: Run TFSec
tfsec .
Step 3: Fix Security Issues
- Modify Terraform files based on TFSec suggestions.
- Run
tfsec .
again to confirm issues are resolved.
Step 4: Automate with Git Pre-Commit Hook
To prevent insecure Terraform code from being committed:
- Install
pre-commit
:pip install pre-commit
- Add
.pre-commit-config.yaml
:repos: - repo: https://github.com/aquasecurity/tfsec rev: v1.28.0 hooks: - id: tfsec
- Install pre-commit hooks:
pre-commit install
7. Using TFSec in SecOps Pipelines
TFSec integrates with CI/CD pipelines to enforce security compliance.
GitHub Actions
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run TFSec
uses: aquasecurity/tfsec-action@main
GitLab CI/CD
stages:
- security
security:
image: aquasec/tfsec:latest
script:
- tfsec .
Jenkins Pipeline
pipeline {
agent any
stages {
stage('Security Scan') {
steps {
sh 'tfsec .'
}
}
}
}
8. TFSec Custom Checks
TFSec allows custom security rules to be defined using Rego policies.
Example: Custom Check for Public S3 Buckets
- Create a custom rule file (
custom.rego
):package tfsec.custom deny[msg] { input.resource_type == "aws_s3_bucket" input.values.acl == "public-read" msg = "S3 buckets should not be public!" }
- Run TFSec with Custom Rules
tfsec --config-file custom.rego
9. TFSec Alternatives
While TFSec is an excellent Terraform security tool, here are some alternatives:
Tool | Description |
---|---|
Checkov | Static analysis security scanner for Terraform, Kubernetes, and CloudFormation. |
Terraform Compliance | Policy-as-code framework for Terraform security and compliance enforcement. |
Terrascan | Security scanner that checks Terraform against compliance frameworks. |
Snyk Infrastructure as Code | Cloud security scanner with a developer-friendly UI. |
Kics (Keep Infrastructure as Code Secure) | Security analysis for Terraform, Kubernetes, and CloudFormation. |
Conclusion
TFSec is a powerful security scanner that helps developers and security teams enforce best practices in Terraform IaC. By integrating TFSec into local development workflows and CI/CD pipelines, teams can proactively detect and fix security vulnerabilities before infrastructure is deployed.
By following this guide, you can install, configure, and use TFSec effectively in your projects. 🚀 Happy SecOps!
Handling TFSec Scanning in the .terraform
Directory
When running TFSec on a Terraform project, it automatically scans all directories, including the .terraform
directory, which contains downloaded Terraform modules and providers. This can result in many false positives or security issues in third-party modules that you cannot directly modify.
To prevent TFSec from scanning the .terraform
directory and reduce noise in your results, follow the best practices below:
🔹 Best Approaches to Exclude .terraform
Directory
1️⃣ Use --exclude-path
Flag
TFSec allows you to ignore specific directories using the --exclude-path
option.
tfsec --exclude-path .terraform
This tells TFSec to skip scanning the .terraform
directory, reducing unnecessary warnings.
2️⃣ Use .tfsecignore
File
You can create a .tfsecignore
file in your Terraform project and exclude specific directories or checks.
Example:
echo ".terraform/" >> .tfsecignore
Or manually create .tfsecignore
and add:
.terraform/
This ensures TFSec always ignores the .terraform
directory for all future scans.
3️⃣ Use --force-all-dirs=false
Flag
By default, TFSec scans all directories, even hidden ones. To disable scanning hidden directories, use:
tfsec --force-all-dirs=false
This stops TFSec from scanning .terraform/
, reducing noise from third-party modules.
4️⃣ Ignore Specific Module Directories
If your Terraform project uses external modules (like AWS modules from Terraform Registry) and you don’t want to scan them, use:
tfsec --exclude-path .terraform/modules
This prevents scanning only the modules/
subdirectory inside .terraform
, while keeping other checks active.
5️⃣ Use --minimum-severity
to Filter Results
If you want to only see critical security issues, set a minimum severity level:
tfsec --minimum-severity HIGH
This filters out low-severity and medium-severity warnings, making results more relevant.
✅ Recommended TFSec Configuration for Excluding .terraform
To ensure TFSec ignores irrelevant issues in .terraform/
, use all the best practices together:
- Create a
.tfsecignore
file:echo ".terraform/" >> .tfsecignore
- Run TFSec with proper flags:
tfsec . --exclude-path .terraform --force-all-dirs=false --minimum-severity HIGH
- Modify
.pre-commit-config.yaml
(if using pre-commit hooks):repos: - repo: https://github.com/aquasecurity/tfsec rev: v1.28.0 hooks: - id: tfsec args: [ "--exclude-path=.terraform", "--minimum-severity=HIGH" ]
By applying these best practices, you can: ✅ Exclude .terraform/
from scans.
✅ Reduce false positives from third-party Terraform modules.
✅ Focus on real security risks in your own Terraform code.
✅ Ensure clean security reports without unnecessary warnings.
This keeps your TFSec scans efficient and relevant while still enforcing security best practices. 🚀
Comprehensive Guide to tfsec
Commands with Examples
Introduction to tfsec
tfsec
is a static analysis security scanner for Terraform configurations. It detects potential security misconfigurations, enforces best practices, and provides remediation suggestions.
Basic Usage
tfsec .
This scans the current directory (.
) for Terraform security issues.
Table of tfsec
Commands and Examples
Command | Description | Example Usage |
---|---|---|
tfsec [directory] | Scans the given directory for security issues in Terraform configurations. | tfsec /path/to/terraform/code |
--code-theme | Sets the theme for annotated code output (light or dark ). | tfsec . --code-theme light |
--concise-output | Reduces output verbosity by hiding statistics. | tfsec . --concise-output |
--config-file | Specifies a configuration file for tfsec . | tfsec . --config-file tfsec-config.json |
--config-file-url | Downloads a remote configuration file (must be JSON or YAML). | tfsec . --config-file-url https://example.com/tfsec-config.yaml |
--custom-check-dir | Defines a directory containing custom security checks. | tfsec . --custom-check-dir /path/to/custom/rules |
--custom-check-url | Downloads a custom check file from a remote location (JSON/YAML). | tfsec . --custom-check-url https://example.com/custom-checks.json |
--debug | Enables debug logging for detailed troubleshooting. | tfsec . --debug |
--disable-grouping | Disables grouping of similar results in output. | tfsec . --disable-grouping |
-e, --exclude | Excludes specific rule IDs from scanning. | tfsec . --exclude AWS001,AWS002 |
--exclude-downloaded-modules | Ignores .terraform directory to avoid scanning dependencies. | tfsec . --exclude-downloaded-modules |
-E, --exclude-ignores | Ignores rules that were manually marked as ignored. | tfsec . --exclude-ignores AWS001,AWS002 |
--exclude-path | Excludes specific directories or files from scanning. | tfsec . --exclude-path .terraform/modules |
--filter-results | Filters results to return specific checks only. | tfsec . --filter-results AWS002,AWS003 |
--force-all-dirs | Scans all directories without searching for .tf files. | tfsec . --force-all-dirs |
-f, --format | Specifies the output format (json , html , csv , sarif , etc.). | tfsec . --format json |
-h, --help | Displays the help menu with available commands. | tfsec --help |
--ignore-hcl-errors | Ignores errors related to HCL parsing failures. | tfsec . --ignore-hcl-errors |
--include-ignored | Displays ignored security issues in the output. | tfsec . --include-ignored |
--include-passed | Shows passed checks in the output. | tfsec . --include-passed |
--migrate-ignores | Migrates ignore codes to a new ID structure. | tfsec . --migrate-ignores |
-m, --minimum-severity | Sets the minimum severity level (LOW , MEDIUM , HIGH , CRITICAL ). | tfsec . --minimum-severity HIGH |
--no-code | Disables inclusion of code snippets in the output. | tfsec . --no-code |
--no-color | Disables colored output. | tfsec . --no-color |
--no-ignores | Forces tfsec to consider ignored checks as active failures. | tfsec . --no-ignores |
--no-module-downloads | Prevents downloading of remote modules during scans. | tfsec . --no-module-downloads |
-O, --out | Saves output to a file with the specified format. | tfsec . --format json --out tfsec-results.json |
--print-rego-input | Displays JSON representation of input for Rego policies. | tfsec . --print-rego-input |
--rego-only | Runs only Rego-based security policies. | tfsec . --rego-only |
--rego-policy-dir | Specifies the directory containing Rego policies for security analysis. | tfsec . --rego-policy-dir policies/ |
--run-statistics | Displays statistical insights about the scan results. | tfsec . --run-statistics |
--single-thread | Runs checks using a single thread (useful for debugging). | tfsec . --single-thread |
-s, --soft-fail | Runs checks but suppresses error exit codes. | tfsec . --soft-fail |
--tfvars-file | Uses a .tfvars file to set variables for evaluation. | tfsec . --tfvars-file terraform.tfvars |
--update | Updates tfsec to the latest version. | tfsec --update |
--var-file | Specifies a .tfvars file (same as --tfvars-file ). | tfsec . --var-file terraform.tfvars |
--verbose | Enables verbose logging output. | tfsec . --verbose |
-v, --version | Displays the current tfsec version. | tfsec --version |
-w, --workspace | Defines a workspace for ignore rules. | tfsec . --workspace dev |
🔹 Practical Usage Examples
1️⃣ Running a Basic Scan
tfsec .
- Scans the current directory and displays detected security issues.
2️⃣ Running a Scan with a Custom Configuration File
tfsec . --config-file tfsec-config.json
- Uses
tfsec-config.json
for custom security rules.
3️⃣ Excluding Specific Checks
tfsec . --exclude AWS001,AWS002
- Skips
AWS001
andAWS002
security rules.
4️⃣ Filtering for Specific Checks
tfsec . --filter-results AWS003,AWS004
- Shows only results matching the specified rules.
5️⃣ Excluding .terraform
Modules
tfsec . --exclude-downloaded-modules
- Prevents scanning of Terraform dependency modules.
6️⃣ Running tfsec
with High Severity Threshold
tfsec . --minimum-severity HIGH
- Reports only HIGH and CRITICAL security issues.
7️⃣ Exporting Scan Results to a JSON File
tfsec . --format json --out tfsec-results.json
- Saves results as a JSON file.
8️⃣ Running tfsec
in a CI/CD Pipeline
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run tfsec
run: |
tfsec . --minimum-severity HIGH --format sarif --out tfsec-results.sarif
- Integrates
tfsec
into a GitHub Actions pipeline. - Runs security checks and exports results in SARIF format for GitHub Security Analysis.
🔹 Conclusion
Using tfsec
ensures secure, compliant, and well-architected Terraform code by detecting misconfigurations before deployment.
Best Practices for Using tfsec
✅ Run tfsec
before every Terraform deployment.
✅ Exclude .terraform/modules/
from scans to avoid third-party module issues.
✅ Use --minimum-severity HIGH
to focus on critical risks.
✅ Save reports (--format json --out
) for compliance tracking.
✅ Integrate tfsec
into CI/CD pipelines for continuous security.
By following these best practices, you can significantly enhance the security posture of your Terraform infrastructure. 🚀
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND