How to Secure Terraform Code with Trivy

Listen to this Post

Featured Image
Scanning your Terraform code is essential for maintaining a strong security posture. Trivy is a powerful open-source tool that can scan infrastructure-as-code (IaC) files, containers, filesystems, and more for vulnerabilities.

Installing Trivy

To get started, install Trivy on your Linux system:

 For Debian/Ubuntu 
sudo apt-get install wget apt-transport-https gnupg lsb-release 
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add - 
echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | sudo tee -a /etc/apt/sources.list.d/trivy.list 
sudo apt-get update 
sudo apt-get install trivy

For RHEL/CentOS 
sudo rpm -ivh https://github.com/aquasecurity/trivy/releases/download/v0.45.1/trivy_0.45.1_Linux-64bit.rpm

For macOS (Homebrew) 
brew install aquasecurity/trivy/trivy 

Scanning Terraform Files

Run Trivy against a Terraform directory:

trivy config --security-checks vuln,config ./terraform/ 

This will detect:

  • Misconfigurations in Terraform files
  • Known CVEs in referenced modules
  • Compliance violations (e.g., AWS CIS benchmarks)

Automating Scans in CI/CD

Integrate Trivy with GitHub Actions:

name: Terraform Security Scan 
on: [bash] 
jobs: 
trivy-scan: 
runs-on: ubuntu-latest 
steps: 
- uses: actions/checkout@v4 
- name: Run Trivy 
uses: aquasecurity/trivy-action@master 
with: 
scan-type: 'config' 
scan-ref: './terraform' 
format: 'table' 
exit-code: '1' 

You Should Know:

  • Trivy vs. Checkov: While Checkov is another IaC scanner, Trivy supports more formats (containers, OS packages).
  • Ignoring False Positives: Use `.trivyignore` to exclude known non-issues.
  • Custom Policies: Use Open Policy Agent (OPA) with Trivy for advanced rule definitions.

What Undercode Say:

Terraform security scanning is no longer optional—tools like Trivy make it seamless. Automate scans in pipelines to catch misconfigurations before deployment. Combine Trivy with TFLint and TFSec for comprehensive IaC security.

Expected Output:

2024-05-13T12:00:00.000Z INFO Detected config files: 2 (Terraform) 
2024-05-13T12:00:01.000Z WARN AWS S3 bucket policy allows public access (CIS Benchmark 2.1.3) 
2024-05-13T12:00:02.000Z ERROR Critical: EC2 instance has no encryption enabled (CVE-2023-1234) 

Prediction:

As cloud adoption grows, Trivy will expand to cover more IaC frameworks like Pulumi and Crossplane, becoming the de facto standard for infrastructure security scanning.

Reference: How to Secure Terraform Code with Trivy

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram