Using Terrascan for Static Code Analysis of Your Infrastructure Code (part 2)
You followed my advice and configured terrascan as a pre-commit hook to scan your terraform code for security weaknesses on your desktop before being committed into your repository.
The setup allows you to quickly check any security issues before they’re introduced into your AWS environment.
You’ve been using it for a while and you’re pretty happy that it has caught some issues before you accidentally pushed them to your GitHub repository.
Unfortunately, not all of your co-workers have it installed and some nasty bugs have been committed into one of your feature branches.
Luckily, terrascan can be used as a step in your continuous integration (CI) pipeline. This would allow you to test your terraform code before any security weaknesses are merged into your master branch.
How do you do that?
Let’s create an example repo.
I’ll be using “hub” for this example on my mac. If you don’t have it installed you can follow the instructions for your OS here. Here’s an example using the org “cloud-security-musings” and the repo “terrascan-example”. You’ll need to use your own username/repo combination:
You should now have a new repository created in GitHub and configured as a remote named “origin”. Let’s confirm.
As in part 1 of this blog series, you need to add a “.pre-commit-config.yaml” file added to the top-level of your repository with the following contents:
Let’s also add an example terraform file to “infra/s3.tf” containing a security issue, so we can test.
Finally, we will follow the instructions here to run pre-commit as part of CI in a GitHub action. To do this you will add the following code to a file named “.github/workflows/precommit.yaml”:
Now, let’s push our changes and see what happens:
Now the action should run to evaluate your s3.tf file since we configured it to run on every push. You can browse to the GitHub actions tab in your repo to see the output of the action. Here’s what I see for my repo at https://github.com/cloud-security-musings/terrascan-examples/actions.
Since we had a security weakness in the s3.tf file, the GitHub action failed. If you click on “pre-commit”, you can see the details of the CI job where the failure is shown:
As the error message indicates. Our aws_s3_bucket resource has a “public-read-write” ACL. Let’s fix the issue by updating infra/s3.tf with the following:
Then execute the commands below:
As expected, you should see the action now succeed indicated by a green checkmark:
What if I don’t use GitHub Actions for CI?
If you don’t use GitHub or GitHub actions for continuous integration, a similar setup can be accomplished with any CI tool. Here’s documentation on how to run pre-commit in other continuous integration tools: https://pre-commit.com/#usage-in-continuous-integration
What other security checks you perform on your CI builds for infrastructure code?