1.6.7.1. Checkov
Checkov is an open-source static analysis tool developed by Bridgecrew and now part of the Palo Alto Networks Prisma Cloud platform. It specializes in security checks for Infrastructure as Code (IaC). By scanning configuration code prior to cloud resource deployment, it detects insecure configurations and compliance risks in a timely manner. Simply put, Checkov parses template code (such as Terraform) to identify potential misconfigurations or vulnerabilities before resources are actually deployed, acting as a "security gatekeeper" for cloud environments. As a practical application of the Policy-as-Code philosophy, Checkov codifies a series of security best practices and compliance requirements into policies, automating the comparison and inspection of infrastructure code. With its extensive built-in rule library and high extensibility, Checkov plays a crucial role in the DevSecOps ecosystem—it seamlessly integrates into development and CI/CD workflows, helping teams enforce security policies during the development phase and preventing risks from reaching later environments.
1.6.7.1.1. Features and Use Cases
As a static analysis tool positioned for IaC frameworks like Terraform, Checkov provides comprehensive security and compliance scanning capabilities. Its primary use case is the static inspection of Terraform template code to uncover security vulnerabilities, misconfigurations, and policy violations at the configuration level. Specifically, it includes:
- Security Best Practices Checks: It comes with over a thousand built-in security baseline rules for cloud environments like AWS, Azure, and GCP. Examples include ensuring encryption is enabled for storage buckets, databases are not exposed to the public internet, and password policies meet requirements. Checkov compares Terraform configurations against these industry best practices, highlighting non-compliant areas and offering suggestions for improvement.
- Compliance Scanning: It supports mapping code against compliance standards such as CIS benchmarks, PCI-DSS, GDPR, and other common specifications. With these checks, teams can identify configurations that violate compliance requirements early on (e.g., disabled audit logging, insufficient retention periods), ensuring infrastructure adheres to regulatory and internal company policies.
- Policy Violation Detection: Beyond industry standards, Checkov can also execute organization-specific policy checks. For instance, requiring all resources to be tagged or prohibiting the use of certain insecure instance types. By writing custom rules (supporting policies written in Python or YAML), enterprises can solidify internal standards into automated checks.
- Secrets Scanning: It checks Terraform code for plaintext credentials or sensitive data. Checkov utilizes regular expressions, keyword matching, and entropy algorithms to detect leaks such as AWS keys, private keys, and database passwords within the code. This helps prevent credential leakage and hardcoded sensitive information in configurations.
- Context-Aware Analysis: Leveraging a graph-based relationship engine, Checkov goes beyond checking individual resources to execute context-aware policies based on relationships between resources. For example, it can assess the risk of a security group rule being too permissive specifically when applied to an instance in a public subnet. This graph-based analysis makes inspections smarter and covers more complex scenarios.
- Multi-Framework Support: Although this section focuses on Terraform, Checkov actually supports various common IaC frameworks, including Terraform Plan, CloudFormation, Kubernetes YAML, Helm, Serverless, and more. This means teams can use the same tool for security scanning regardless of the template language adopted (cross-cloud policy details are omitted here). This multi-platform compatibility makes Checkov a universal tool in the cloud-native infrastructure code security domain.
- Rich Reporting: Checkov supports outputting scan results in multiple formats for both human and system consumption. In addition to the default CLI console output, it can generate JSON reports, JUnit XML test reports, SARIF files, and GitHub-flavored Markdown. These diverse output forms facilitate integration with other systems: for example, using JUnit output for CI platform parsing and display, or SARIF output to upload results to code hosting platforms for security analysis views.
Through these features, Checkov is able to perform a comprehensive static analysis of Terraform modules and configurations. During the scan, it lists every detected issue, including the violated rule ID, severity level, affected resources, and corresponding remediation guidance. For each violation, Checkov typically provides a reference link or description explaining how to fix it (hints can be disabled via the --no-guide argument). This series of static checks does not require actual cloud resource deployment, making it fast and broad in coverage, providing teams with timely feedback and remediation suggestions.
1.6.7.1.2. Why We (Might) Need Checkov
In large teams and complex projects, introducing IaC static scanning tools like Checkov is vital for Terraform module governance. Here is an explanation of its value from several perspectives:
- Security Assurance for Module Reuse: Terraform encourages code reuse through modules. However, if a widely reused module contains configuration flaws, it can lead to identical security risks appearing across numerous environments. Using Checkov allows for the automatic scanning of module code at the time of publication or integration, detecting insecure settings early (e.g., a module not enforcing encryption or exposing default ports). This way, organizations can fix hidden dangers before promoting the module for reuse, ensuring that shared modules are secure and reliable across all projects. From a governance perspective, Checkov establishes a quality gate for modules, preventing bad configurations from spreading.
- Team Collaboration and Standardization: In scenarios where multiple people collaborate on Terraform code, different members may have inconsistent understanding and execution of security best practices. Checkov provides a unified standard for automated checks, acting as a "code auditor" that never overlooks details. Every time code is submitted, Checkov audits it against the same standards, ensuring everyone follows the same security and compliance baselines. This reduces the burden and subjective differences of manual Code Reviews, allowing new members to immediately know which configurations do not meet team standards. By institutionalizing security rules into a tool, team collaboration becomes smoother, and the style and quality of infrastructure code become more consistent.
- Reducing Cloud Configuration Risks: Configuration errors are one of the main causes of cloud environment security incidents. Many disasters stem from simple mistakes, such as overly permissive storage bucket permissions, disabled logging, or network ports exposed to the public internet. Checkov's role is to capture these misconfigurations before risks turn into consequences and stop them from entering the deployment process. This "Shift Left" security approach significantly reduces the probability of cloud environments suffering attacks or violations. Compared to discovering issues afterwards through cloud monitoring or penetration testing, proactive static scanning is not only more efficient and cost-effective but also avoids the potential losses caused by exposing misconfigurations in production environments. In short, Checkov moves the cloud security defense line forward, providing critical support for module governance and overall infrastructure security.
It is worth mentioning that the philosophy embodied by Checkov is "Prevention is better than cure." By performing checks before deployment, teams can follow best practices and security policies, avoiding the high cost of fixing configuration vulnerabilities later. The sooner issues are found and fixed, the more time and resources are saved—Checkov is the sharp tool for practicing this philosophy.
1.6.7.1.3. Installation and Local Usage
Checkov is implemented in Python, so a Python 3.7+ runtime environment is required (Terraform code itself is recommended to be version 0.12+). Installation is quite simple and can be completed via the Python package manager pip in most cases:
# Install Checkov using pip (Cross-platform)
pip install checkov
Or:
pip3 install checkov
# (Optional) Install Checkov using Homebrew (macOS)
brew install checkov
For environments where direct installation is not convenient (such as CI servers), official Docker images are also provided to run Checkov. No installation is needed; simply pull the image and run the command, for example:
# Run Checkov using the official Docker image to scan the current directory
docker pull bridgecrew/checkov
docker run --rm -v "$(pwd):/iac" bridgecrew/checkov -d /iac --framework terraform
The above command executes Checkov inside a container, mounting the current working directory into it and scanning the Terraform configurations within.
Once installed, you can use the checkov command via the command line to scan Terraform templates. The basic usage is very intuitive; you can scan an entire Terraform configuration project by specifying a directory, or point to a specific file:
# Scan all Terraform configuration files in a specific directory
checkov --directory /path/to/terraform/code
# Scan a single Terraform file
checkov --file /path/to/example.tf
After executing the above commands, Checkov will parse the Terraform templates and run built-in policies against every resource configuration found. The scan results will be output to the terminal, including passed checks and failed checks. For failed items, Checkov displays the rule ID, the name and type of the violating resource, a brief description of the issue, and suggested remediation measures or reference links.
Here is an example from TerraGoat, a sample repository designed for researching Terraform security configuration issues:
resource "azurerm_managed_disk" "example" {
name = "terragoat-disk-${var.environment}"
location = var.location
resource_group_name = azurerm_resource_group.example.name
storage_account_type = "Standard_LRS"
create_option = "Empty"
disk_size_gb = 1
encryption_settings {
enabled = false
}
tags = {
git_commit = "d68d2897add9bc2203a5ed0632a5cdd8ff8cefb0"
git_file = "terraform/azure/storage.tf"
git_last_modified_at = "2020-06-16 14:46:24"
git_last_modified_by = "nimrodkor@gmail.com"
git_modifiers = "nimrodkor"
git_org = "bridgecrewio"
git_repo = "terragoat"
yor_trace = "d17da7b3-f1c5-4723-9f77-d1b9069459c7"
}
}
resource "azurerm_storage_account" "example" {
name = "tgsa${var.environment}${random_integer.rnd_int.result}"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "GRS"
queue_properties {
logging {
delete = false
read = false
write = true
version = "1.0"
retention_policy_days = 10
}
hour_metrics {
enabled = true
include_apis = true
version = "1.0"
retention_policy_days = 10
}
minute_metrics {
enabled = true
include_apis = true
version = "1.0"
retention_policy_days = 10
}
}
tags = {
git_commit = "5c6b5d60a8aa63a5d37e60f15185d13a967f0542"
git_file = "terraform/azure/storage.tf"
git_last_modified_at = "2021-05-02 10:06:10"
git_last_modified_by = "nimrodkor@users.noreply.github.com"
git_modifiers = "Adin.Ermie/nimrodkor"
git_org = "bridgecrewio"
git_repo = "terragoat"
yor_trace = "23861ff4-c42d-495e-80ac-776c74035f43"
}
}
resource "azurerm_storage_account_network_rules" "test" {
resource_group_name = azurerm_resource_group.example.name
storage_account_name = azurerm_storage_account.example.name
default_action = "Deny"
ip_rules = ["127.0.0.1"]
bypass = ["Metrics"]
}
WARNING!! This example is intentionally set up to contain multiple security issues to test the policy library of strategy checking tools. Please DO NOT do this in a production environment!!
Let's try scanning this file with Checkov:
/workspaces/terragoat/terraform/azure (master) $ checkov --file storage.tf
[ terraform framework ]: 100%|████████████████████|[1/1], Current File Scanned=storage.tf
[ secrets framework ]: 100%|████████████████████|[1/1], Current File Scanned=storage.tf
_ _
___| |__ ___ ___| | _______ __
/ __| '_ \ / _ \/ __| |/ / _ \ \ / /
| (__| | | | __/ (__| < (_) \ V /
\___|_| |_|\___|\___|_|\_\___/ \_/
By Prisma Cloud | version: 3.2.439
terraform scan results:
Passed checks: 5, Failed checks: 14, Skipped checks: 0
Check: CKV_AZURE_36: "Ensure 'Trusted Microsoft Services' is enabled for Storage Account access"
PASSED for resource: azurerm_storage_account.example
File: /storage.tf:23-60
Guide: [https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-networking-policies/enable-trusted-microsoft-services-for-storage-account-access](https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-networking-policies/enable-trusted-microsoft-services-for-storage-account-access)
Check: CKV_AZURE_3: "Ensure that 'enable_https_traffic_only' is enabled"
PASSED for resource: azurerm_storage_account.example
File: /storage.tf:23-60
Guide: [https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/azr-general-3](https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/azr-general-3)
Check: CKV_AZURE_206: "Ensure that Storage Accounts use replication"
PASSED for resource: azurerm_storage_account.example
File: /storage.tf:23-60
Guide: [https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/azr-general-206](https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/azr-general-206)
Check: CKV_AZURE_244: "Avoid the use of local users for Azure Storage unless necessary"
PASSED for resource: azurerm_storage_account.example
File: /storage.tf:23-60
Guide: [https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/bc-azure-244](https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-general-policies/bc-azure-244)
Check: CKV_AZURE_35: "Ensure default network access rule for Storage Accounts is set to deny"
PASSED for resource: azurerm_storage_account_network_rules.test
File: /storage.tf:62-69
Guide: [https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-networking-policies/set-default-network-access-rule-for-storage-accounts-to-deny](https://docs.prismacloud.io/en/enterprise-edition/policy-reference/azure-policies/azure-networking-policies/set-default-network-access-rule-for-storage-accounts-to-deny)
Check: CKV_AZURE_251: "Ensure Azure Virtual Machine disks are configured without public network access"
FAILED for resource: azurerm_managed_disk.example
File: /storage.tf:1-21
1 | resource "azurerm_managed_disk" "example" {
2 | name = "terragoat-disk-${var.environment}"
3 | location = var.location
4 | resource_group_name = azurerm_resource_group.example.name
5 | storage_account_type = "Standard_LRS"
6 | create_option = "Empty"
7 | disk_size_gb = 1
8 | encryption_settings {
9 | enabled = false
10 | }
11 | tags = {
12 | git_commit = "d68d2897add9bc2203a5ed0632a5cdd8ff8cefb0"
13 | git_file = "terraform/azure/storage.tf"
14 | git_last_modified_at = "2020-06-16 14:46:24"
15 | git_last_modified_by = "nimrodkor@gmail.com"
16 | git_modifiers = "nimrodkor"
17 | git_org = "bridgecrewio"
18 | git_repo = "terragoat"
19 | yor_trace = "d17da7b3-f1c5-4723-9f77-d1b9069459c7"
20 | }
21 | }
...
We can see which checks passed, which failed, the description of failed rules, and information about the code blocks triggering the failures.
The Checkov CLI provides rich arguments to customize scanning behavior:
- Use
-dor--directoryto recursively scan a directory, or-f/--fileto target a single file. If unspecified, it scans the current directory by default. - Use the
--checkargument to run only specified rule checks, for example, to check only specific rule IDs: ```bash checkov --directory . --check CKV_AWS_20,CKV_AWS_57
The above example will only run checks for rules *CKV_AWS_20* and *CKV_AWS_57*, useful for focusing on specific issues.
* Conversely, use the `--skip-check` argument to **skip certain checks**:
```bash
checkov -d . --skip-check CKV_AWS_20
This will ignore rule CKV_AWS_20 during the scan. This is useful for skipping rules that are not applicable to the team due to special circumstances. The --skip-check and --check arguments also support specifying risk level keywords (HIGH, MEDIUM, etc.) to filter high or medium risk issues.
- Use
-o/--outputto specify the output format, e.g.,-o jsonfor JSON,-o junitxmlto generate JUnit XML reports for CI consumption, or-o sarifto generate SARIF format for code scanning platforms. You can also save results to a file using--output-file-path. - By default, if any check fails, the Checkov process will end with a non-zero exit code, which can be used by scripts or CI to determine scan failure. If you wish to not fail the process even if violations are found, use the
--soft-failargument to set the exit code to0. This is useful during initial implementation or trial runs to avoid blocking teamwork due to scan failures. - Checkov also allows managing arguments centrally via a configuration file. You can create a
config.yamlcontaining the above command-line options (e.g., directory to scan, checks to skip, output format) and load it at runtime using--config-file config.yaml. With the--create-configargument, you can even automatically generate a configuration file template based on given command-line options for further customization.
In addition to manual execution, integrating Checkov into developers' daily workflows significantly improves efficiency. In local development environments, Git hooks (pre-commit) are a common integration method. Through Git's pre-commit hooks, Checkov checks can be automatically executed when a developer commits code, blocking code that does not meet policies from entering the repository. The implementation involves using the open-source pre-commit framework and adding the Checkov hook configuration provided by Bridgecrew. For example, add .pre-commit-config.yaml to the project root directory:
- repo: [https://github.com/bridgecrewio/checkov.git](https://github.com/bridgecrewio/checkov.git)
rev: '' # change to tag or sha
hooks:
- id: checkov
# - id: checkov_container
# - id: checkov_diff
# - id: checkov_diff_container
# - id: checkov_secrets
# - id: checkov_secrets_container
Then execute pre-commit install --install-hooks to install the hook. Thereafter, every time git commit is run, Checkov will automatically scan the changed Terraform files; if there are any failed checks, it will reject the commit and report the issues, enabling developers to fix them before committing. Through this mechanism, security checks are invisibly integrated into the daily coding process, reducing the chance of discovering problems later. It is worth noting that Checkov also provides a VS Code editor extension, which can scan in real-time and provide inline security suggestions while developing Terraform files. Whether using the IDE plugin or Git hooks, local integration ensures issues are discovered and resolved at the earliest opportunity, improving module code quality.
1.6.7.1.4. Integration into CI/CD Pipelines
Integrating Checkov into Continuous Integration/Continuous Deployment (CI/CD) pipelines allows for setting automated security gates before code merging and deployment. Below is an introduction on how to embed Checkov into mainstream CI/CD platforms.
1.6.7.1.4.1. Integration in GitHub Actions
GitHub Actions provides a convenient mechanism to incorporate Checkov into workflows. Bridgecrew has released a ready-made Checkov Action that can be directly used to scan Terraform code. With this Action, we don't need to install the environment ourselves; configuration is very simple. For example, add a new workflow .github/workflows/checkov.yml:
---
name: Checkov
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python 3.8
uses: actions/setup-python@v4
with:
python-version: 3.8
- name: Test with Checkov
id: checkov
uses: bridgecrewio/checkov-action@master
with:
directory: example/examplea
framework: terraform
The above configuration runs a Checkov job every time a Pull Request is submitted: it first checks out the code, then uses the official Checkov Action to perform the scan. We specify via parameters to scan the Terraform configuration within the example/examplea directory of the current repository. The execution effect is: if Checkov detects any failed rules, the Action will mark the check as failed, causing the GitHub PR check status to turn ❌ and preventing insecure configuration changes from being merged. Developers can see which checks failed on the Pull Request page and click for details to understand the specific violating resources and reasons. With GitHub Actions, integrating security scanning into the code review process achieves automated security auditing for every change. Additionally, Checkov supports outputting SARIF format combined with GitHub Code Scanning, allowing scan results to appear in the repository's security tab, further enhancing visibility (requires separate configuration to upload SARIF).
As seen from the above example, simply adding a step to execute checkov in the pipeline and configuring its parameters and report format is sufficient. When the scan finds issues, failing the pipeline (or blocking the merge) realizes continuous governance of Terraform modules. In large projects, these CI integration configurations can be templated or centrally managed so that all projects within the organization can easily use the same security scanning standards. Continuous automated checks can significantly raise the security baseline of Terraform modules, and when combined with the previously mentioned local scanning methods, truly form a comprehensive module governance process from development to deployment, ensuring that every step of Infrastructure as Code is safeguarded by security.
In summary, Bridgecrew's Checkov tool provides powerful support for Terraform module governance. From local scanning during the developer's coding phase to automated auditing in CI pipelines, Checkov deeply integrates security and compliance checks into the Terraform module lifecycle. With it, teams can confidently reuse modules on a large scale while maintaining control over cloud environment risks. In the practice of module governance, introducing Checkov not only improves efficiency but also significantly enhances the security and reliability of infrastructure code, escorting the enterprise's cloud infrastructure.