An intelligent Terraform automation tool that combines infrastructure deployment with AI-powered error analysis and cost optimization. This project provides automated Terraform workflows with built-in error detection, automatic fixes, and cost analysis using OpenAI and Infracost.
- Automated Terraform Operations: Plan and apply infrastructure changes via GitHub Actions
- AI-Powered Error Analysis: Automatically analyzes Terraform failures using OpenAI GPT-4
- Intelligent Auto-Fix: Generates and applies code fixes for common Terraform errors
- Cost Analysis: Integrates with Infracost for infrastructure cost estimation and tracking
- Pull Request Integration: Provides detailed plan summaries and cost breakdowns in PR comments
- AWS S3: Bucket creation and management
- AWS Lambda: Function deployment with S3 integration
- AWS EC2: Instance provisioning (modular)
- AWS VPC: Network infrastructure (modular)
- Remote State: S3 backend with DynamoDB locking
terraform-analyzer/
โโโ .github/workflows/
โ โโโ terraform-analyzer.yml # Main Terraform workflow
โ โโโ cost-analyzer.yml # Cost analysis workflow
โโโ terraform/
โ โโโ modules/ # Reusable Terraform modules
โ โ โโโ s3/ # S3 bucket module
โ โ โโโ lambda/ # Lambda function module
โ โ โโโ ec2/ # EC2 instance module
โ โ โโโ vpc/ # VPC networking module
โ โ โโโ remote-state/ # State management module
โ โโโ main.tf # Main Terraform configuration
โ โโโ variables.tf # Input variables
โ โโโ outputs.tf # Output values
โโโ terraform-analyzer.py # AI error analysis script
โโโ README.md
Choose your preferred deployment method:
Perfect for: Quick setup, existing projects, minimal configuration
name: Terraform AI Analyzer
on:
pull_request:
branches: [ main ]
workflow_dispatch:
inputs:
action:
type: choice
options: [ plan, apply ]
default: plan
permissions:
id-token: write
contents: write
pull-requests: write
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Terraform AI Analyzer
uses: Leapfrog-DevOps/terraform-analyzer@v0.6
with:
deployment-role: ${{ secrets.AWS_DEPLOYMENT_ROLE }}
openai-api-key: ${{ secrets.OPENAI_API_KEY }}
infracost-api-key: ${{ secrets.INFRACOST_API_KEY }}
action: ${{ github.event.inputs.action || 'plan' }}Complete workflow can be found here.
- AWS Account with OIDC provider configured
- OpenAI API Key (Get here)
- Infracost API Key (Get here) - Optional, 1,000 free runs/month
- GitHub repository with Actions enabled
Add these to your repository secrets:
| Secret | Description | Example |
|---|---|---|
AWS_DEPLOYMENT_ROLE |
AWS IAM role ARN for OIDC | arn:aws:iam::123456789:role/deployment-role |
OPENAI_API_KEY |
OpenAI API key | sk-... |
INFRACOST_API_KEY |
Infracost API key (optional) | ico-... |
| Input | Description | Required | Default |
|---|---|---|---|
terraform-version |
Terraform version | No | 1.11.4 |
terraform-directory |
Directory with Terraform files | No | ./terraform |
action |
Terraform action (plan/apply) | No | plan |
aws-region |
AWS region | No | us-east-1 |
deployment-role |
AWS IAM role ARN | Yes | - |
openai-api-key |
OpenAI API key | Yes | - |
infracost-api-key |
Infracost API key | No | - |
mode |
Action mode: (analyze/cost) | No | analyze |
enable-cost-analysis |
Enable cost analysis | No | true |
comment-pr |
Comment on PRs | No | true |
| Output | Description |
|---|---|
plan-exitcode |
Terraform plan exit code |
apply-exitcode |
Terraform apply exit code |
has-changes |
Whether plan detected changes |
cost-analysis |
Cost analysis results |
Perfect for: Custom workflows, advanced configuration, learning the internals
- AWS Account with appropriate permissions
- GitHub repository with Actions enabled
- OpenAI API key for error analysis
- Infracost API key for cost analysis (optional)
- Git installed locally
- Terraform CLI (optional for local testing)
git clone https://github.com/Leapfrog-DevOps/terraform-analyzer.git
cd terraform-analyzer
โ ๏ธ IMPORTANT: The current Terraform code in this repository is just a placeholder for demonstration purposes. DO NOT run it directly as it may create unwanted AWS resources or fail due to missing dependencies.
Replace the placeholder code with your actual Terraform infrastructure:
Custom Directory Setup (Optional): If you prefer a different directory structure:
- Create your custom folder (e.g.,
infrastructure/) - Update
CODE_PATHvariable interraform-analyzer.py - Update working directory paths in
.github/workflows/terraform-analyzer.yml
# Remove existing placeholder files
rm -rf terraform/*
# Add your .tf files to terraform/ directory
# Example structure:
terraform/
โโโ main.tf # Your main configuration
โโโ variables.tf # Input variables
โโโ outputs.tf # Output values
โโโ modules/ # Custom modules (optional)Get OpenAI API Key:
- Visit OpenAI Platform
- Create new API key
- Copy the key (starts with
sk-)
Get Infracost API Key:
- Visit Infracost Dashboard
- Sign up/login and get API key
- Copy the key (starts with
ico-)
Go to your GitHub repository โ Settings โ Secrets and variables โ Actions
Add Repository Secrets:
DEPLOYMENT_ROLE: arn:aws:iam::<your-account>:role/deployment-role
OPENAI_API_KEY: sk-your-openai-key-here
INFRACOST_API_KEY: ico-your-infracost-key-here
# GITHUB_TOKEN is automatically providedAdd Repository Variables:
AWS_REGION: us-east-1
ENVIRONMENT: dev
DEPLOY_LAMBDA: trueCreate IAM Role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::<your-account>:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:<your-org-name>/<your-repo-name>:ref:refs/heads/main"
}
}
}
]
}Attach Required Policies:
- S3 bucket operations
- Lambda function management
- EC2 instance management
- DynamoDB table access (for state locking)
- IAM permissions for resource creation
Create S3 bucket and DynamoDB table for Terraform state:
# Create S3 bucket for state
aws s3 mb s3://terraform-state-bucket-team5-opensource --region us-east-1
# Create DynamoDB table for locking
aws dynamodb create-table \
--table-name terraform-locks \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--region us-east-1The workflow automatically runs on:
- Pull Requests to
final_testbranch โ Runsterraform plan - Manual Dispatch โ Choose between
planorapply
- Go to Actions tab in your repository
- Select "Terraform - Plan & Apply" workflow
- Click "Run workflow"
- Choose action:
planorapply - Click "Run workflow" button
- Create a new branch:
git checkout -b feature/my-infrastructure
- Make changes to Terraform files
- Commit and push:
git add . git commit -m "Add new infrastructure" git push origin feature/my-infrastructure
- Create PR to
final_testbranch - Workflow automatically runs
terraform plan
โ ๏ธ WARNING: Make sure you have replaced the placeholder Terraform code with your actual infrastructure code before running any workflows.
- Ensure all secrets and variables are configured
- Replace placeholder Terraform code with your actual infrastructure
- Run manual workflow with
planaction first - Review the plan output in GitHub Actions
- If plan looks good, run with
applyaction - Monitor logs for any errors or AI auto-fixes
- Runs
terraform plan - Posts plan summary as PR comment
- If plan fails: Triggers AI error analysis and creates auto-fix
branch

- If plan succeeds: Uploads plan artifacts and triggers cost analyzer
workflow

- Runs
terraform apply - If successful, create infrastructure
- If errors occur, runs the analyzer and attempts and push to auto-fix branch.
When Terraform operations fail, the analyzer:
- Extracts Context: Parses error logs and identifies relevant files
- AI Analysis: Sends complete code context to OpenAI GPT-4
- Generates Fixes: Creates corrected Terraform code blocks
- Applies Changes: Automatically updates files with fixes
- Creates PR: Pushes fixes to
auto-tf-fixbranch
- Resource configuration errors
- Provider version conflicts
- Variable reference issues
- Module configuration problems
- AWS resource conflicts
- Preserves original code structure
- Only modifies problematic sections
- Creates backup files before changes
- Generates detailed fix explanations
- Maintains code formatting and style
- Analyzes infrastructure costs before deployment
- Compares costs between different plan versions
- Tracks cost changes over time
- Stores cost data in dedicated
infracostbranch - Cost Baseline: Uses
infracostbranch as cost state reference for drift detection - Free Tier: Up to 1,000 runs per month at no cost
- Baseline costs stored per environment
- Diff analysis for PR changes
- Historical cost data retention
- Integration with GitHub step summaries
Customize infrastructure in terraform/variables.tf:
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "s3_bucket_name" {
description = "S3 bucket name"
type = string
default = "sample-open-source"
}
variable "lambda_function_name" {
description = "Lambda function name"
type = string
default = "sample-lambda"
}Modify .github/workflows/terraform-analyzer.yml to:
- Change trigger branches
- Adjust Terraform version
- Modify auto-fix branch names
- Configure additional AWS regions
- Terraform logs stored in
logs/terraform.log - Plan files uploaded as GitHub artifacts
- Cost analysis results in step summaries
- Auto-fix results in GitHub summaries
- Check workflow logs for detailed error information
- Review AI analysis output in failed runs
- Examine auto-fix branch for proposed changes
- Verify AWS permissions and credentials
- Fork the repository
- Create feature branch:
git checkout -b feature/new-feature - Make changes and test thoroughly
- Commit changes:
git commit -m 'Add new feature' - Push to branch:
git push origin feature/new-feature - Create Pull Request
This project is open source and available under the GPL-3.0 License.
For issues and questions:
- Create GitHub Issues for bugs and feature requests
- Check workflow logs for deployment issues
- Review AI analysis output for Terraform errors
- Consult AWS documentation for permission issues
We are planning to build our own AI-powered open source cost analyzer.
Thanks to these amazing people who have contributed to this project:
Binaya Dahal Idea, Core Developer & Documentation |
Rabindra Raj Sah Core Developer & Coordinator |
Ankit Karna GitHub Actions & Automation |
Santosh Bhandari Security Testing |
Jenith Shrestha Quality Control |
Special thanks to Infracost for providing the excellent infrastructure cost calculation tool that powers our cost analysis features. Your tool makes it possible for teams to understand and optimize their cloud spending before deployment. We're grateful for your contribution to the DevOps community and for making cost transparency accessible to everyone.
Built with โค๏ธ by Terraform Analyzer Team