Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[DevSecOps] Scan Terraform

Posted on July 27, 2023 By nim No Comments on [DevSecOps] Scan Terraform

Mình copy bài này:
https://spacelift.io/blog/what-is-tfsec

More and more organizations are adopting IaC to codify their infrastructure requirements and streamline the maintenance processes around it. While Terraform is one of the dominant technologies today in the space of Infrastructure as Code (IaC), there is still a lot of scope of improvement. One such opportunity is its SecOps aspect.

In this post, we will explore how tfsec – an open-source tool by Aqua Security – helps in identifying security shortcomings beforehand. Tfsec is a static analysis tool that scans Terraform code, identifies, and highlights gaps from the security aspect from an infrastructure and IaC perspective.

We will cover the topics below in this blog post, and also see tfsec in action.

Contents

Toggle
  • What is tfsec?
  • Tfsec features
    • 1. Comprehensive scanning of IaC
    • 2. Scanning modules and variables
    • 3. Detailed reporting and recommendations
    • 4. Integration with CI/CD Pipelines
    • 5. Policy Customization and Extensibility
  • Tfsec benefits
    • 1. Built-in checks
    • 2. Ease of use
    • 3. Strong community support
    • 4. Module scanning
  • How to use tfsec?
  • How to install tfsec?
    • How to install tfsec on Linux
    • How to install tfsec on macOS
    • How to install tfsec on Windows
    • How to install tfsec using go
    • How to install tfsec using Docker image
  • Working with tfsec locally
    • Understanding the output
    • Ignoring checks

What is tfsec?

Tfsec is a powerful static analysis security scanner that comes into play when it comes to securing our Terraform code. With the ability to run locally and integrate seamlessly into our CI pipelines, tfsec offers developer-friendly output and a comprehensive range of checks.

tfsec is specifically designed to analyze our Terraform code and identify potential misconfigurations that may pose security risks. By leveraging static analysis techniques, tfsec thoroughly examines our code to ensure it adheres to best security practices. Regardless of the cloud provider, with its extensive library of built-in rules, tfsec scans our code against hundreds of predefined checks, leaving no room for vulnerabilities.

To streamline the security review process, tfsec seamlessly integrates into our development workflow – both locally and/or into our CI pipelines. Its developer-friendly output provides clear and concise information about the security issues it discovers, allowing for efficient remediation. With tfsec, we can catch and address security concerns before they impact our infrastructure, saving valuable time and resources.

Tfsec is deeply integrated with the official HashiCorp Configuration Language (HCL) parser. This improves the accuracy of tfsec scans of our Terraform templates. Thus, tfsec can catch security vulnerabilities and misconfigurations early on. This proactive approach empowers developers to address potential security risks during the development phase itself, leading to a more secure infrastructure.

Tfsec features

Some of the top features which that tfsec appealing to use in our IaC workflows are described below.

1. Comprehensive scanning of IaC

tfsec has the ability to perform a thorough scan of the Terraform code, identifying potential vulnerabilities and misconfigurations before they are deployed into production. It supports multiple cloud providers, including AWS, Azure, and GCP, ensuring that our IaC is secure regardless of the platform we choose. Thus we can use a single tool to scan our entire infrastructure and streamline our security processes. 

2. Scanning modules and variables

Tfsec not only scans our main Terraform files but also examines modules (both local and remote) and variables. This feature ensures that our entire IaC is analyzed, and provides a comprehensive view of our infrastructure’s security posture. Tfsec evaluates HCL expressions, allowing it to detect potential issues that may not be apparent when examining static values.

3. Detailed reporting and recommendations

Tfsec provides developers with detailed reports and recommendations for fixing detected issues, making it easy to understand and remediate potential vulnerabilities in developer-friendly output. Various output formats are available, allowing developers to choose the one that best suits their needs. Tfsec also includes links to relevant documentation from AWS, Azure, GCP, and Terraform, ensuring that developers have all the information they need to fix issues and adhere to best practices.

4. Integration with CI/CD Pipelines

Tfsec is designed to integrate seamlessly with various CI/CD pipelines and IDEs, making it an important part of our development workflow. It can be easily integrated with popular CI/CD tools like GitHub Actions, GitLab CI, and Azure DevOps, allowing us to incorporate automated security scanning into your build and deployment processes.

5. Policy Customization and Extensibility

Tfsec offers the flexibility to define our custom policies and checks, ensuring that our IaC adheres to our organization’s specific security requirements. It is possible to create custom checks in tfsec using JSON or YAML. Tfsec allows us to exclude or include specific policies during the scanning process so that we can focus on specific security aspects or when we want to ignore certain policies that may not apply to our infrastructure.

There are many more handy features related to compatibility with CDK, functions, and expressions evaluation – all of them are listed in the Github repo here.

Tfsec benefits

As mentioned earlier, tfsec performs static analysis on Terraform configuration. By static analysis, there is no need to even initialize the Terraform project or run the plan and apply commands. It checks for misconfigurations in the directory where all the Terraform config files exist.

Some of the benefits of using tfsec are highlighted below.

1. Built-in checks

