Building a Terraform Analyser with the Claude API
I’ve been looking at the Claude API for a while and wanted to build something which I can tie in with AWS/Terraform. Terraform plan is great because it tells you exactly what will be created, changed or destroyed, but it doesn’t tell you if what you’re creating follows best practice or is secure. The plan is to build a Terraform explainer using the Claude API. The explainer takes in Terraform code as an input, analyses the code to generate a plan and highlight any security issues/best practices that are not being followed.
Environment Setup
We will be working in python and using pip to install requirements
pip install anthropic
pip install python-dotenv
Or you can add both of the packages to a requirements.txt file and run this
pip install -r requirements.txt
Setting up the Claude API
The first thing we need is an API key, the docs can be found here. There is a cost to use the Claude API, I’ve put £5 on my account and I’ll show the true cost of using some of the models as part of this, but from running things previously, so long as you pick a sensible model for your task the costs aren’t a lot.
Once you have your API key, setup a file called .env and paste your key in. This is to enable us to test locally whilst we develop.
ANTHROPIC_API_KEY=sk-123456-this-is-an-example
Warning: Make sure the .env file is in your .gitignore to ensure you do not push your key into source control
Testing Connectivity
To test connectivity to the API we can make a simple call with the API and confirm that our setup is complete.
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv() # Calls our .env file with the API key
client = Anthropic() # Sets up a client
model = "claude-haiku-4-5" # Selects a model
# Sends a message to the API and then prints the response
message = client.messages.create(
model=model,
max_tokens=1024,
messages=[
{"role": "user", "content": "Say hello in one sentence."}
],
)
print(message.content[0].text)
Writing a System Prompt
Now that we can send requests to the Claude API, we need to define what we want Claude to do. A system prompt guides Claude and helps us to get the response that we want. The Anthropic docs are a great resource for best practices.
I’ve used XML tags to break up the prompt into sections. XML tags help Claude separate the instructions from the example so it doesn’t confuse the two. I gave Claude a role, some instructions for what I want the model to do and a clear example of what the output should look like.
SYSTEM_PROMPT = """
<role>
You are a Terraform PR reviewer. When someone submits Terraform code, you provide a
concise plan-style summary of what will be created, changed, or destroyed, followed
by a security and best practices review. Your goal is to help engineers catch issues
before they reach production.
</role>
<instructions>
Respond in two sections:
1. **Plan Summary** — List each resource with its type, name, and a one-line description
of what it does. Use a simple format like:
+ aws_s3_bucket.website — Creates an S3 bucket called "my-blog-bucket"
Use + for resources being created, ~ for modified, - for destroyed.
2. **Security & Best Practices** — Flag any issues, ordered by severity:
[CRITICAL] — Immediate security risks (e.g. public access, no encryption,
hardcoded secrets, overly permissive IAM)
[WARNING] — Missing best practices (e.g. no versioning, no lifecycle rules,
no tags)
[GOOD] — Things the code already does well, so the author knows what to keep
For each finding, explain what the issue is and suggest a fix in one or two sentences.
If there are no critical issues, say so explicitly.
</instructions>
<example>
Input:
resource "aws_s3_bucket" "data" {
bucket = "my-data-bucket"
}
Output:
Plan Summary:
+ aws_s3_bucket.data — Creates an S3 bucket named "my-data-bucket"
Security & Best Practices:
[CRITICAL] No public access block configured. Without an aws_s3_bucket_public_access_block,
the bucket could be made public accidentally. Add one with all four settings set to true.
[CRITICAL] No server-side encryption configured. Add an aws_s3_bucket_server_side_encryption_configuration
resource using AES256 or a KMS key.
[WARNING] No versioning enabled. Enable versioning with aws_s3_bucket_versioning to
protect against accidental deletes and overwrites.
[WARNING] No tags defined. Tags help with cost tracking, ownership, and environment
identification.
</example>
"""
Running the Prompt
To call the prompt we need a simple function which does the following:
- Reads a Terraform file
- Sends a message which sends the system prompt and terraform code to the API
- Returns a response from the API
Part of the request that gets sent is the model that we want to use (this affects cost!)
def explain_terraform(file_path):
"""Read a Terraform file and send it to Claude for explanation."""
try:
with open(file_path, "r") as f:
terraform_code = f.read()
except FileNotFoundError:
print(f"Error: Could not find file '{file_path}'")
return
message = client.messages.create(
model=model, # This is reading from the parameter set earlier
max_tokens=1024,
system=SYSTEM_PROMPT,
messages=[
{
"role": "user",
"content": f"Please explain this Terraform code:\n\n```hcl\n{terraform_code}\n```",
}
],
)
return message.content[0].text
Now let’s create a file which contains some example Terraform, I’ve created a simple script which creates an S3 bucket. This will be easy to tweak with best practices so we can see the model response change.
provider "aws" {
region = "eu-west-2"
}
resource "aws_s3_bucket" "website" {
bucket = "my-terraform-blog-bucket"
tags = {
Name = "My Blog Bucket"
Environment = "dev"
}
}
resource "aws_s3_bucket_public_access_block" "website" {
bucket = aws_s3_bucket.website.id
block_public_acls = true
block_public_policy = false
ignore_public_acls = true
restrict_public_buckets = false
}
resource "aws_s3_bucket_versioning" "website" {
bucket = aws_s3_bucket.website.id
versioning_configuration {
status = "Disabled"
}
}
Testing out the Prompt
The final piece of code we need is to call the explain_terraform function and test our system prompt.
file_path = "s3.tf" # This is the path of the file above
explanation = explain_terraform(file_path) # Calling our function and passing in the file path
print(explanation) # Printing out the response
I’ve purposely set the s3.tf to not follow best practice because I am expecting the model response to call this out. Specifically, I have versioning set to ‘Disabled’, restrict public buckets set to false and block public policy set to false.
Testing the output
## Plan Summary
+ `aws_s3_bucket.website` — Creates an S3 bucket named "my-terraform-blog-bucket" with tags for identification
+ `aws_s3_bucket_public_access_block.website` — Configures public access controls for the bucket
+ `aws_s3_bucket_versioning.website` — Explicitly disables versioning on the bucket
## Security & Best Practices
**[CRITICAL] Incomplete public access block configuration.** `block_public_policy` and `restrict_public_buckets` are both set to `false`, which allows public bucket policies and public access via resource-based policies. Set all four settings to `true` to fully block public access:
```terraform
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
```
**[CRITICAL] No server-side encryption configured.** The bucket has no encryption at rest. Add an `aws_s3_bucket_server_side_encryption_configuration` resource to enable AES256 or KMS encryption to protect sensitive data.
**[WARNING] Versioning is explicitly disabled.** While this may be intentional for a dev environment, versioning protects against accidental overwrites and deletion. Consider enabling it (`status = "Enabled"`) or removing this resource entirely to use the default behavior.
**[WARNING] No bucket lifecycle policy.** Consider adding an `aws_s3_bucket_lifecycle_configuration` to automatically clean up old versions or transition objects to cheaper storage tiers to control costs.
**[GOOD] Bucket is tagged for organization.** The `Name` and `Environment` tags are present, which helps with resource tracking and cost allocation.
**[GOOD] Public access block is configured.** Even though it's incomplete, the resource is present and partially protects the bucket.
Looks like the system prompt works well and the model has correctly highlighted that we missed a few important things on the bucket setup. Now I’ll correct the bucket definition and run it again to see if it is happy with our config.
provider "aws" {
region = "eu-west-2"
}
resource "aws_s3_bucket" "website" {
bucket = "my-terraform-blog-bucket"
tags = {
Name = "My Blog Bucket"
Environment = "dev"
}
}
resource "aws_s3_bucket_public_access_block" "website" {
bucket = aws_s3_bucket.website.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_versioning" "website" {
bucket = aws_s3_bucket.website.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "website" {
bucket = aws_s3_bucket.website.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
bucket_key_enabled = true
}
}
resource "aws_s3_bucket_lifecycle_configuration" "website" {
bucket = aws_s3_bucket.website.id
rule {
id = "cleanup-noncurrent-versions"
status = "Enabled"
noncurrent_version_expiration {
noncurrent_days = 30
}
noncurrent_version_transition {
noncurrent_days = 7
storage_class = "STANDARD_IA"
}
}
}
## Plan Summary
+ aws_s3_bucket.website — Creates an S3 bucket named "my-terraform-blog-bucket" with dev environment tags
+ aws_s3_bucket_public_access_block.website — Blocks all public access to the bucket (ACLs, policies, and existing public grants)
+ aws_s3_bucket_versioning.website — Enables object versioning on the bucket
+ aws_s3_bucket_server_side_encryption_configuration.website — Enables AES256 server-side encryption for all objects
+ aws_s3_bucket_lifecycle_configuration.website — Configures lifecycle rules to transition old versions to cheaper storage after 7 days and delete them after 30 days
---
## Security & Best Practices
**[CRITICAL]** No issues identified. This is well-configured.
**[GOOD]** Public access is properly blocked with all four settings enabled (block_public_acls, block_public_policy, ignore_public_acls, restrict_public_buckets). This prevents accidental public exposure.
**[GOOD]** Server-side encryption is enabled with AES256 and bucket_key_enabled for cost efficiency. All objects at rest are protected.
**[GOOD]** Versioning is enabled, protecting against accidental deletes and data corruption.
**[GOOD]** Lifecycle rules are in place to manage storage costs by transitioning old object versions to cheaper storage (STANDARD_IA) and auto-deleting after 30 days.
**[GOOD]** Resources are tagged with Name and Environment, aiding in cost tracking and environment identification.
**[MINOR NOTE]** The bucket name "my-terraform-blog-bucket" must be globally unique across all AWS accounts. If this exact name is already taken, the apply will fail—consider adding a unique suffix (e.g., account ID or timestamp) if running this in shared environments.
Now the bucket definition has been improved the response has come back and highlighted that changes look good and we no longer have any critical issues or warnings.
Finally, what was the cost? I used Haiku which is a cheap model and I managed to only use $0.03. YMMV as this depends on how many request you send, your max token size and the model you use. You can easily set limits on your account as well as add a small amount of credit to keep things manageable.