15 Prompts for Terraform and IaC: From Modules to Multi-Cloud

Introduction

Infrastructure as Code (IaC) has transformed how we manage cloud resources. Terraform, by HashiCorp, is the de facto standard for provisioning across AWS, Azure, GCP, and on-premises environments. But even experienced engineers hit walls — debugging state drift, structuring modules, or orchestrating multi-cloud deployments. That's where AI-assisted prompts come in.

This collection of 15 battle-tested prompts will help you write Terraform code faster, avoid common pitfalls, and build production-grade infrastructure. Each prompt includes a real-world example, so you can copy-paste and adapt immediately. Whether you're a solo developer or part of a platform team, these prompts will save you hours.

Why Prompts Matter for IaC

AI models like Claude and GPT-4 understand Terraform HCL (HashiCorp Configuration Language) syntax and best practices. But generic prompts yield generic results. Specific prompts — with constraints, examples, and context — produce production-ready code. The prompts below are designed to be used with any AI coding assistant or chat interface.

15 Prompts for Terraform and IaC

1. Generate a Modular VPC with Subnets

Prompt:
"Create a Terraform module for an AWS VPC with public and private subnets across three availability zones. Include variables for CIDR blocks, enable NAT Gateway, and output the subnet IDs. Use Terraform 1.5+ with for_each for subnet creation."

Example output snippet:

# modules/vpc/main.tf
resource "aws_vpc" "main" {
  cidr_block = var.cidr_block
  enable_dns_hostnames = true
  enable_dns_support   = true
  tags = {
    Name = var.name
  }
}

resource "aws_subnet" "public" {
  for_each = var.availability_zones
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet(var.cidr_block, 8, index(var.availability_zones, each.key))
  availability_zone = each.key
  map_public_ip_on_launch = true
  tags = {
    Name = "${var.name}-public-${each.key}"
  }
}

This approach ensures reusability across projects. Official module registry provides a similar pattern.

2. Migrate Terraform State from Local to S3

Prompt:
"Write a Terraform configuration to migrate state from a local terraform.tfstate file to an S3 backend with DynamoDB locking. The bucket should be versioned, encrypted, and in us-east-1. Show the terraform init -migrate-state command."

Example:

# backend.tf    erraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket-2026"
    key            = "infra/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}

After adding this block, run terraform init -migrate-state. This technique is documented in HashiCorp's state management guide.

3. Handle State Drift Detection

Prompt:
"Explain how to detect and resolve state drift in Terraform. Provide a script that runs terraform plan daily, compares it to a known-good state, and alerts if resources changed outside Terraform. Use AWS CloudWatch Events and Lambda."

Example approach:
Use a Lambda function triggered by CloudWatch Events to execute terraform plan -no-color and send output to SNS. If changes are detected, a notification is sent. Code sample:

import boto3
import subprocess

def lambda_handler(event, context):
    result = subprocess.run(['terraform', 'plan', '-no-color'], capture_output=True, text=True)
    if 'No changes' not in result.stdout:
        sns = boto3.client('sns')
        sns.publish(TopicArn='arn:aws:sns:us-east-1:123456789012:terraform-drift', Message=result.stdout)
    return {'statusCode': 200}

This pattern follows AWS's drift detection best practices.

4. Create a Multi-Cloud Kubernetes Cluster (EKS + GKE)

Prompt:
"Write Terraform code to provision an EKS cluster in AWS and a GKE cluster in GCP. Use separate modules for each provider. Output the kubeconfig commands for both clusters. Include node groups with auto-scaling."

Example structure:

# main.tf
module "eks" {
  source = "./modules/eks"
  cluster_name = "my-eks"
  region       = var.aws_region
}

module "gke" {
  source = "./modules/gke"
  cluster_name = "my-gke"
  project_id   = var.gcp_project
}

Each module uses provider-specific resources. For EKS, use aws_eks_cluster; for GKE, google_container_cluster. This pattern is common in enterprises running multi-cloud strategies.