Tfsec supports major cloud providers like AWS, Azure, GCP, and other cloud platforms. It also includes checks for widely used solutions like Kubernetes, Github, and OpenStack. If you have never used any kind of checks on your Terraform project, then these exhaustive checks are a great place to begin as they readily highlight the security shortcomings in current configuration. This offsets the efforts required to learn the lessons and then implement security best practices.

2. Ease of use

Installing and getting started with tfsec locally is quite easy. It also supports DevOps pipeline tasks for Github Actions, Azure DevOps, and the likes which are readily usable. If there are custom checks implemented, they are automatically verified in any automation or CI workflow. The CLI output displays all the misconfigurations in a well-formatted manner, along with their severity. It also offers the output to be stored in a file in multiple user-friendly formats as build artifacts.

3. Strong community support

The built-in checks are essential contributions made globally by the users of all the organizations. It is the cumulative experience of the community of implementing best practices condensed in tfsec that helps make our infrastructure management via Terraform more secure.

4. Module scanning

We use modules to save time in reinventing the wheel. In this scenario, we often trust the module developer as far as internal working and security are concerned. Tfsec also scans the modules, making sure the best practices are met within.

The list above highlights some of the compelling benefits and reasons why tfsec should be used by the teams. 

How to use tfsec?

To begin using tfsec, start by installing it on your local machine. Tfsec is available for different platforms, including Windows, macOS, and Linux. We can either download the binary from the official GitHub repository or use a package manager like Homebrew (for macOS) or Chocolatey (for Windows) to install it. Once installed, ensure that the tfsec command is accessible from your command line. 

Navigate to the directory containing our Terraform code and execute the tfsec command followed by the appropriate flags. By default, tfsec scans all .tf and .tfvars files in the current directory and its subdirectories. It analyzes our Terraform configuration files and provides security-related feedback and recommendations.

We can customize the behavior by using flags such as --exclude to exclude certain directories or files, or --severity to filter results by severity level. The output is displayed in our terminal, and we can review the issues reported by tfsec to identify potential security vulnerabilities in our Terraform code.

Then using the Custom Inputs feature, you can integrate tfsec (or Checkov, Terrascan, Kics, and others) in your workflows with Spacelift. Security is one of Spacelift’s biggest priorities, so there are also state-of-the-art security solutions that are embedded inside the product, like Policy as Code, Encryption, Single Sign On (SSO), and Private Worker Pools.

Read more about integrating security tools with Spacelift.

How to install tfsec?

This section describes the installation procedure for tfsec on various platforms like Linux, MacOS, and Windows.

How to install tfsec on Linux

Download the tfsec binary by running the command below.

curl -L "$(curl -s https://api.github.com/repos/tfsec/tfsec/releases/latest | grep -o -E "https://.+tfsec-linux-amd64")" -o tfsec

Change the permissions of the downloaded file to execute the same.

chmod +x tfsec

Move this file under the bin directory, making sure the path to the bin directory is added to the PATH environment variable.

sudo mv tfsec /usr/local/bin

Alternatively, run a single command below, which effectively performs all the tasks above.

curl -s https://raw.githubusercontent.com/aquasecurity/tfsec/master/scripts/install_linux.sh | bash

How to install tfsec on macOS

Tfsec can be installed using Homebrew on macOS-based systems. To install, run the command below in a terminal.

brew install tfsec

How to install tfsec on Windows

Tfsec can be installed on Windows-based systems using the Chocolatey package manager.

choco install tfsec

How to install tfsec using go

If go is installed on any system, then the package managers above are not needed. It is also possible to install tfsec using go, by running the command below. This installs the latest version of tfsec.

go install github.com/aquasecurity/tfsec/cmd/tfsec@latest

How to install tfsec using Docker image

Alternatively, if Docker is installed on the system, and if we do not want to go through the installation process, we can run a quick scan using the official tfsec Docker image as shown in the example below.

docker run --rm -it -v "$(pwd):/src" aquasec/tfsec /src

Here, the /src directory is where all the Terraform files and sub-directories exist.

Working with tfsec locally

Let us begin by installing and using tfsec in one of the Terraform projects locally.

Once installed, let us begin by creating a Terraform project directory and by adding a main.tf file in it. We will attempt to create a VPC using the minimum required configuration and run tfsec in-built checks against the same.

The code below shows the minimal configuration required to create a VPC in AWS using Terraform.

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
  enable_dns_hostnames = true
  tags = {
    name = "main"
  }
}

At this point, the code is capable of creating the VPC with no problems.

However, to be sure about security practices being followed, let us run the tfsec scan in this directory. Open the terminal and navigate to this project directory.

Run the command below.

tfsec .

Understanding the output

The output should look similar to the one below.

Result #1 MEDIUM VPC Flow Logs is not enabled for VPC  
────────────────────────────────────────────────────────────────────────────────────────────────────────
  main.tf:1-7
────────────────────────────────────────────────────────────────────────────────────────────────────────
    1    resource "aws_vpc" "main" {
    2      cidr_block           = var.vpc_cidr
    3      enable_dns_hostnames = true
    4      tags = {
    5        name = "main"
    6      }
    7    }
