Run Terraform via PR comments with apply-before-merge workflow
- 💬 PR Comment Triggered - Execute Terraform via
terraform planorterraform applycomments - 📦 Multi-Project Support - Manage multiple Terraform projects in one repository
- 🤖 Autoplan - Automatically run plan when Terraform files are modified
- ✅ Requirements Enforcement - Validate mergeable status and approvals before execution
- 📝 Formatted Output - Beautiful PR comments powered by tfcmt
Create .github/workflows/terraform-pr.yml:
name: Terraform PR
on:
issue_comment:
types: [created]
pull_request:
types: [opened, synchronize, closed]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
terraform:
runs-on: ubuntu-latest
if: |
github.event_name == 'pull_request' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
startsWith(github.event.comment.body, 'terraform'))
steps:
- name: Checkout PR code
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.7.0
- name: Run terraform-action
uses: tkasuz/terraform-action@v1.1.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
config-path: .terraform-action.yamlCreate .terraform-action.yaml:
automerge: true
projects:
- name: production
dir: terraform/production
autoplan:
enabled: true
when_modified: ["*.tf", "*.tfvars", ".terraform.lock.hcl"]
plan_requirements: [mergeable]
apply_requirements: [mergeable, approved]
- name: staging
dir: terraform/staging
autoplan:
enabled: true
when_modified: ["*.tf", "*.tfvars"]
plan_requirements: [mergeable]
apply_requirements: [mergeable, approved]
tfcmt:
enabled: true
skip_no_changes: trueComment on a pull request:
# 📋 Plan all projects
terraform plan
# 📋 Plan specific projects
terraform plan -project=production,staging
# 🚀 Apply all projects
terraform apply
# 🚀 Apply specific project
terraform apply -project=production| Field | Required | Description |
|---|---|---|
name |
✅ | Project name |
dir |
✅ | Directory containing Terraform files |
autoplan.enabled |
❌ | Enable automatic plan on file changes |
autoplan.when_modified |
❌ | File patterns that trigger autoplan |
plan_requirements |
❌ | Requirements for plan (default: [mergeable]) |
apply_requirements |
❌ | Requirements for apply (default: [mergeable, approved]) |
| Requirement | Description |
|---|---|
mergeable |
PR must be mergeable (no conflicts, passing checks) |
approved |
PR must have at least one approval |
"Terraform is not installed"
Add the
hashicorp/setup-terraform step before this action.
"Configuration file not found"
Ensure
.terraform-action.yaml exists in your repository root.
"PR requirements not met"
Verify the PR is mergeable and has required approvals.
"Project not found"
Check that project names in
-p flag match your config file.