Test Terraform policies
We recommend that you test your policies when you author or modify them. You can also include policy testing as part of a CI/CD pipeline, before enforcing them with HCP Terraform.
Overview
Test policies to help ensure that they work as expected before enforcing them in your organization. When you author or modify policies, update your tests as well, and run your tests before you commit updates to your VCS. You can also include policy tests as part of your CI/CD pipelines to automatically verify changes to your policies before you enforce them with HCP Terraform.
Run tests manually
- Write one or more policies in
.policy.hclfiles. - Create test cases for your policies in
.policytest.hclfiles. - Run your tests locally with the
tfpolicy testcommand. - Commit both policy and test files to your VCS.
- Configure a policy set in HCP Terraform to enforce your policies.
For more information about testing your policies on your local machine, refer to Test policies.
Automate tests
In addition to manually testing your policies on your local machine, you can integrate policy testing into your CI/CD pipeline. Configure your CI/CD pipeline to run all of your policy tests and ensure that they pass before merging changes to your VCS repository's main branch.
CI/CD integration examples
Refer to the following examples to learn how to integrate Terraform policy into popular CI/CD pipeline tools.
GitHub Actions
name: Test Terraform policies
on:
pull_request:
paths:
- 'policies/**'
- 'tests/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Download tfpolicy CLI
run: |
curl -o tfpolicy.tar.gz https://releases.hashicorp.com/tfpolicy/0.0.1/tfpolicy_0.0.1_linux_amd64.tar.gz
tar -xzf tfpolicy.tar.gz
chmod +x tfpolicy
- name: Run policy tests
run: ./tfpolicy test --policies=policies/
GitLab CI
test-policies:
stage: test
image: alpine:latest
before_script:
- apk add --no-cache curl tar
- curl -o tfpolicy.tar.gz https://releases.hashicorp.com/tfpolicy/0.0.1/tfpolicy_0.0.1_linux_amd64.tar.gz
- tar -xzf tfpolicy.tar.gz
- chmod +x tfpolicy
script:
- ./tfpolicy test --policies=policies/
only:
changes:
- policies/**
- tests/**
Jenkins Pipeline
pipeline {
agent any
stages {
stage('Test Policies') {
when {
changeset "policies/**"
}
steps {
sh '''
curl -o tfpolicy.tar.gz https://releases.hashicorp.com/tfpolicy/0.0.1/tfpolicy_0.0.1_linux_amd64.tar.gz
tar -xzf tfpolicy.tar.gz
chmod +x tfpolicy
./tfpolicy test --policies=policies/
'''
}
}
}
}