5. Write a Terraform Module for an Auto-Scaling Group with ALB

Prompt:
"Create a Terraform module for an AWS Auto Scaling Group with an Application Load Balancer. Include health checks, scaling policies based on CPU, and a launch template. Use variables for instance type, min/max size, and VPC ID."

Example code:

resource "aws_autoscaling_group" "app" {
  name               = "${var.name}-asg"
  vpc_zone_identifier = var.subnet_ids
  min_size           = var.min_size
  max_size           = var.max_size
  launch_template {
    id      = aws_launch_template.app.id
    version = "$Latest"
  }
  tag {
    key                 = "Name"
    value               = var.name
    propagate_at_launch = true
  }
}

This module can be reused across environments. AWS documentation provides reference.

6. Implement Terraform Workspaces for Environments

Prompt:
"Show how to use Terraform workspaces for dev, staging, and prod environments. Include a configuration that reads environment-specific variables from separate terraform.tfvars files. Explain workspace commands."

Example:

terraform workspace new dev
terraform workspace new staging
terraform workspace new prod
terraform workspace select dev
terraform apply -var-file="dev.tfvars"

Inside code:

variable "instance_count" {
  default = {
    dev     = 1
    staging = 2
    prod    = 4
  }
}

resource "aws_instance" "app" {
  count = var.instance_count[terraform.workspace]
  ami   = var.ami
  instance_type = var.instance_type
}

Workspaces are ideal for managing multiple environments with minimal code duplication. HashiCorp documentation details this.

7. Generate IAM Policies Dynamically

Prompt:
"Write a Terraform module that generates IAM policies based on a list of actions and resources. Use jsonencode to create the policy document dynamically. Include examples for S3 read-only and EC2 full access."

Example:

variable "policy_actions" {
  type = map(list(string))
}

data "aws_iam_policy_document" "dynamic" {
  for_each = var.policy_actions
  statement {
    actions   = each.value
    resources = ["*"]
  }
}

resource "aws_iam_policy" "dynamic" {
  for_each = data.aws_iam_policy_document.dynamic
  name   = each.key
  policy = each.value.json
}

This pattern reduces boilerplate. IAM best practices are covered in AWS IAM documentation.

8. Use terraform_remote_state to Share Outputs

Prompt:
"Explain how to use terraform_remote_state data source to read outputs from another Terraform configuration. Provide an example where a VPC module's subnet IDs are consumed by an EC2 module."

Example:

data "terraform_remote_state" "vpc" {
  backend = "s3"
  config = {
    bucket = "my-terraform-state"
    key    = "vpc/terraform.tfstate"
    region = "us-east-1"
  }
}

resource "aws_instance" "web" {
  subnet_id = data.terraform_remote_state.vpc.outputs.public_subnet_ids[0]
  ami       = var.ami
}

This decouples state files, enabling team collaboration. Terraform guide explains this.

9. Write a Sentinel Policy for Compliance

Prompt:
"Create a Sentinel policy that prevents Terraform from provisioning EC2 instances larger than t3.large. Include a mock for testing. Explain how to integrate with Terraform Cloud."

Example policy:

import tfplan

# Rule: instance type must be <= t3.large
allowed_types = ["t3.nano", "t3.micro", "t3.small", "t3.medium", "t3.large"]

main = rule {
  all tfplan.resources.aws_instance as _, instances {
    all instances as _, instance {
      instance.applied.instance_type in allowed_types
    }
  }
}

Sentinel policies enforce governance. HashiCorp Sentinel documentation is the primary source.

10. Create a Terraform Provider for a Custom API

Prompt:
"Outline steps to create a custom Terraform provider for a REST API. Include the structure of the provider, resource schema, and CRUD operations. Use the Terraform Plugin SDK v2."

Example structure:

my-provider/
├── main.go
├── provider.go
└── resources/
    └── resource_myapp.go

Code snippet from resource_myapp.go:

func resourceMyAppCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
  client := m.(*ProviderClient)
  name := d.Get("name").(string)
  // Make API call
  d.SetId(name)
  return nil
}

