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

Introduction

Infrastructure as Code (IaC) has become the backbone of modern cloud operations, and Terraform by HashiCorp remains the dominant tool for provisioning resources across AWS, Azure, GCP, and beyond. As a developer who uses AI daily to accelerate infrastructure workflows, I’ve compiled a set of battle-tested prompts that solve real problems: managing Terraform state, designing reusable modules, handling multi-cloud setups, and debugging complex configurations. These prompts are designed to be dropped directly into your AI assistant (like Claude, ChatGPT, or a local LLM) to get actionable, copy-paste-ready code and explanations.

Each prompt below includes a concrete usage example and a brief explanation of why it works. No fluff—just practical value.

1. Prompt: Generate a Terraform Module Skeleton

Prompt:

Create a Terraform module for deploying an AWS EC2 instance with the following features: variable declarations for instance type, AMI ID, subnet ID, security group IDs, and tags. Include outputs for instance ID and public IP. Use Terraform AWS provider version 5.x. Output only the variables.tf, outputs.tf, main.tf, and README.md files.

Usage Example:

# variables.tf
variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}

variable "ami_id" {
  description = "AMI ID for the instance"
  type        = string
}

variable "subnet_id" {
  description = "Subnet ID to launch the instance in"
  type        = string
}

variable "security_group_ids" {
  description = "List of security group IDs"
  type        = list(string)
}

variable "tags" {
  description = "Tags to apply to the instance"
  type        = map(string)
  default     = {}
}

Why it works: This prompt forces the AI to generate a complete module with inputs, outputs, and documentation—saving hours of boilerplate. The explicit provider version avoids compatibility issues.

2. Prompt: Debug a Terraform State Locking Issue

Prompt:

I'm getting a Error acquiring the state lock in Terraform when running terraform apply. My backend is AWS S3 with DynamoDB for locking. Provide step-by-step commands to unlock the state, and explain how to prevent this in the future. Also, show how to check which process holds the lock using AWS CLI.

Usage Example:

# Force unlock (use with caution)
terraform force-unlock <LOCK_ID>

# Check DynamoDB table for lock item
aws dynamodb get-item --table-name terraform-locks --key '{"LockID": {"S": "my-bucket/path/to/state/terraform.tfstate-md5"}}'

# List all lock items
aws dynamodb scan --table-name terraform-locks

Why it works: State locking is a common headache in team environments. This prompt produces a diagnostic script and prevention tips (e.g., using terraform plan -out=tfplan to avoid concurrent applies).

3. Prompt: Refactor a Monolithic Terraform Configuration into Modules

Prompt:

I have a single main.tf that deploys an AWS VPC, subnets, an RDS instance, and an EC2 instance. Refactor this into separate modules: vpc, rds, and ec2. Show the directory structure, and how to call the modules from a root main.tf. Assume the original code uses Terraform 1.5+ and AWS provider 5.x.

Usage Example (root main.tf):

module "vpc" {
  source = "./modules/vpc"
  cidr_block = "10.0.0.0/16"
  name       = "my-vpc"
}

module "rds" {
  source = "./modules/rds"
  vpc_id = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnet_ids
  db_name   = "mydb"
  db_user   = "admin"
  db_password = var.db_password
}

module "ec2" {
  source = "./modules/ec2"
  subnet_id = module.vpc.public_subnet_ids[0]
  vpc_id    = module.vpc.vpc_id
}

Why it works: Refactoring into modules improves reusability and team collaboration. The AI generates a clear separation of concerns and example calls.

4. Prompt: Migrate Terraform State from Local to Remote

Prompt:

My Terraform state is stored locally. Write a script to migrate it to an S3 backend with DynamoDB locking. Include the backend configuration block, the terraform init -migrate-state command, and an example DynamoDB table creation command via AWS CLI. Also, list potential pitfalls like state versioning and access permissions.

Usage Example (backend config):

terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Why it works: This prompt covers the entire migration workflow, which is critical for teams moving from local to remote state management.

5. Prompt: Generate a Multi-Cloud Terraform Configuration (AWS + Azure)

Prompt:

Write a Terraform configuration that deploys a simple web app across AWS and Azure. On AWS, create an EC2 instance running Nginx. On Azure, create a VM with the same role. Use separate providers (hashicorp/aws and hashicorp/azurerm), and pass a shared variable for the app name. Output the public IPs of both instances. Use Terraform 1.5+ and latest provider versions.

Usage Example:

provider "aws" {
  region = "us-west-2"
}

provider "azurerm" {
  features {}
}

variable "app_name" {
  default = "my-multicloud-app"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0" # Amazon Linux 2
  instance_type = "t3.micro"
  tags = {
    Name = "${var.app_name}-aws"
  }
}

resource "azurerm_linux_virtual_machine" "web" {
  name                = "${var.app_name}-azure"
  resource_group_name = azurerm_resource_group.main.name
  location            = "East US"
  size                = "Standard_B1s"
  admin_username      = "adminuser"
  network_interface_ids = [azurerm_network_interface.main.id]
  admin_ssh_key {
    username   = "adminuser"
    public_key = file("~/.ssh/id_rsa.pub")
  }
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }
  source_image_reference {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "18.04-LTS"
    version   = "latest"
  }
}

Why it works: Multi-cloud configurations are complex due to different resource types. This prompt generates a working cross-cloud deployment with shared variables, reducing manual research.

6. Prompt: Write a Terraform Sentinel Policy (Enterprise/Cloud)

Prompt:

Create a Sentinel policy that enforces the following rules for Terraform Cloud/Enterprise: (1) All AWS resources must have a CostCenter tag, (2) EC2 instances must not use t2.micro or t3.nano in production workspaces, (3) S3 buckets must have versioning enabled. Use Sentinel language, and include a mock request to test.

Usage Example (policy snippet):

import "tfplan/v2" as tfplan

# Rule 1: All AWS resources must have CostCenter tag
all_aws_resources = filter tfplan.resource_changes as _, rc {
  rc.type is "aws_*"
}

mandatory_tags = ["CostCenter"]

main = rule {
  all all_aws_resources as _, rc {
    all mandatory_tags as tag {
      rc.change.after.tags[tag] else null is not null
    }
  }
}

Why it works: Sentinel policies are essential for governance in large organizations. This prompt generates a policy that can be directly uploaded to Terraform Cloud.

7. Prompt: Optimize Terraform Plan Time with -target and Module Strategies

Prompt:

My Terraform plan takes 5 minutes because it refreshes all 200 resources. Suggest strategies to reduce plan time: use of -target flag, -refresh-only, splitting state, and using terraform plan -out with a lock file. Provide examples of each. Also, explain when to use terraform plan -refresh=false (deprecated in newer versions) and alternatives.

Usage Example:

# Plan only specific resource
export TF_CLI_ARGS_plan="-target=aws_instance.web"

# Refresh only mode (no changes, just update state)
terraform apply -refresh-only

# Split state using terraform state mv
terraform state mv aws_instance.web module.web

Why it works: Large infrastructures suffer from slow plans. This prompt provides actionable optimization techniques without guesswork.

8. Prompt: Handle Terraform Workspaces for Multi-Environment Deployments

Prompt:

I need to manage three environments (dev, staging, prod) using Terraform workspaces. Show me how to structure my code with a terraform.tfvars per workspace, how to use terraform.workspace in resource naming, and how to automate workspace creation in CI/CD. Include a bash script that creates workspaces if they don't exist.

Usage Example:

#!/bin/bash
WORKSPACES=("dev" "staging" "prod")
for ws in "${WORKSPACES[@]}"; do
  if terraform workspace list | grep -q "$ws"; then
    echo "Workspace $ws exists"
  else
    terraform workspace new $ws
  fi
done

Why it works: Workspaces are often misused (e.g., for complex multi-account setups). This prompt gives a clean pattern for environment isolation.

9. Prompt: Write a Terraform Module for Kubernetes (EKS/AKS/GKE)

Prompt:

Create a reusable Terraform module for deploying a Kubernetes cluster on AWS EKS. The module should accept variables for cluster name, node group instance types, desired size, and VPC configuration. Use the official AWS EKS module from the Terraform Registry as a base. Output the kubeconfig command and cluster endpoint.

Usage Example:

module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 20.0"

  cluster_name    = var.cluster_name
  cluster_version = "1.29"

  vpc_id     = var.vpc_id
  subnet_ids = var.subnet_ids

  eks_managed_node_groups = {
    main = {
      desired_size = var.desired_size
      instance_types = var.instance_types
    }
  }
}

output "kubeconfig_command" {
  value = "aws eks update-kubeconfig --region ${var.region} --name ${module.eks.cluster_name}"
}

Why it works: Kubernetes cluster creation is notoriously repetitive. This prompt generates a production-ready module leveraging the community module.

10. Prompt: Convert Terraform State to JSON for External Tools

Prompt:

I need to parse my Terraform state to extract all EC2 instance IDs and their public IPs for an inventory script. Write a Python script using json library that reads terraform state pull output and prints a CSV. Also, show how to use terraform show -json for plan output.

Usage Example:

import json
import subprocess
import sys

result = subprocess.run(["terraform", "state", "pull"], capture_output=True, text=True)
state = json.loads(result.stdout)

resources = state.get("values", {}).get("root_module", {}).get("resources", [])
for res in resources:
    if res["type"] == "aws_instance":
        inst_id = res["values"]["id"]
        pub_ip = res["values"].get("public_ip", "N/A")
        print(f"{inst_id},{pub_ip}")

Why it works: State parsing is a common need for integration with CMDBs or monitoring. This prompt produces a ready-to-run script.

11. Prompt: Troubleshoot Terraform Provider Version Conflicts

Prompt:

When running terraform init, I get Error: Failed to query available provider packages for the hashicorp/aws provider. My required_providers block specifies version ~> 5.0, but my colleague uses ~> 4.67. Explain the conflict, how to use version constraints with >= and ~>, and show how to pin all providers in a versions.tf file. Also, demonstrate using terraform providers command to see the dependency tree.

Usage Example:

terraform {
  required_version = ">= 1.5"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    random = {
      source  = "hashicorp/random"
      version = ">= 3.0"
    }
  }
}

Why it works: Version conflicts are a top support issue. This prompt teaches constraint syntax and debugging commands.

Conclusion

These 11 prompts cover the most frequent Terraform and IaC challenges I encounter daily: from building modules and managing state to multi-cloud and Kubernetes deployments. They are designed to be copied, pasted, and adapted to your specific context. The key is to be explicit in your prompt—specify provider versions, desired outputs, and constraints—so the AI generates production-ready code rather than generic examples.

As you integrate these prompts into your workflow, remember that AI is a copilot, not a replacement for understanding Terraform’s core concepts. Always review generated code for security and compliance, especially when dealing with state files or multi-cloud setups. With these prompts, you can cut down infrastructure coding time by 50–70% while maintaining quality.

Note: For advanced Terraform training and real-world project templates, check out courses that cover these patterns in depth.

← All posts

Comments