DEV Community

Cover image for Terraform Linting and Validation with a shell script
Rudolf Olah
Rudolf Olah

Posted on • Edited on

Terraform Linting and Validation with a shell script

Writing Terraform configurations is like writing any programming language; you must ensure your code is formatted correctly, linted, validated, and secure.

Formatting: This is similar to running prettier to adhere to a standard format, making the configurations more readable.

Linting with tflint: The tflint tool will scan for configuration errors and unused resource declarations and enforce naming conventions. There are rulesets for each of the major cloud providers (AWS, GCP, Azure).

Security check with tfsec/trivy: The tfsec tool scans for misconfigurations and, more importantly, to see if secrets such as access keys or tokens are included in the Terraform.

Validation: Before deploying your Terraform configurations, let's make sure everything is in order. This step will check the syntax and whether the configuration is internally consistent.

Designed to work with zsh, this script will run the above steps:

# Install:
# brew install tflint
# brew install tfsec
# brew install terraform
# nano /path/to/check_tf.sh
# chmod +x /path/to/check_tf.sh
#
# Usage:
# cd /path/to/terraform/tf_files
# tflint --init
# TFLINT_CONFIG=$(realpath ./.tflint.hcl) ./check_tf.sh
# TFLINT_CONFIG=/path/to/.tflint.hcl /path/to/check_tf.sh
if [ "$TFLINT_CONFIG" = '' ]; then
echo 'the TFLINT_CONFIG environment variable must be set'
exit 1
fi
echo "Checking Terraform configuration..."
echo "Formatting..."
terraform fmt
echo "Linting..."
tflint --config="$TFLINT_CONFIG" --recursive
echo "Checking security..."
tfsec
echo "Validating..."
terraform validate
view raw check_tf.sh hosted with ❤ by GitHub

You can use it as a git pre-commit hook if you setup the TFLINT_CONFIG variable.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more