This enables managing any custom service. Terraform Plugin SDK guide is essential reading.

11. Debug Terraform State with CLI Commands

Prompt:
"List essential Terraform CLI commands for debugging state issues: terraform state list, terraform state show, terraform state mv, and terraform state rm. Provide real-world scenarios for each."

Example scenario:
If a resource was deleted manually, use terraform state rm to remove it from state, then terraform apply will recreate it. Command:

terraform state rm aws_instance.web
terraform apply -target=aws_instance.web

This prevents deletion of other resources. CLI documentation covers all commands.

12. Implement Terraform Workspaces with Terragrunt

Prompt:
"Show a Terragrunt configuration that manages multiple Terraform workspaces across environments. Include terragrunt.hcl that reads account IDs from YAML and generates backend config."

Example:

# terragrunt.hcl
locals {
  environment = path_relative_to_include()
  config      = yamldecode(file("${get_terragrunt_dir()}/../config.yaml"))
}

remote_state {
  backend = "s3"
  config = {
    bucket = "my-terraform-state-${local.environment}"
    key    = "${path_relative_to_include()}/terraform.tfstate"
    region = "us-east-1"
  }
}

Terragrunt reduces duplication. Terragrunt documentation explains this.

13. Use templatefile for Dynamic Configs

Prompt:
"Demonstrate how to use Terraform's templatefile function to generate user data scripts for EC2 instances. Include variables for environment and app version."

Example:

locals {
  user_data = templatefile("${path.module}/user_data.sh.tpl", {
    app_version = var.app_version
    environment = var.environment
  })
}

resource "aws_instance" "web" {
  user_data = base64encode(local.user_data)
  ami       = var.ami
  instance_type = "t3.micro"
}

Template file user_data.sh.tpl:

#!/bin/bash
APP_VERSION="${app_version}"
ENVIRONMENT="${environment}"
echo "Deploying ${APP_VERSION} in ${ENVIRONMENT}"

This keeps scripts clean. Terraform templatefile docs.

14. Write a Module for Cross-Region Replication

Prompt:
"Create a Terraform module that sets up S3 cross-region replication. Include source and destination buckets, IAM roles, and replication rules. Use lifecycle policies to expire old objects."

Example:

resource "aws_s3_bucket" "source" {
  bucket = var.source_bucket
  versioning {
    enabled = true
  }
}

resource "aws_s3_bucket_replication_configuration" "replication" {
  depends_on = [aws_s3_bucket_versioning.source]
  role   = aws_iam_role.replication.arn
  bucket = aws_s3_bucket.source.id
  rule {
    status = "Enabled"
    destination {
      bucket = aws_s3_bucket.destination.arn
    }
  }
}

This ensures data durability. AWS S3 replication guide provides details.

15. Optimize Terraform Plan Performance

Prompt:
"Provide tips to speed up Terraform plans for large infrastructures: use -parallelism, limit refresh with -refresh=false, use -target for specific resources, and enable provider caching."

Example commands:

# Increase parallelism to 20
export TF_CLI_ARGS_plan="-parallelism=20"
terraform plan
# Skip refresh if state is trusted
terraform plan -refresh=false
# Target specific module
terraform plan -target=module.vpc

For caching, set provider_installation in .terraformrc:

provider_installation {
  filesystem_mirror {
    path    = "/usr/share/terraform/providers"
    include = ["registry.terraform.io/hashicorp/*"]
  }
}

These optimizations are recommended by HashiCorp performance guide.

Conclusion

These 15 prompts cover the most common Terraform tasks: from modular design and state management to multi-cloud deployments and performance tuning. By using them, you'll write cleaner code, reduce errors, and accelerate your IaC workflow. Start with the VPC module prompt — it's a foundational skill. Then experiment with multi-cloud patterns. Remember, the best Terraform code is versioned, tested, and reviewed. Now open your editor and try one of these prompts with your AI assistant. Your infrastructure will thank you.

← All posts

Comments