Skip to content

Jamonygr/terraform-github-actions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

31 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Terraform GitHub Actions

Terraform License: MIT GitHub Actions

Terraform GitHub Actions banner

Pipeline components overview

Reusable GitHub Actions for Terraform workflows. Includes plan, apply, validate, security scanning, cost estimation, and more. Automate your infrastructure deployments with production-ready CI/CD pipelines.


πŸ“‹ Table of Contents


✨ Features

Feature Description
οΏ½ OIDC Authentication Secure Azure authentication without long-lived secrets
πŸ”„ Plan & Apply Safe infrastructure changes with plan review and approval gates
πŸ”’ Security Scanning Integrated tfsec, Checkov, and TFLint for compliance
πŸ’° Cost Estimation Infracost integration for cost visibility
πŸ“Š Metrics & Reporting Resource inventory, change logs, and dependency graphs
πŸ§ͺ Testing Terratest integration for infrastructure testing
πŸ” Drift Detection Scheduled detection of infrastructure drift
πŸ” Secret Scanning Detect hardcoded secrets before deployment
πŸ“ Documentation Auto-generate terraform-docs
πŸ’Ύ State Backup & Restore Automated state file backups with restore capability
πŸ’¬ PR Comments Automatic plan/cost/security summaries on pull requests
πŸ“’ Notifications Slack, Teams, Discord integration
🏷️ Module Versioning Semantic versioning for modules
🚨 Policy Checks OPA/Sentinel policy validation
⚑ Plugin Caching Faster builds with Terraform plugin caching

πŸš€ Quick Start

1. Copy the Actions to Your Repository

# Clone this repository
git clone https://github.com/Jamonygr/terraform-github-actions.git

# Copy the .github folder to your Terraform project
cp -r terraform-github-actions/.github your-terraform-project/

2. Set Up Authentication

Option A: OIDC (Recommended) πŸ”

Add these Variables to your GitHub repository:

Variable Description Required
AZURE_CLIENT_ID Azure AD Application (Client) ID βœ… Yes
AZURE_TENANT_ID Azure AD Tenant ID βœ… Yes
AZURE_SUBSCRIPTION_ID Azure Subscription ID βœ… Yes
USE_OIDC Set to true βœ… Yes

Add these Secrets:

Secret Description Required
TF_STATE_RG Terraform state resource group βœ… Yes
TF_STATE_SA Terraform state storage account βœ… Yes
INFRACOST_API_KEY Infracost API key ❌ Optional

See SETUP.md for detailed OIDC configuration instructions.

Option B: Service Principal (Legacy)

Add these Secrets to your GitHub repository:

Secret Description Required
AZURE_CREDENTIALS Azure service principal JSON βœ… Yes
TF_STATE_RG Terraform state resource group βœ… Yes
TF_STATE_SA Terraform state storage account βœ… Yes
INFRACOST_API_KEY Infracost API key ❌ Optional

3. Trigger the Workflow

# Push changes to trigger the pipeline
git add .
git commit -m "Add Terraform GitHub Actions"
git push

πŸ“š Documentation

Full documentation is available in the repo wiki folder. Start here:

Diagram Gallery

Pipeline overview

Modes diagram

Architecture overview

Workflow triggers

Authentication options

Environment promotion

Security layers

Cost visibility

Testing pyramid

Drift detection loop

State backup and restore

Policy and approval gates

Ephemeral PR environment

Actions catalog

Observability outputs


πŸ“¦ Actions Reference

Core Actions

Action Description Key Inputs
setup Shared Terraform setup with caching terraform_version, use_oidc
validate Terraform format and validate working_directory
plan Initialize and create execution plan use_oidc, var_file, state_key
apply Apply Terraform changes use_oidc, plan_artifact
destroy Destroy infrastructure use_oidc, confirm: DESTROY

Security Actions

Action Description Tools Used
security Security scanning tfsec, Checkov, TFLint
secret-scan Detect hardcoded secrets Gitleaks with SARIF upload
policy-check Policy validation OPA, Conftest

