Terraform Security in GitLab CI:
Complete Integration Guide
A complete .gitlab-ci.yml configuration for automated terraform security scanning — with plan scanning, fail-on-violation, and MR blocking.
GitLab CI is the pipeline of choice for thousands of enterprise DevOps teams. Adding terraform security in GitLab CI with TFGaurd takes less than 10 minutes — and turns every merge request into a security gate.
This guide covers the complete .gitlab-ci.yml pipeline: initializing Terraform, generating a plan, scanning it with TFGaurd, uploading reports as artifacts, and configuring the pipeline to fail on high-severity violations.
Key Advantage: TFGaurd runs entirely on your GitLab Runner. No code is sent to external servers. Your Terraform HCL and plan JSON stay within your self-hosted or GitLab.com runner environment.
Pipeline Architecture Overview
A well-structured GitLab CI pipeline for Terraform security has four stages, each with a clear responsibility:
Syntax validation. Run terraform validate to catch HCL syntax errors before investing runner minutes in a full plan.
Generate plan JSON. Run terraform plan and export to JSON. This is the input TFGaurd needs for deep plan-file analysis.
TFGaurd scan. Scan the plan JSON against 1200+ security rules. Fail the pipeline if violations exceed your configured threshold.
Optional apply. Only runs if all previous stages pass. Protect this stage with when: manual for production environments.
Complete .gitlab-ci.yml Configuration
Paste this configuration into your project root. Adjust TF_ROOT to match your Terraform directory.
Configuring GitLab CI/CD Variables
Store sensitive values in Settings → CI/CD → Variables. Mark cloud credentials as Masked and Protected:
AWS_ACCESS_KEY_ID— AWS access key (masked, protected)AWS_SECRET_ACCESS_KEY— AWS secret key (masked, protected)TFGAURD_API_KEY— Optional; unlocks premium GCP/Azure/Oracle rulesTFGAURD_FAIL_ON— Override severity threshold per environment
Environment-Scoped Variables: Set TFGAURD_FAIL_ON=high for production and TFGAURD_FAIL_ON=critical for staging environments using GitLab's environment-scoped variable feature.
Blocking Merge Requests on Violations
TFGaurd returns exit code 1 when violations meet or exceed your --fail-on threshold. GitLab CI automatically marks the pipeline as failed, which prevents the merge request from being merged if you've configured pipelines must succeed in your branch protection rules.
Enable this in Settings → Repository → Protected Branches → check "Pipelines must succeed" for your main branch.
Important: The tfgaurd:scan job runs with when: always for artifacts — meaning the report is uploaded even when the scan fails. This lets you review the full violation list before fixing and retrying.
Secure Your GitLab Terraform Pipeline
Free for all AWS rules. Premium plan unlocks 1200+ rules for GCP, Azure, and Oracle.
Start Free — No Card Required