terrascan icon indicating copy to clipboard operation
terrascan copied to clipboard

Using terrascan in Git pre-commit hooks leads to 'error: invalid object'

Open sfuerte opened this issue 3 years ago • 1 comments

  • terrascan version:
$ terrascan version
version: v1.13.0
  • Operating System:
$ > sw_vers
ProductName:	macOS
ProductVersion:	12.1
  • Git version
$ git --version
git version 2.35.0

Description

A simple pre-commit hook (via Bash script wrapper - .git/hooks/pre-commit) leads to failure to do a commit after, e.g.

#!/bin/bash
set -e    # -o errexit
set -x

terrascan scan --non-recursive -i terraform -d . || true  # need the output at this point, not an error

Here an example of a commit attempt:

$ git commit -am "test commit" && git push
+ terrascan scan --non-recursive -i terraform -d .
...
Scan Summary -

	File/Folder         :	....
	IaC Type            :	terraform
	Scanned At          :	2022-01-25 20:45:28.668204 +0000 UTC
	Policies Validated  :	13
	Violated Policies   :	4
	Low                 :	0
	Medium              :	3
	High                :	1
+ true
error: invalid object 100644 f3df96b5ddfbb5d293f8329003ddfea2fe3dfa4b for '.github/ISSUE_TEMPLATE/bug_report.md'
error: Error building trees

After search and digging, it lead to https://github.com/pre-commit/pre-commit/issues/1849 and https://github.com/pre-commit/pre-commit/issues/300. And the former comments with

please report to [the tool maintainer] -- they need the same code as in our no_git_env helper if they are dealing with doing git writes

What I Did

adding the following to the wrapper script

env | grep -E "(GIT|TF)" || true
git status

leads to another error:

$ git commit -am "test commit" && git push
+ terrascan scan --non-recursive -i terraform -d .
...
+ git status
fatal: unable to read f3df96b5ddfbb5d293f8329003ddfea2fe3dfa4b

unsetting GIT_INDEX_FILE env variable after terrascan run fixes Git usage INSIDE the wrapper but still fails with the first error:

export GIT_INDEX_FILE=
env | grep -E "(GIT|TF)" || true
git status
$ git commit -am "test commit" && git push
+ terrascan scan --non-recursive -i terraform -d .
...
+ git status
On branch test
Changes to be committed:
...
error: invalid object 100644 f3df96b5ddfbb5d293f8329003ddfea2fe3dfa4b for '.github/ISSUE_TEMPLATE/bug_report.md'
error: Error building trees

sfuerte avatar Jan 25 '22 21:01 sfuerte

I ran into this today. This was my workaround...

  - repo: local
    hooks:
      - id: terrascan
        name: terrascan
        description: Runs terrascan on Terraform templates.
        language: system
        entry: >
          /bin/bash -c "
          unset GIT_INDEX_FILE;
          terrascan scan --use-terraform-cache -i terraform;
          "
        files: \.tf$
        exclude: \.terraform/.*$
        require_serial: true

I know this issue is old, but its still valid.

AbrohamLincoln avatar Mar 15 '24 16:03 AbrohamLincoln