Terminal showing AI generating Terraform infrastructure code from natural language description
← All Articles
AI + DevOps

How to Use AI to Write Terraform and Infrastructure as Code (Real Examples)

Writing Terraform used to take hours — VPC setup, security groups, IAM roles, variables, outputs, README. AI does it in 30 seconds from a single sentence. More importantly, it does it correctly — with encryption, tags, multi-AZ, and best practices baked in by default.

This guide covers the prompts, patterns, and workflows that actually produce production-ready IaC. Not the toy examples you find in demos — the real patterns that work on infrastructure that handles live traffic.


Why AI + IaC Is a Game Changer

Time saved per module. A complete, production-ready Terraform module for something like an EKS cluster with IRSA, node groups, and CloudWatch logging used to take 3–4 hours of writing, referencing documentation, and debugging provider version issues. With AI, it takes 10–15 minutes — writing the prompt, reviewing the output, adjusting for your specific requirements, and running the plan.

Error reduction. AI has seen thousands of Terraform modules. It knows that EBS volumes should be encrypted by default. It knows that S3 buckets need block_public_access even when you think you don’t need it. It knows that IAM policies should follow least privilege. These best practices appear in the output without you having to remember them.

Consistent style across the team. When everyone uses AI with the same CLAUDE.md context file (more on this below), every module follows the same naming conventions, tag structure, and formatting. Code reviews become faster because the baseline is consistent.

Learning accelerator for juniors. A junior engineer can ask AI to explain what a lifecycle block does, why a particular depends_on is needed, or what the difference between aws_iam_role_policy and aws_iam_role_policy_attachment is — and get a clear, contextual answer immediately. The learning curve collapses.


What AI Is Good At vs What Still Needs Human Review

AI handles these well

  • Boilerplate VPC, subnet, and route table configurations
  • Standard IAM policies for common services (Lambda, ECS, EC2)
  • EKS and RDS module patterns
  • Variable and output blocks with proper types and descriptions
  • locals blocks for repeated values
  • data sources for existing resources
  • Provider version constraints
  • Resource tagging blocks

Still needs human review

Production security settings. AI applies general best practices but does not know your organization’s specific security requirements, compliance frameworks, or network topology. Always review security group rules, IAM policies, and encryption settings before applying.

Custom compliance requirements. If you have NCA, SOC 2, HIPAA, or PCI-DSS requirements, AI will not automatically know your specific control requirements. Add them explicitly to your CLAUDE.md.

Cost-sensitive choices. AI might suggest r6i.2xlarge when r6i.xlarge is sufficient for your workload. Review instance types, storage sizes, and NAT Gateway configurations with cost in mind.

Multi-account setups. Cross-account IAM trust relationships, AWS Organizations SCPs, and complex account architectures require careful human design. AI can write the code once you have the design — but the architecture decisions are yours.


The Best AI Tools for Terraform Writing

Claude Code — best for large, complex modules where you need the AI to read multiple existing files, understand your project structure, and write consistent code that fits your existing patterns. The 200K context window handles entire Terraform repos.

GitHub Copilot — best for inline suggestions while writing in VS Code. Fast, friction-free, good for filling in resource arguments you partially remember. Less good for generating complete modules from scratch.

Amazon Q Developer — best for AWS-specific IaC. Trained heavily on AWS documentation and CloudFormation patterns. Strong for AWS-native resources.

ChatGPT-4o — best for explanations alongside code generation. If you want to understand why the generated code does something, ChatGPT tends to give better explanations than Claude in interactive sessions.


Prompt Patterns That Work

Pattern 1 — Single Resource, Full Detail

Write a Terraform module for an AWS RDS PostgreSQL instance with:
- Multi-AZ enabled
- Encrypted storage using a customer-managed KMS key
- Parameter group for postgres16
- Security group allowing only port 5432 from the app security group (variable input)
- Automated backups: 7-day retention
- Random password stored in AWS Secrets Manager
- Deletion protection enabled

Variables: environment, vpc_id, app_security_group_id, instance_class
Outputs: endpoint, port, secret_arn, db_name

This produces a complete, usable module on the first pass. The key is being specific about exactly what you want — instance type, encryption approach, network access pattern.

Pattern 2 — Full Stack Module

