Setup and context — When AI Writes Your Infrastructure Code
Infrastructure as Code (IaC) has become the standard for managing cloud resources. But let's face it — writing Terraform's HCL (HashiCorp Configuration Language) from scratch means memorizing hundreds of resource definitions across cloud providers, keeping up with API changes, and manually checking for security misconfigurations.
What if your AI coding assistant could handle all of that?
By integrating Antigravity's AI agents with Terraform, you can describe infrastructure requirements in plain English, have production-ready HCL generated automatically, and get instant AI-powered reviews of your terraform plan output — all while enforcing your team's security and cost policies.
What you'll learn:
- How to configure Antigravity for efficient Terraform project development
- Techniques for AI-powered Terraform code generation
- A practical workflow for AI-reviewing
terraform plandiffs - Building automated security and cost optimization checklists with AI
Prerequisites: Familiarity with Terraform basics and at least one cloud provider (AWS examples used throughout)
Environment Setup
Required Tools
Make sure you have the following installed before getting started.
# Verify Terraform installation
terraform --version
# Terraform v1.10.x or later recommended
# Verify Antigravity IDE is up to date
# Check for latest version in the IDE
# AWS CLI (using AWS as our example provider)
aws --version
# aws-cli/2.x.x or laterProject Structure
A well-organized project structure helps the AI agent understand your infrastructure layout and generate contextually appropriate code.
infra/
├── environments/
│ ├── dev/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── terraform.tfvars
│ ├── staging/
│ └── production/
├── modules/
│ ├── networking/
│ ├── compute/
│ ├── database/
│ └── monitoring/
├── .antigravity/
│ └── agents.md # AI agent configuration
└── scripts/
└── plan-review.sh # Automated AI review script
Configuring Antigravity's IaC Agent
Providing Context with agents.md
The key to getting high-quality Terraform code from Antigravity is giving the AI agent proper context. Create a .antigravity/agents.md file in your project root.
# Infrastructure Agent Configuration
## Project Context
- Cloud Provider: AWS (ap-northeast-1)
- Terraform Version: >= 1.10
- State Backend: S3 + DynamoDB locking
- Environments: dev, staging, production
## Coding Standards
- All resources must have Name and Environment tags
- Use modules for reusable components
- No hardcoded credentials — use AWS IAM roles
- Enable encryption at rest for all storage resources
- VPC flow logs must be enabled in all environments
## Security Requirements
- No public S3 buckets unless explicitly approved
- All security groups must have explicit egress rules
- RDS instances must not be publicly accessible
- Enable AWS CloudTrail in all accountsWith this configuration in place, the AI agent automatically factors in your project-specific requirements every time it generates or reviews Terraform code.
Custom Commands for Terraform Workflows
Set up custom commands in Antigravity to streamline common Terraform tasks.
{
"customCommands": {
"tf-gen": {
"description": "Generate Terraform code from natural language",
"prompt": "Generate Terraform code based on the following requirements. Follow the security requirements in agents.md and use proper variable parameterization: "
},
"tf-review": {
"description": "AI review of terraform plan output",
"prompt": "Review the following terraform plan output. Flag any security risks, cost implications, best practice violations, and rollback concerns: "
}
}
}AI-Powered Terraform Code Generation
The Basic Generation Flow
Here's a real-world example of describing infrastructure requirements in natural language and having Antigravity generate the corresponding Terraform code.
Prompt:
"Create a production RDS PostgreSQL instance with Multi-AZ deployment, encryption enabled, and 7-day automated backup retention."
AI-generated code:
# modules/database/main.tf
resource "aws_db_subnet_group" "main" {
name = "${var.project_name}-${var.environment}-db-subnet"
subnet_ids = var.private_subnet_ids
tags = {
Name = "${var.project_name}-${var.environment}-db-subnet"
Environment = var.environment
ManagedBy = "terraform"
}
}
resource "aws_db_instance" "postgresql" {
identifier = "${var.project_name}-${var.environment}-postgres"
engine = "postgres"
engine_version = var.postgres_version
instance_class = var.db_instance_class
# Storage configuration
allocated_storage = var.allocated_storage
max_allocated_storage = var.max_allocated_storage
storage_type = "gp3"
storage_encrypted = true # Encryption enabled
kms_key_id = var.kms_key_arn
# Network configuration
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = [var.db_security_group_id]
publicly_accessible = false # No public access
# High availability
multi_az = var.environment == "production" ? true : false
# Backup configuration
backup_retention_period = 7
backup_window = "03:00-04:00"
maintenance_window = "sun:04:00-sun:05:00"
# Deletion protection
deletion_protection = var.environment == "production" ? true : false
skip_final_snapshot = var.environment != "production"
final_snapshot_identifier = var.environment == "production" ? "${var.project_name}-final-snapshot" : null
tags = {
Name = "${var.project_name}-${var.environment}-postgres"
Environment = var.environment
ManagedBy = "terraform"
}
}
# Output: connection details
# endpoint = aws_db_instance.postgresql.endpoint
# port = aws_db_instance.postgresql.portNotice how the AI automatically incorporates encryption, disables public access, and adds environment-aware conditional logic — all based on the agents.md security requirements.
Generating Cross-Module Dependencies
When generating infrastructure that spans multiple modules, the AI agent resolves dependency chains automatically.
# environments/production/main.tf
module "networking" {
source = "../../modules/networking"
project_name = var.project_name
environment = "production"
vpc_cidr = "10.0.0.0/16"
# AI suggests appropriate AZ distribution
availability_zones = ["ap-northeast-1a", "ap-northeast-1c", "ap-northeast-1d"]
}
module "database" {
source = "../../modules/database"
project_name = var.project_name
environment = "production"
private_subnet_ids = module.networking.private_subnet_ids # Dependency resolved
db_security_group_id = module.networking.db_security_group_id
kms_key_arn = module.encryption.kms_key_arn
postgres_version = "16.4"
db_instance_class = "db.r6g.large"
allocated_storage = 100
max_allocated_storage = 500
}
module "monitoring" {
source = "../../modules/monitoring"
project_name = var.project_name
environment = "production"
db_identifier = module.database.db_instance_id # Dependency resolved
alarm_sns_topic_arn = var.alarm_sns_topic_arn
}AI-Powered terraform plan Review Workflow
Automated Review Script
Build a script that captures terraform plan output and feeds it to the AI agent for review.
#!/bin/bash
# scripts/plan-review.sh
# Feed terraform plan output to AI for review
set -euo pipefail
ENVIRONMENT="${1:-dev}"
PLAN_FILE="/tmp/tfplan-${ENVIRONMENT}.out"
echo "=== Terraform Plan for ${ENVIRONMENT} ==="
cd "environments/${ENVIRONMENT}"
# Run plan and save output
terraform plan -out="${PLAN_FILE}" -no-color 2>&1 | tee /tmp/plan-output.txt
# Extract change summary
CHANGES=$(terraform show -no-color "${PLAN_FILE}" 2>/dev/null)
echo ""
echo "=== AI Review Request ==="
cat <<EOF > /tmp/review-request.txt
## Terraform Plan Review Request
### Environment: ${ENVIRONMENT}
### Plan Output:
\`\`\`
${CHANGES}
\`\`\`
### Review Checklist:
1. Are there any security risks?
2. Is the cost impact reasonable?
3. What is the blast radius for production?
4. Does this follow infrastructure best practices?
5. Can these changes be safely rolled back?
EOF
echo "Review request saved to /tmp/review-request.txt"What the AI Reviews
The Antigravity agent evaluates terraform plan output across several dimensions.
Security checks:
- Security groups open to 0.0.0.0/0
- S3 bucket public access settings
- Encryption at rest and in transit
- IAM policies following least-privilege principle
Cost analysis:
- Instance type appropriateness for the workload
- Comparison with Reserved Instance pricing
- Identification of potentially unnecessary resources
Availability checks:
- Multi-AZ configuration where appropriate
- Backup and retention settings
- Health check configuration
Security and Cost Optimization with AI
AI-Generated Sentinel Policies
Combine HashiCorp Sentinel with Antigravity to generate and manage infrastructure policies.
# sentinel/policies/enforce-encryption.sentinel
# AI-generated security policy
import "tfplan/v2" as tfplan
# Verify encryption on all S3 buckets
s3_buckets = filter tfplan.resource_changes as _, rc {
rc.type is "aws_s3_bucket" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
encryption_check = rule {
all s3_buckets as _, bucket {
bucket.change.after.server_side_encryption_configuration is not null
}
}
# Verify encryption on all RDS instances
rds_instances = filter tfplan.resource_changes as _, rc {
rc.type is "aws_db_instance" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
rds_encryption_check = rule {
all rds_instances as _, db {
db.change.after.storage_encrypted is true
}
}
main = rule {
encryption_check and rds_encryption_check
}Automated Cost Estimation
# Integrate Infracost with Antigravity for cost analysis
# AI analyzes cost estimates and suggests optimizations
infracost breakdown --path environments/production \
--format json \
--out-file /tmp/cost-estimate.json
# Feed results to Antigravity agent for optimization analysis
echo "Cost estimate saved — pass to Antigravity agent
for optimization recommendations"Putting It Together: CI/CD Pipeline Integration
GitHub Actions × Antigravity × Terraform
# .github/workflows/terraform-ai-review.yml
name: Terraform AI Review
on:
pull_request:
paths:
- 'infra/**'
jobs:
plan-and-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.10.0"
- name: Terraform Init
working-directory: infra/environments/dev
run: terraform init
- name: Terraform Plan
working-directory: infra/environments/dev
run: |
terraform plan -no-color -out=tfplan 2>&1 | tee plan-output.txt
- name: AI Security Review
run: |
# Send plan output to AI review
echo "## AI Infrastructure Review" >> $GITHUB_STEP_SUMMARY
echo "Plan output saved for AI agent review" >> $GITHUB_STEP_SUMMARY
- name: Cost Estimation
uses: infracost/actions/setup@v3
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
- name: Generate Cost Report
run: |
infracost breakdown \
--path infra/environments/dev \
--format tableCommon Errors and Troubleshooting
State Lock Conflicts
If the AI agent attempts to run multiple terraform apply commands simultaneously, state lock conflicts will occur.
# Error message
# Error: Error acquiring the state lock
# Fix: check lock info and release
terraform force-unlock <LOCK_ID>
# Prevention: limit concurrent runs in CI/CD
# Use GitHub Actions concurrency settingsType Errors in AI-Generated Code
When AI-generated HCL has type mismatches, catch them early with validation.
# Always run after generation
terraform validate
# Expected output:
# Success! The configuration is valid.Wrapping Up — The Future of AI-Powered Infrastructure Management
Integrating Antigravity with Terraform unlocks a fundamentally different approach to infrastructure management.
- Faster code generation — Describe what you need in plain English, and the AI produces security-compliant Terraform code automatically
- Automated reviews — Every
terraform plangets instant AI analysis for security risks, cost implications, and best practice violations - Consistent policies — Rules defined in
agents.mdare enforced across every code generation, keeping your entire team aligned - Lower learning curve — You don't need to memorize every HCL resource type when AI generates best-practice code for you
Start small — try it on a dev environment first, then gradually expand to staging and production as you build confidence in the workflow. The combination of AI intelligence and Terraform's declarative power is a game-changer for infrastructure teams of any size.
Internal links: