Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Terraform Tutorials: TFSec for Security Scanning

Table of Contents

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

CommandDescription
tfsec .Scan current Terraform directory.
tfsec --exclude aws-s3-enable-bucket-loggingIgnore specific checks.
tfsec --soft-failRun without failing CI pipelines.
tfsec --format jsonOutput results in JSON format.
tfsec --minimum-severity HIGHShow 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:

  1. Install pre-commit: pip install pre-commit
  2. Add .pre-commit-config.yaml: repos: - repo: https://github.com/aquasecurity/tfsec rev: v1.28.0 hooks: - id: tfsec
  3. 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

  1. 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!" }
  2. 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:

ToolDescription
CheckovStatic analysis security scanner for Terraform, Kubernetes, and CloudFormation.
Terraform CompliancePolicy-as-code framework for Terraform security and compliance enforcement.
TerrascanSecurity scanner that checks Terraform against compliance frameworks.
Snyk Infrastructure as CodeCloud 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:

  1. Create a .tfsecignore file: echo ".terraform/" >> .tfsecignore
  2. Run TFSec with proper flags: tfsec . --exclude-path .terraform --force-all-dirs=false --minimum-severity HIGH
  3. 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

CommandDescriptionExample Usage
tfsec [directory]Scans the given directory for security issues in Terraform configurations.tfsec /path/to/terraform/code
--code-themeSets the theme for annotated code output (light or dark).tfsec . --code-theme light
--concise-outputReduces output verbosity by hiding statistics.tfsec . --concise-output
--config-fileSpecifies a configuration file for tfsec.tfsec . --config-file tfsec-config.json
--config-file-urlDownloads a remote configuration file (must be JSON or YAML).tfsec . --config-file-url https://example.com/tfsec-config.yaml
--custom-check-dirDefines a directory containing custom security checks.tfsec . --custom-check-dir /path/to/custom/rules
--custom-check-urlDownloads a custom check file from a remote location (JSON/YAML).tfsec . --custom-check-url https://example.com/custom-checks.json
--debugEnables debug logging for detailed troubleshooting.tfsec . --debug
--disable-groupingDisables grouping of similar results in output.tfsec . --disable-grouping
-e, --excludeExcludes specific rule IDs from scanning.tfsec . --exclude AWS001,AWS002
--exclude-downloaded-modulesIgnores .terraform directory to avoid scanning dependencies.tfsec . --exclude-downloaded-modules
-E, --exclude-ignoresIgnores rules that were manually marked as ignored.tfsec . --exclude-ignores AWS001,AWS002
--exclude-pathExcludes specific directories or files from scanning.tfsec . --exclude-path .terraform/modules
--filter-resultsFilters results to return specific checks only.tfsec . --filter-results AWS002,AWS003
--force-all-dirsScans all directories without searching for .tf files.tfsec . --force-all-dirs
-f, --formatSpecifies the output format (json, html, csv, sarif, etc.).tfsec . --format json
-h, --helpDisplays the help menu with available commands.tfsec --help
--ignore-hcl-errorsIgnores errors related to HCL parsing failures.tfsec . --ignore-hcl-errors
--include-ignoredDisplays ignored security issues in the output.tfsec . --include-ignored
--include-passedShows passed checks in the output.tfsec . --include-passed
--migrate-ignoresMigrates ignore codes to a new ID structure.tfsec . --migrate-ignores
-m, --minimum-severitySets the minimum severity level (LOW, MEDIUM, HIGH, CRITICAL).tfsec . --minimum-severity HIGH
--no-codeDisables inclusion of code snippets in the output.tfsec . --no-code
--no-colorDisables colored output.tfsec . --no-color
--no-ignoresForces tfsec to consider ignored checks as active failures.tfsec . --no-ignores
--no-module-downloadsPrevents downloading of remote modules during scans.tfsec . --no-module-downloads
-O, --outSaves output to a file with the specified format.tfsec . --format json --out tfsec-results.json
--print-rego-inputDisplays JSON representation of input for Rego policies.tfsec . --print-rego-input
--rego-onlyRuns only Rego-based security policies.tfsec . --rego-only
--rego-policy-dirSpecifies the directory containing Rego policies for security analysis.tfsec . --rego-policy-dir policies/
--run-statisticsDisplays statistical insights about the scan results.tfsec . --run-statistics
--single-threadRuns checks using a single thread (useful for debugging).tfsec . --single-thread
-s, --soft-failRuns checks but suppresses error exit codes.tfsec . --soft-fail
--tfvars-fileUses a .tfvars file to set variables for evaluation.tfsec . --tfvars-file terraform.tfvars
--updateUpdates tfsec to the latest version.tfsec --update
--var-fileSpecifies a .tfvars file (same as --tfvars-file).tfsec . --var-file terraform.tfvars
--verboseEnables verbose logging output.tfsec . --verbose
-v, --versionDisplays the current tfsec version.tfsec --version
-w, --workspaceDefines 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 and AWS002 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. 🚀

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x