State Management Actions

Action Description Key Features
state-backup Backup state files Auto-cleanup, retention policy
state-restore Restore from backup List backups, confirm required
drift-detect Detect infrastructure drift Auto-create issues

Communication Actions

Action Description Supported
pr-comment Post summaries to PRs Plan, cost, security
notification Send notifications Slack, Teams, Discord

Utility Actions

Action Description Output
cost-estimate Infrastructure cost estimation Monthly cost, cost diff
terraform-docs Generate documentation README updates
graph Dependency visualization SVG/PNG graph
resource-inventory List managed resources Resource report
changelog Generate change log CHANGELOG.md
metrics Pipeline metrics Duration, resource counts
module-version Module versioning Versions JSON, update check
terratest Infrastructure testing Test results

πŸ“ Workflow Example

Basic Workflow

name: 'Terraform'

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:
    inputs:
      action:
        type: choice
        options: [plan, apply, destroy]
        default: 'plan'

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Validate
        uses: ./.github/actions/validate

      - name: Security Scan
        uses: ./.github/actions/security

      - name: Plan
        uses: ./.github/actions/plan
        with:
          azure_credentials: ${{ secrets.AZURE_CREDENTIALS }}
          backend_resource_group: ${{ secrets.TF_STATE_RG }}
          backend_storage_account: ${{ secrets.TF_STATE_SA }}
          state_key: 'myproject.tfstate'
          var_file: 'environments/lab.tfvars'
          environment: 'lab'

      - name: Cost Estimate
        uses: ./.github/actions/cost-estimate
        with:
          api_key: ${{ secrets.INFRACOST_API_KEY }}
          var_file: 'environments/lab.tfvars'

πŸ”„ Pipeline Stages

The unified workflow (terraform.yml) supports single, matrix, and drift modes. High-level view:

Pipeline overview

Stage Details

Stage Job(s) Purpose Notes
0 router Select mode (single, matrix, drift) repo-hygiene optional
1 format Enforce terraform fmt Blocking
2 validate Validate configuration Blocking
3 Security suite tfsec, Checkov, secret scan, ShellCheck Terrascan optional
4 Lint and policy TFLint, policy checks, terraform-docs Docs check optional
5 Analysis Graph + module versions Always on
6 Cost and versions Infracost + provider checks Cost is single mode only
7 plan Plan + PR comment + blast radius Single mode only
8 apply Apply in single mode Auto on push unless AUTO_APPLY=false; environment gates still apply
9 destroy Manual destroy + confirm Environment gates
10 metrics Post-apply reporting Single mode only

Optional post-plan actions include tag audit, Terratest PR integration tests, ephemeral PR environments, and canary apply. Many stages are gated by mode, event, or repo variables, so plan-only runs will show skipped jobs. See Pipeline Stages for the full list and mode-specific jobs (matrix and drift).


βš™οΈ Configuration

Workflow Inputs

Input Description Default Options
mode Pipeline mode single single, matrix, drift
environment Target environment (single mode) lab dev, lab, staging, prod
environments Target environments (matrix mode) dev,staging,prod Comma-separated list
action Pipeline action plan plan, apply, destroy
destroy_confirm Destruction confirmation - Type DESTROY
working_directory Terraform working directory ./test Any relative path
create_drift_issue Create GitHub issue on drift true true, false

Note: this repository ships a minimal Terraform config in ./test, so the workflow defaults to ./test. Set working_directory to . or your own path (or set TF_WORKING_DIRECTORY) when using your own Terraform layout.

Environment Variables

env:
  TF_VERSION: '1.9.0'          # Terraform version
  ENVIRONMENT: 'lab'            # Default environment
  WORKING_DIRECTORY: './test'   # Default for this repo; override as needed

Optional Repository Variables

