How to Use tfsec for Terraform Security Scanning
Use
tfsec by installing it and running tfsec [directory] to scan your Terraform code for security issues. It analyzes your code and reports potential risks with clear messages to help you fix them.Syntax
The basic command to run tfsec is tfsec [directory]. Replace [directory] with the path to your Terraform files. You can add options like --format to change output style or --exclude to skip certain checks.
tfsec: The tool command.[directory]: Folder with Terraform code to scan.--format: Output format (e.g., json, junit).--exclude: Skip specific rules by ID.
bash
tfsec [directory] [options]
Example
This example shows how to scan a Terraform folder named infra using tfsec. It will print security issues found in the code.
bash
tfsec infra
Output
Result for infra:
[HIGH] AWS S3 Bucket 'my_bucket' has public read access
/infra/main.tf:12
[MEDIUM] Security group allows ingress from 0.0.0.0/0
/infra/security.tf:8
Summary: 1 High, 1 Medium, 0 Low issues found.
Common Pitfalls
Common mistakes when using tfsec include:
- Running tfsec outside the Terraform directory, causing no files to scan.
- Ignoring output messages and missing critical security warnings.
- Not updating tfsec regularly, missing new checks.
- Using
--excludetoo broadly, skipping important rules.
Always run tfsec inside your Terraform project folder and review all findings carefully.
bash
Wrong: tfsec Right: tfsec ./my-terraform-folder
Quick Reference
| Command | Description |
|---|---|
| tfsec ./path | Scan Terraform code in the given path |
| tfsec --format json ./path | Output results in JSON format |
| tfsec --exclude AWS001 ./path | Skip rule with ID AWS001 |
| tfsec --version | Show tfsec version installed |
Key Takeaways
Run tfsec inside your Terraform project folder to scan for security issues.
Review all tfsec output carefully to fix potential risks.
Use options like --format and --exclude to customize scanning.
Keep tfsec updated to get the latest security checks.
Avoid skipping important rules unless you understand the risk.