Create Terraform code for a production-ready EKS cluster:
- 3 node groups: spot (t3.medium), on-demand (m5.large), and GPU (g4dn.xlarge, min 0 max 5)
- IRSA enabled with OIDC provider
- VPC CNI plugin with prefix delegation
- Cluster autoscaler IAM role with correct policy
- AWS Load Balancer Controller IAM role
- CloudWatch logging for all log types
- Encryption for secrets using KMS
- Tags: Environment=prod, Team=platform, ManagedBy=terraform

Use the terraform-aws-eks community module where appropriate.

Pattern 3 — Review and Fix Existing Code

Review this Terraform code for security issues and AWS best practices.
Flag each finding with HIGH/MEDIUM/LOW severity.
For each HIGH or MEDIUM finding, show the corrected code.

[paste your terraform code here]

This pattern is particularly powerful in CI/CD — see the GitHub Actions section below.

AI writing Terraform code in VS Code with GitHub Copilot suggestions AI suggesting complete Terraform resource blocks from a single descriptive comment


Real Examples: Before and After AI

Example 1: S3 Bucket with Replication

Manual time estimate: 45–60 minutes including documentation lookup for replication config syntax, IAM policy for replication, and lifecycle rules.

Prompt:

Write a Terraform module for an S3 bucket with:
- Cross-region replication to eu-west-1
- Server-side encryption (AES-256)
- Versioning enabled
- Lifecycle rule: transition to Standard-IA after 30 days, Glacier after 90 days
- Block all public access
- Tags: Environment, Project, Owner

AI time: 25 seconds to generate, 10 minutes to review and adjust the replication IAM role.

What needed manual adjustment: The replication IAM role trust policy needed to reference the specific source bucket ARN, not a wildcard. This is a security decision that requires human intent.

Example 2: EKS Node Group with Spot Instances

Prompt:

Write a Terraform aws_eks_node_group resource for a spot instance node group:
- Instance types: t3.large, t3a.large, m5.large (for spot capacity diversification)
- Min: 2, desired: 4, max: 20
- Launch template with custom userdata for EKS bootstrap
- Capacity type: SPOT
- Labels: role=spot-workers, lifecycle=spot
- Taints: none (mixed workloads allowed on spot)

What was generated: Complete node group with launch template, correct EKS bootstrap userdata, proper IAM node role attachment, and a capacity rebalancing configuration. This would have taken 90 minutes of documentation reading to write from scratch.

What needed review: The bootstrap command in the userdata needed the cluster name injected correctly — the AI used a placeholder variable that needed connecting to the actual cluster name output.


CLAUDE.md Setup for IaC Projects

This is the most important setup step. A well-written CLAUDE.md means every AI-generated module follows your team’s standards automatically:

# Terraform Project Context

## Cloud & Region
Primary: AWS us-east-1
DR: AWS eu-west-1
Account IDs: use data.aws_caller_identity, never hardcode

## Naming Convention
Format: {environment}-{service}-{resource-type}
Example: prod-payments-rds, staging-api-ec2-asg

## Required Tags (on every resource)
Environment = var.environment
Project     = var.project
Team        = var.team
ManagedBy   = "terraform"

## Style Guide
- Follow HashiCorp style guide
- Use snake_case for all names
- Always use data sources for existing resources (VPCs, subnets, etc.)
- Never hardcode account IDs, region names, or AMI IDs
- Always use remote state: S3 bucket + DynamoDB lock
- Pin provider versions (do not use ~> without major version pin)

## Security Requirements
- All EBS volumes must be encrypted
- All S3 buckets must block public access
- No IAM policies with wildcard resources on write actions
- All RDS instances require deletion_protection = true in prod

## Testing
- Module tests use Terratest
- Run terraform validate and terraform fmt before committing

CI/CD: AI Review in Pull Requests

Add this to your GitHub Actions to get an AI security review on every Terraform PR:

# .github/workflows/terraform-ai-review.yml
name: AI Terraform Review
on:
  pull_request:
    paths: ['**.tf']

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

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3

      - name: Terraform Init
        run: terraform init
        working-directory: ./terraform

      - name: Terraform Plan
        id: plan
        run: terraform plan -no-color 2>&1 | tee plan_output.txt
        working-directory: ./terraform
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

      - name: AI Security Review
        id: ai-review
        run: |
          PLAN=$(cat terraform/plan_output.txt | head -200)
          REVIEW=$(curl -s -X POST https://api.anthropic.com/v1/messages \
            -H "x-api-key: ${{ secrets.ANTHROPIC_API_KEY }}" \
            -H "anthropic-version: 2023-06-01" \
            -H "content-type: application/json" \
            -d "{
              \"model\": \"claude-sonnet-4-6\",
              \"max_tokens\": 1500,
              \"messages\": [{
                \"role\": \"user\",
                \"content\": \"Review this Terraform plan for security issues. Flag HIGH/MEDIUM/LOW. Focus on: IAM changes, security group rules, public resource exposure, encryption gaps, destructive operations.\n\nPlan:\n${PLAN}\"
              }]
            }" | jq -r '.content[0].text')
          echo "review<<EOF" >> $GITHUB_OUTPUT
          echo "$REVIEW" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Comment PR
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## 🤖 AI Terraform Review\n\n${{ steps.ai-review.outputs.review }}`
            })

Terminal showing Terraform plan output being reviewed by AI for security issues AI reviewing a Terraform plan and flagging overly permissive IAM policies before merge

Code appearing on screen fast like magic AI generating a complete Terraform VPC module in under 10 seconds


Common Mistakes When Using AI for IaC

Trusting AI output without reviewing. AI generates plausible-looking code that can contain subtle errors — wrong resource references, missing dependencies, or outdated provider syntax. Always run terraform plan and review the diff before terraform apply.

Not providing enough context. “Write me a Terraform module” produces generic output. “Write a Terraform module for a production PostgreSQL RDS instance that needs to be accessible only from our EKS cluster in the same VPC, encrypted with a CMK, with 7-day backups” produces something usable.

Using AI-suggested provider versions without checking. AI training data has a cutoff. The provider versions suggested may be outdated. Always check the Terraform Registry for the current version.

Ignoring AI warnings about costs. AI sometimes flags resource choices as expensive in its output. These warnings are worth reading — a multi-AZ RDS instance with Provisioned IOPS is correct for production but wrong for a development environment.

Not setting up CLAUDE.md. Without project context, AI generates code that doesn’t match your naming conventions, missing your required tags, and using different patterns from your existing modules.


FAQ

Can AI write production-ready Terraform? Yes, with two conditions: you provide sufficient context (via CLAUDE.md or detailed prompts), and a human reviews the output before applying. AI-generated Terraform for common patterns is very good. For complex, custom architectures it provides an excellent starting point that still needs engineering judgment.

Which AI tool is best for writing Terraform? For complete modules and large IaC projects: Claude Code. For inline suggestions while coding: GitHub Copilot. For AWS-specific resources with deep AWS documentation: Amazon Q Developer. Use what fits your workflow.

Is AI-generated Terraform safe to use? Safe to use with review. Not safe to blindly apply. Treat AI-generated IaC like code from a skilled contractor — review it, understand it, run terraform plan, check the diff, then apply. Never apply AI-generated infrastructure changes without understanding what they do.

Can Claude understand AWS best practices? Yes. Claude is well-trained on AWS documentation and Terraform provider documentation. It defaults to encryption, least-privilege IAM, and multi-AZ configurations without being asked. For organization-specific requirements, add them to CLAUDE.md.

How do I set up AI review in my CI/CD pipeline? See the GitHub Actions workflow above. The core pattern: run terraform plan, send the output to the Claude API with a security review prompt, post the response as a PR comment. This takes about an hour to implement and provides permanent value on every infrastructure PR.


Conclusion

AI does not replace infrastructure engineers — it removes the tedious parts of their job. The hours spent looking up resource argument syntax, writing boilerplate variable blocks, and formatting IAM policies are hours that could go toward architecture decisions, reliability improvements, and the work that actually requires expertise.

Set up CLAUDE.md today. Try one complete module generation from a detailed prompt. Review the output critically. Apply it with terraform plan. You will spend the rest of the week wondering why you were writing Terraform by hand.

Using AI for infrastructure automation at scale? Explore our DevOps services →

Related: Claude Code: The Complete Setup Guide for DevOps Engineers

Written by
SysOpX
Battle-tested DevOps & AWS engineering guides
Need DevOps help? →