Variable Name Description
TF_WORKING_DIRECTORY Default Terraform working directory (e.g., ./test)
ENABLE_TERRAFORM_TESTS Set to false to disable terraform test stage
ENABLE_MODULE_CONTRACTS Enable module contract checks for modules/
FAIL_ON_MODULE_CONTRACTS Fail pipeline when contract checks find issues
DOCS_ENFORCE Enforce terraform-docs check (fail on diff)
ENABLE_TERRASCAN Enable Terrascan security scan
TERRASCAN_VERSION Override Terrascan version (default 1.18.3)
AUTO_APPLY Auto-apply on push unless set to false
REQUIRED_TAG_KEYS Comma-separated required tag keys for tag audit
FAIL_ON_TAG_AUDIT Fail pipeline when tag audit finds missing tags
ENABLE_CANARY Enable canary apply before prod
CANARY_ENVIRONMENT Environment name for canary (e.g., canary)
CANARY_VAR_FILE Var file for canary (default environments/<env>.tfvars)
CANARY_STATE_KEY State key for canary (default <env>.terraform.tfstate)
ENABLE_EPHEMERAL_ENV Enable ephemeral PR environment (apply + destroy)
EPHEMERAL_VAR_FILE Var file for ephemeral PR environment
ENABLE_REPO_HYGIENE Enable repo hygiene checks (branch protection)
FAIL_ON_REPO_HYGIENE Fail pipeline if hygiene checks fail

Additional optional variables (health checks, dependency checks, quotas, SBOM, auto-rollback, etc.) are documented in Pipeline Stages.

Concurrency Control

concurrency:
  group: terraform-${{ github.ref }}-${{ inputs.environment || github.event.inputs.environment || github.event.inputs.mode || 'default' }}
  cancel-in-progress: false     # Never cancel in-progress runs

πŸ’° Cost Estimation

The pipeline integrates with Infracost for cost visibility.

Setup

  1. Get a free API key from Infracost
  2. Add INFRACOST_API_KEY to your repository secrets

Sample Output

πŸ’° Cost Estimation

Project: azure-landing-zone
Currency: USD

Monthly Cost: $547.42
β”œβ”€β”€ Azure Firewall:     $350.40
β”œβ”€β”€ VPN Gateway:        $138.70
β”œβ”€β”€ Virtual Machines:    $45.00
β”œβ”€β”€ Load Balancer:       $18.32
└── Storage:              $5.00

Cost Change: +$25.00 (+4.8%)

πŸ”’ Security Scanning

Tools Integrated

Tool Purpose Checks
tfsec Static analysis 100+ security rules
Checkov Compliance scanning CIS, SOC2, HIPAA, PCI-DSS
TFLint Linting Best practices, errors
gitleaks Secret detection API keys, passwords

Security Best Practices

Practice Implementation
No hardcoded secrets Use sensitive = true and Key Vault
Encryption at rest Enable storage encryption
Network security NSGs, private endpoints
Least privilege Minimal IAM permissions
State protection Encrypted backend storage

πŸ”§ Troubleshooting

Common Issues & Solutions

Pipeline Fails at Format Check

# Fix formatting locally
terraform fmt -recursive

# Commit the changes
git add .
git commit -m "Fix: terraform formatting"
git push

Authentication Failed

# Verify Azure credentials
az login --service-principal \
  --username $ARM_CLIENT_ID \
  --password $ARM_CLIENT_SECRET \
  --tenant $ARM_TENANT_ID

# Check the credentials JSON format
{
  "clientId": "xxx",
  "clientSecret": "xxx",
  "subscriptionId": "xxx",
  "tenantId": "xxx"
}

State Lock Error

# Force unlock (use carefully!)
terraform force-unlock <LOCK_ID>

Variables File Not Found

  • Ensure working_directory points to your Terraform configuration (this repo defaults to ./test).
  • Ensure var_file paths are relative to the working directory.

Security Scan Fails

Security scans use soft_fail: true by default. To block on failures:

- name: Security Scan
  uses: ./.github/actions/security
  with:
    soft_fail: false  # Block on security issues

Terraform Timing Reference

Operation Typical Duration
Format Check ~10 seconds
Validate ~30 seconds
Security Scans ~1-2 minutes
Plan (small) ~1-3 minutes
Plan (large) ~5-10 minutes
Apply Varies by resources

πŸ“ Project Structure

terraform-github-actions/
β”œβ”€β”€ .github/
β”‚   β”œβ”€β”€ workflows/
β”‚   β”‚   └── terraform.yml      # Main pipeline workflow
β”‚   β”‚
β”‚   β”œβ”€β”€ actions/               # Reusable composite actions
β”‚   β”‚   β”œβ”€β”€ apply/             # Terraform apply
β”‚   β”‚   β”œβ”€β”€ changelog/         # Generate changelogs
β”‚   β”‚   β”œβ”€β”€ cost-estimate/     # Infracost integration
β”‚   β”‚   β”œβ”€β”€ destroy/           # Terraform destroy
β”‚   β”‚   β”œβ”€β”€ graph/             # Dependency visualization
β”‚   β”‚   β”œβ”€β”€ metrics/           # Pipeline metrics
β”‚   β”‚   β”œβ”€β”€ module-version/    # Semantic versioning
β”‚   β”‚   β”œβ”€β”€ plan/              # Terraform plan
β”‚   β”‚   β”œβ”€β”€ policy-check/      # OPA/Sentinel policies
β”‚   β”‚   β”œβ”€β”€ resource-inventory/# Resource listing
β”‚   β”‚   β”œβ”€β”€ secret-scan/       # Secret detection
β”‚   β”‚   β”œβ”€β”€ security/          # Security scanning
β”‚   β”‚   β”œβ”€β”€ state-backup/      # State file backup
β”‚   β”‚   β”œβ”€β”€ terraform-docs/    # Documentation generation
β”‚   β”‚   β”œβ”€β”€ terratest/         # Infrastructure testing
β”‚   β”‚   └── validate/          # Format & validate
β”‚   β”‚
β”‚   └── SETUP.md               # Detailed setup guide
β”‚
β”œβ”€β”€ wiki/                     # Documentation wiki
β”‚   β”œβ”€β”€ Home.md                # Wiki landing page
β”‚   β”œβ”€β”€ Pipeline-Stages.md     # Stage-by-stage details
β”‚   β”œβ”€β”€ Actions-Reference.md   # Actions catalog
β”‚   β”œβ”€β”€ Troubleshooting.md     # Common issues
β”‚   β”œβ”€β”€ assets/                # Diagrams and images
β”œβ”€β”€ test/                     # Minimal Terraform example (default workflow target)
β”œβ”€β”€ tests/                    # Terratest integration tests
└── README.md                  # This file

Key Files

File Purpose
terraform.yml Main workflow orchestrating all stages
SETUP.md Step-by-step Azure and GitHub setup
actions/*/action.yml Individual composite actions
wiki/ Local wiki documentation and diagrams
test/ Minimal Terraform example (default workflow target)
tests/ Terratest integration tests (PR-only)

πŸ”— Using Actions in Other Repositories

Option 1: Copy Actions

Copy the .github/actions/ folder to your repository.

Option 2: Reference Remote Actions

# In your workflow
- name: Terraform Plan
  uses: Jamonygr/terraform-github-actions/.github/actions/plan@main
  with:
    azure_credentials: ${{ secrets.AZURE_CREDENTIALS }}
    # ... other inputs

🏷️ Supported Terraform Versions

Version Status
1.9.x βœ… Recommended
1.8.x βœ… Supported
1.7.x βœ… Supported
1.6.x ⚠️ Limited
< 1.6 ❌ Not supported

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments


πŸ“ž Support

Resource Link
Issues GitHub Issues
Terraform Docs Terraform Documentation
GitHub Actions Actions Documentation

Built with ❀️ for Infrastructure as Code automation

Last Updated: January 2026

About

Reusable GitHub Actions for Terraform workflows. Includes plan, apply, validate, security scanning, cost estimation, and more. Automate your infrastructure deployments with production-ready CI/CD pipelines.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages