Free — no signup required

Prompt Engineering for IaC

2 min read

Why Prompts Are Infrastructure

The quality of AI-generated IaC is almost entirely determined by the quality of the prompt. A vague prompt produces vague, generic code. A precise prompt that encodes your constraints produces code that's 90% production-ready instead of 60%.

Think of a prompt as a specification document. The more context you provide — provider version, naming conventions, security requirements, output format — the less correction work you do afterward.

The Anatomy of a High-Quality IaC Prompt

A production-grade IaC prompt has four components:

1. Role and context: Tell the model what kind of engineer it's acting as and what environment it's working in.

2. Specific requirements: List the exact features, not just the resource type.

3. Constraints: Naming conventions, provider versions, things to avoid.

4. Output format: Specify which files to produce and how to structure them.

Weak prompt:

"Write Terraform for an S3 bucket."

Strong prompt:

"You are a senior AWS platform engineer. Write a Terraform module for an AWS S3 bucket using the hashicorp/aws provider version 5.x. The module must:
- Enable versioning by default, with a variable to disable it
- Enable AES-256 server-side encryption using the aws_s3_bucket_server_side_encryption_configuration resource (not the deprecated inline server_side_encryption_configuration block)
- Block all public access using aws_s3_bucket_public_access_block
- Accept a tags variable of type map(string) applied to all resources
- Use _ as the separator in resource names (e.g., aws_s3_bucket.this)
Output three files: main.tf, variables.tf, and outputs.tf. Do not use deprecated arguments."

The second prompt will produce code that requires minimal correction. The first will produce code that requires significant rework.

Iterative Refinement

Treat AI-generated IaC like a pull request from a junior engineer. Your first prompt gets you a draft. Follow-up prompts refine it:

  • "The aws_s3_bucket_acl resource is deprecated in provider 5.x. Remove it and ensure the bucket is private using only aws_s3_bucket_public_access_block."
  • "Add a lifecycle rule that transitions objects to STANDARD_IA after 30 days and expires them after 365 days."
  • "The bucket_prefix variable should have a validation block that ensures it's lowercase and contains only alphanumeric characters and hyphens."

Each follow-up narrows the gap between generated code and production code. This iterative loop — prompt, review, refine — is the core skill of working with generative IaC.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free