────────────────────────────────────────────────────────────────────────────────────────────────────────
          ID aws-ec2-require-vpc-flow-logs-for-all-vpcs
      Impact Without VPC flow logs, you risk not having enough information about network traffic flow to investigate incidents or identify security issues.
  Resolution Enable flow logs for VPC

  More Information
  - https://aquasecurity.github.io/tfsec/v1.28.1/checks/aws/ec2/require-vpc-flow-logs-for-all-vpcs/
────────────────────────────────────────────────────────────────────────────────────────────────────────


  timings
  ──────────────────────────────────────────
  disk i/o             61.375µs
  parsing              177.375µs
  adaptation           70.834µs
  checks               3.057291ms
  total                3.366875ms

  counts
  ──────────────────────────────────────────
  modules downloaded   0
  modules processed    1
  blocks processed     7
  files read           3

  results
  ──────────────────────────────────────────
  passed               2
  ignored              0
  critical             0
  high                 0
  medium               1
  low                  0

  2 passed, 1 potential problem(s) detected.

Instead of reading from the top, let us read the output from bottom to up, as all the result details are summarized at the bottom.

The last line indicates how many checks have passed – two in this case and the number of potential problems detected by tfsec – one in this case.

The section above this line summarizes the results by providing various counts. The meaning of the count is explained below.

  1. Passed – This is the number of checks which were passed by tfsec, and that no action is required to close these gaps.
  2. Ignored – tfsec ignores some checks due to several reasons. It is possible to skip a certain check explicitly, which we will cover in the next section.
  3. Critical, high, medium, low – each tfsec check is associated with a level of severity or impact. Any failed check is counted against the respective severity. In our example, we have encountered a medium severity check.

Note: tfsec does not prevent Terraform from applying these changes. It is still perfectly fine to provision infrastructure without addressing the problems identified by tfsec. However, it is highly encouraged to resolve them for more secure infrastructure.

The next section above “results” is “counts”. These counts indicate the “code coverage” of the Terraform configuration. The counts are explained below.

  1. Modules downloaded – if our configuration reuses any externally downloaded modules, then all those modules are counted here.
  2. Modules processed – tfsec treats the Terraform configuration included in the current directory as a module being scanned. Thus this count value is calculated as the sum of all the externally downloaded modules + 1.
  3. Blocks processed – number Terraform blocks processed by tfsec. Currently, in my Terraform configuration, apart from the VPC block, there are additional blocks for variables and providers. Thus the count is 7.
  4. Files read – all the configuration blocks are spread across three files – namely “main.tf”, “provider.tf”, and “variables.tf”.

The timings section above counts represents the system stats used by tfsec to perform these checks. Tfsec is quite fast, so it usually does not cause any drastic performance impact.

The sections which follow above the “timings” section describe each problem in detail. The details of each problem are described with the information listed below.

  1. The severity of the problem detected
  2. Short description
  3. Location of the resource block where the problem exists.
  4. ID of the check, which can be used to refer to the associated documentation.
  5. Description of the impact to help us decide next actions
  6. Resolution suggestion
  7. More information with links to appropriate documentation

Ignoring checks

Let us pretend that the problem highlighted by tfsec is not that important to us and that it would be okay to ignore this. We can inform it to tfsec by adding a comment at the top of the resource block where this problem exists.

The format in which the comment needs to be added is shown below.

#tfsec:ignore:<check-id>

Our modified code should look like the one below. We have picked up the ID from the previous tfsec terminal output.

#tfsec:ignore:aws-ec2-require-vpc-flow-logs-for-all-vpcs
resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
  enable_dns_hostnames = true
  tags = {
    name = "main"
  }
}

Run the tfsec command again and observe the output below.

 timings
  ──────────────────────────────────────────
  disk i/o             410.167µs
  parsing              318.376µs
  adaptation           1.701375ms
  checks               3.9175ms
  total                6.347418ms

  counts
  ──────────────────────────────────────────
  modules downloaded   0
  modules processed    1
  blocks processed     7
  files read           3

  results
  ──────────────────────────────────────────
  passed               2
  ignored              1
  critical             0
  high                 0
  medium               0
  low                  0


No problems detected!

Since we had only one problem detected by tfsec, and we have chosen to ignore the same, tfsec now highlights “No problems detected!”.

Note how the ignored count is incremented by one in the counts section of the output.

DevSecOps, Terraform

Post navigation

Previous Post: [Renovate] Automate Dependency Management With Renovate From Mend
Next Post: [Python] use Try/Except in python

More Related Articles

[Terraform/GCP] Registering a Google Cloud Account is Free! GCP - Google Cloud
[Terraform] Your query returned no results. Please change your search criteria and try again Terraform
[Terraform] – Terraform Beginner – Lesson 7: Terraform Modules AWS - Amazon Web Service
[Terraform] Let’s look into For Function in terraform Terraform
[DevSecOps] What is DevSecOps DevSecOps
[Trivy] Protect your application by Trivy DevSecOps

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.