Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Using AI to Write Terraform and Kubernetes YAML

By Kokil Thapa | Last reviewed: September 2026

Using AI to write Terraform and Kubernetes YAML can cut draft time from hours to minutes. It cannot replace a disciplined review loop. Large language models know common HCL patterns and Kubernetes API shapes. They also invent resource types, skip required fields, and suggest deprecated API versions. On production systems, that gap shows up as failed terraform apply runs, CrashLoopBackOff pods, or worse—exposed services you did not intend to ship. This guide walks through a workflow I use on client infrastructure work: prompt with context, generate a draft, validate mechanically, review security by hand, and merge only through CI. If you already run infrastructure as code with Terraform, treat AI as a junior author—not an approver.

What Does Using AI to Write Terraform and Kubernetes YAML Actually Produce?

AI output for infrastructure code falls into three buckets. Most of it is usable scaffolding: a VPC module skeleton, a Deployment with probes, a Service and Ingress pair. Some of it is subtly wrong: wrong attribute names, missing dependencies, or apiVersion values that worked in 2021 but fail today. A smaller slice is actively dangerous: wide-open security groups, cluster-admin bindings, or hard-coded secrets in plain text.

Terraform HCL and Kubernetes YAML look declarative and simple. That simplicity hides coupling. A Terraform resource may depend on a data source three files away. A Kubernetes Pod needs requests, limits, and a ServiceAccount that matches your network policy. Models trained on public snippets rarely know your remote state backend, your Terraform workspace layout, or whether you run K3s on the edge versus a managed control plane.

AI-Assisted IaC WorkflowContextVersions + layoutAI DraftHCL or YAMLValidatePlan + schemaReviewHuman + CIReject Path — Never SkipHallucinated resource namesMissing depends_on or lifecycle rulesOver-privileged RBAC or open SG rulesSecrets in git — use vars or External Secrets
Using AI to write Terraform and Kubernetes YAML: context in, validated and reviewed output out—never apply raw model text.

Good prompts specify constraints the model cannot guess. Bad prompts say “write Terraform for AWS” and hope for the best. The difference shows up in plan output and in how many review cycles you burn.

What AI handles well

  • Boilerplate: variables, outputs, standard labels, probe stubs, resource requests.
  • Repetitive patterns: three similar environments, ten near-identical Deployments.
  • Documentation comments and README sections explaining what a module does.
  • Translating a diagram or ticket into a first-pass manifest or module call.

What AI handles poorly

  • Your exact state backend, workspace naming, and remote state locking setup.
  • Org-specific policy: allowed instance types, tag standards, CIDR ranges.
  • Subtle provider drift between AWS, GCP, and Azure attribute names.
  • Cluster-specific admission controllers, Pod Security standards, or custom CRDs.

How Should You Prompt AI for Terraform HCL?

Terraform prompts need version pins and provider context. Without them, the model may emit syntax from Terraform 0.11 or provider schemas from two major releases ago. State your Terraform CLI version, provider constraints, and whether you use modules from the public registry or private Git repos.

A practical prompt skeleton looks like this:

You are writing Terraform HCL for Terraform 1.9+.
Provider: hashicorp/aws ~> 5.0
Pattern: reusable module with variables and outputs.
Task: S3 bucket with versioning, SSE-KMS, public access blocked.
Constraints:
- No hard-coded ARNs
- Use aws_kms_key data source by alias
- Add lifecycle prevent_destroy on production buckets
Output: main.tf, variables.tf, outputs.tf only

After generation, run validation locally before you trust anything:

terraform fmt -recursive
terraform init -backend=false
terraform validate
terraform plan -out=plan.tfplan

On teams that use OpenTofu instead of HashiCorp Terraform, swap the binary but keep the same gate. The validation mindset does not change. See OpenTofu as the open Terraform fork if your org has standardised on it.

Module-aware prompting

If you maintain reusable Terraform modules, paste the module’s variable block—not the whole repo—into the prompt. Ask the model to call your module instead of inlining resources. That keeps naming and tagging consistent across environments.

module "web" {
  source = "../../modules/ecs-service"

  name           = var.service_name
  vpc_id         = module.network.vpc_id
  subnet_ids     = module.network.private_subnet_ids
  container_image = var.image
  desired_count  = var.replica_count
}

Then ask the model to generate only the root-level variables.tf and environment tfvars. It is less creative that way. That is what you want for production.

Policy and guardrails

Pair AI drafts with policy-as-code. Tools like Sentinel or OPA can block merges when AI adds 0.0.0.0/0 on port 22. Read Sentinel policy as code for Terraform for the pattern. AI does not know your compliance rules unless you paste them in—and even then, it may ignore them.

How Should You Prompt AI for Kubernetes YAML?

Kubernetes YAML fails in production for predictable reasons. Wrong apiVersion. Missing resources.requests so the scheduler packs nodes badly. Probes that point at the wrong port. Services that select no Pods because label keys do not match.

Anchor every prompt to a target cluster version. Kubernetes removes API versions on a published timeline. A model may still emit extensions/v1beta1 Ingress objects that modern clusters reject outright.

Cluster: Kubernetes 1.31
Task: Deployment + Service + Ingress for a Laravel app
Requirements:
- 2 replicas, rolling update maxUnavailable 0
- liveness /health, readiness /ready on port 8080
- requests: 250m CPU, 512Mi memory; limits: 500m / 1Gi
- non-root user, readOnlyRootFilesystem true
- ServiceAccount named laravel-app (already exists)
Output: separate YAML files with --- separators

Validate YAML before any apply:

kubectl apply --dry-run=client -f deployment.yaml
kubeconform -kubernetes-version 1.31.0 -summary manifest.yaml

For Laravel workloads specifically, cross-check against Kubernetes for Laravel getting started patterns. Queue workers, Horizon, and session storage often need separate Deployments the model merges into one blob.

Validation PipelineFormat + LintSchema CheckDry RunHuman Reviewterraform fmt · tflint · yamlfmtCatch style and obvious HCL errorsterraform validate · kubeconformReject unknown fields and bad apiVersionterraform plan · kubectl dry-runSurface dependency and RBAC failuresSecurity review: SG rules, RBAC, secrets, image tags
Every AI-generated Terraform or Kubernetes file should pass format, schema, and dry-run gates before merge.

Resource limits and probes

Models often omit resources blocks or set fantasy CPU values. That leads to noisy neighbours or OOM kills under load. Cross-check against Kubernetes resource limits and requests guidance. If probes are missing, expect CrashLoopBackOff debugging after deploy.

Edge and lightweight clusters

Prompts for K3s lightweight Kubernetes differ from EKS or GKE. Storage classes, load balancer annotations, and Ingress controllers change. Tell the model which ingress controller and storage class name you use.

How Do AI-Assisted IaC Workflows Compare to Manual Writing?

Speed is not the only metric. Mean time to first draft drops with AI. Mean time to safe production often does not—unless you automate validation in CI.

CriteriaManual IaCAI-assisted IaCAI + CI gates
First draft speedSlowFastFast
Schema accuracyHigh if experiencedVariableHigh after validate
Security consistencyDepends on reviewerOften weakImproved with policy checks
Knowledge transferStrongWeak unless documentedModerate with PR notes
Best forNovel architectureBoilerplate, refactorsTeam scale, frequent changes

The winning pattern for most teams is hybrid. Senior engineers define modules, policies, and module interfaces. AI fills in environment-specific calls and YAML variants. CI enforces the contract everyone must meet.

In my experience maintaining GitLab CI pipelines for production apps, the same rule applies to application code and IaC. Generated output merges only when automated checks pass and a human approves the plan diff. That mirrors how I treat AI for test generation in CI—useful accelerator, not a merge button.

Manual vs AI-Assisted IaCManualSlower draft, higher initial accuracyDeep context, fewer surprisesHard to scale repetitive workAI + CI GatesFast draft, validated before mergePolicy blocks bad security patternsNeeds strong module boundariesRecommended HybridHumans own modules, policies, and architectureAI generates env-specific manifests and module callsCI runs plan, conftest, and security scans on every PR
Hybrid IaC: engineers define boundaries; AI accelerates repetitive YAML and HCL inside those boundaries.

What Security Mistakes Appear in AI-Generated Infrastructure Code?

Security review is non-optional. Models optimise for plausible syntax, not your threat model. Recurring issues show up in almost every unreviewed draft.

  1. Secrets in source. API keys in terraform.tfvars or Kubernetes env literals. Use Vault, SSM Parameter Store, or External Secrets instead.
  2. Overbroad IAM and RBAC. *:* actions or ClusterRoleBindings to built-in cluster-admin.
  3. Public exposure by default. S3 buckets, RDS instances, or Services typed LoadBalancer when internal was intended.
  4. Missing network controls. No NetworkPolicy while assuming the cluster is trusted.
  5. Stale image tags. :latest on production Deployments—fine for a demo, wrong for prod.

Align AI usage with AI governance and responsible AI basics. Do not paste production credentials, customer data, or full state files into public chat tools. Redact account IDs if your policy requires it.

External references help you verify what the model claims. The official HashiCorp Terraform documentation and Kubernetes API reference are the ground truth when a generated attribute looks suspicious.

Pre-merge checklist

  • No secrets or tokens in diff.
  • terraform plan shows only intended changes—no surprise destroys.
  • RBAC follows least privilege; ServiceAccounts are named and scoped.
  • Labels and annotations match your org standard for cost allocation.
  • Dependency graph makes sense—AI loves orphan resources with no references.

Paste YAML into a JSON formatter only when converting between formats for tools—not as a substitute for schema validation. Structure pretty-printing does not catch invalid fields.

How Do You Wire AI-Generated IaC Into CI/CD Safely?

CI is where AI-assisted IaC earns trust or loses it. A typical GitLab or GitHub pipeline stage order:

  1. Lint: tflint, terraform fmt -check, yamllint.
  2. Validate: terraform validate, kubeconform or kubeval.
  3. Plan: terraform plan on ephemeral credentials; comment plan output on the PR.
  4. Policy: OPA/conftest, Checkov, or tfsec on the plan JSON.
  5. Apply: manual approval or protected branch only.
stages:
  - lint
  - validate
  - plan

terraform:plan:
  stage: plan
  script:
    - terraform init -input=false
    - terraform plan -out=plan.cache
    - terraform show -json plan.cache > plan.json
  artifacts:
    paths:
      - plan.json

For Kubernetes, run kubectl diff against a staging cluster before production. Controllers like Ingress or cert-manager may mutate objects. Diff shows what the API server will actually accept.

Teams without a full platform group often outsource the hardening pass. Linux system administration and support and maintenance engagements frequently include review of Terraform and k8s manifests before first prod apply. Smaller Nepali businesses run the same risk as global teams: one bad manifest at 11 p.m. beats a week of saved typing.

If you want AI embedded in product workflows—not just IaC—see AI integration and automation services. The discipline is identical: generated logic stays behind validation, logging, and rollback.

When to Use AI for IaCNew IaC task?BoilerplateUse AI draftRefactorUse AI draftNew architectureManual firstAlways Required After AIterraform validate · plan · policy scankubeconform · kubectl dry-run · RBAC reviewNever apply raw model output to production
Decision guide for using AI to write Terraform and Kubernetes YAML: yes for boilerplate, caution for greenfield architecture.

Rollback and blast radius

Keep AI-generated changes small. One module or one Deployment per PR. Large “generate my whole stack” prompts create huge plans that reviewers skim. That is when prod breaks.

On platforms like Adventure Third Pole Trek, booking workloads need reliable deploy paths. The same PR discipline I use for Laravel releases applies to manifest changes: reversible, observable, and tested in staging first.

Read how AI is impacting IT jobs in Nepal for the broader picture. IaC skills still matter. AI shifts time from typing HCL to reading plans and designing modules.

Key Takeaways

  • Treat AI output as a draft: run terraform validate, terraform plan, and Kubernetes schema checks before every merge.
  • Pin Terraform provider versions, cluster version, and module interfaces in every prompt.
  • Never commit secrets; redact credentials before sending context to any model.
  • Use hybrid workflows—humans own architecture and policy; AI handles repetitive HCL and YAML.
  • Wire lint, validate, plan, and policy stages into CI so hallucinations fail the pipeline, not production.
  • Keep PRs small and review plan diffs line by line—speed without review is debt.

People Also Ask

Can ChatGPT write production-ready Terraform?

It can write production-shaped Terraform that still fails validate or plan. Production-ready means your pipeline passed fmt, validate, plan, policy checks, and a human approved the diff. Without that chain, treat any model output as untrusted input.

Is AI-generated Kubernetes YAML safe to kubectl apply?

Not without validation. Run client-side dry-run, schema validation with kubeconform against your cluster version, and a staging apply first. Review RBAC, probes, resource limits, and image tags manually—models routinely skip securityContext and requests blocks.

What tools validate AI-written infrastructure code?

For Terraform: terraform fmt, validate, plan, tflint, Checkov, and tfsec. For Kubernetes: kubeconform, kubectl dry-run, OPA conftest, and optionally kyverno in-cluster. Combine mechanical checks with human review of plan output.

Should juniors rely on AI for learning Terraform and Kubernetes?

Use AI to explore patterns, then read official docs and break things in a lab cluster. Learning happens when you fix a failed plan or a CrashLoop, not when you copy-paste a manifest that happened to apply once. Pair AI drafts with Terraform Associate study and hands-on labs.

Ship IaC Faster Without Shipping Incidents

Using AI to write Terraform and Kubernetes YAML is worth adopting when validation and review keep pace with generation. Prompt with versions and constraints, reject raw output, and merge only through CI gates you would trust for hand-written code. That is how you get speed without trading away weekends to incident response.

Need help hardening Terraform modules, Kubernetes manifests, or CI pipelines around them? Contact us to review your stack—or browse the portfolio for production systems built with the same deploy discipline. For broader context on AI in engineering, see impact of AI on the web industry and about me.

Frequently Asked Questions

It is a draft-first workflow where a large language model generates HCL or YAML from your constraints, then you validate and review before merge. Models know common Terraform patterns and Kubernetes API shapes but also invent resource types, skip required fields, and suggest deprecated apiVersion values. Treat the output as scaffolding from a junior author, not approved infrastructure. Production use means prompt with provider version, module layout, and cluster constraints, then run mechanical checks and human security review before any terraform apply or kubectl apply.

Only after your pipeline approves it. Raw model output is production-shaped, not production-ready. Production-ready means terraform fmt, validate, and plan passed, policy tools like Checkov or tfsec cleared the diff, and a human reviewed the plan output line by line. Without that chain, failed applies, surprise destroys, or exposed resources are common. Never merge unvalidated HCL straight from a chat window.

No, not without checks first. Run kubectl apply --dry-run=client, validate with kubeconform against your target cluster version, apply to staging, and review RBAC, probes, resource requests and limits, securityContext, and image tags by hand. Models routinely omit requests blocks, point probes at wrong ports, mismatch Service selectors to Pod labels, or emit apiVersion values modern clusters reject outright.

Mean time to first draft drops sharply—often from hours to minutes for boilerplate like Deployments, Services, variable blocks, and module skeletons. Mean time to safe production usually does not shrink unless lint, validate, plan, and policy stages run in CI. Speed without review creates debt: one bad manifest at night can cost more than a week of saved typing.

Pin Terraform CLI version, provider constraints, and module pattern in every prompt. State whether you use public registry modules or private Git repos. Specify the task, constraints like no hard-coded ARNs, and desired file outputs such as main.tf, variables.tf, outputs.tf only. For module-based repos, paste the module variable block and ask the model to call your module instead of inlining resources. Vague prompts like write Terraform for AWS produce syntax from old provider releases and orphan resources.

Anchor every prompt to a target cluster version because removed API versions break applies silently in old training data. Include replica count, rolling update strategy, probe paths and ports, CPU and memory requests and limits, securityContext settings, and existing ServiceAccount names. Specify ingress controller and storage class for K3s versus EKS or GKE. Ask for separate YAML files. For Laravel apps, note queue workers, Horizon, and session storage may need separate Deployments the model otherwise merges into one blob.

Run terraform fmt -recursive, terraform init -backend=false, terraform validate, and terraform plan -out=plan.tfplan locally before trusting anything. In CI add tflint, terraform fmt -check, Checkov, tfsec, and OPA or Sentinel policy checks on plan JSON. Teams on OpenTofu swap the binary but keep the same gates. Schema validation catches wrong attribute names; plan output catches dependency and destroy surprises policy tools may miss.

Use kubectl apply --dry-run=client for client-side acceptance, kubeconform with your cluster version for schema checks, yamllint in CI, and OPA conftest or Kyverno for policy. Run kubectl diff against a staging cluster before production because controllers like Ingress or cert-manager mutate objects and diff shows what the API server actually accepts. Mechanical validation catches invalid fields; it does not replace human review of RBAC scope and network exposure.

Recurring issues include API keys in terraform.tfvars or Kubernetes env literals, IAM or RBAC with wildcard actions or cluster-admin bindings, S3 buckets or LoadBalancer Services exposed publicly when internal was intended, missing NetworkPolicy while assuming a trusted cluster, and :latest image tags on production Deployments. Models optimise for plausible syntax, not your threat model. Redact credentials and account IDs before sending context to any model, and never paste production state files into public chat tools.

Manual writing gives high schema accuracy and strong knowledge transfer when the author is experienced, but first drafts are slow. AI-assisted drafting is fast with variable accuracy and often weak security consistency. The winning hybrid pattern: senior engineers define modules, policies, and interfaces; AI fills environment-specific calls and YAML variants; CI enforces fmt, validate, plan, and policy gates everyone must pass. Generated output merges only when automated checks pass and a human approves the plan diff.

Typical pipeline order: lint with tflint, terraform fmt -check, and yamllint; validate with terraform validate and kubeconform; plan on ephemeral credentials with plan output commented on the PR; policy with OPA conftest, Checkov, or tfsec; apply only on manual approval or protected branches. For Kubernetes, kubectl diff on staging before production. Same discipline applies as application code on GitLab CI: useful accelerator, not a merge button. Smaller teams often add a hardening review before first production apply.

AI handles boilerplate well: variables, outputs, standard labels, probe stubs, repetitive multi-environment patterns, README sections, and translating tickets or diagrams into first-pass manifests. It handles poorly your remote state backend and workspace layout, org tag standards and allowed instance types, subtle AWS versus GCP versus Azure attribute drift, admission controllers, Pod Security standards, custom CRDs, and cluster-specific storage or ingress annotations. Context you do not paste in, the model guesses—and guesses wrong under production load.

Use AI to explore patterns, then read official HashiCorp Terraform documentation and the Kubernetes API reference when an attribute looks suspicious. Learning happens when you fix a failed terraform plan or debug a CrashLoopBackOff, not when you copy-paste a manifest that applied once in a lab. Pair AI drafts with hands-on labs and certification study. AI accelerates typing; it does not replace understanding state, dependencies, RBAC, or why a probe failed after deploy.

Paste the module variable block—not the whole repo—into the prompt and ask the model to call your existing module rather than inlining resources. That keeps naming, tagging, and interface consistency across environments. Then ask it to generate only root-level variables.tf and environment tfvars. It is less creative that way, which is what you want for production. Module-aware prompting reduces orphan resources and mismatched attribute names that show up as validate or plan failures.

Keep changes small: one module or one Deployment per pull request. Large generate-my-whole-stack prompts produce huge plans reviewers skim, and that is when production breaks. Pre-merge checklist: no secrets in the diff, terraform plan shows only intended changes, RBAC follows least privilege, labels match org standards, and the dependency graph has no orphan resources. Apply the same reversible, observable, staging-first discipline you use for application releases. Rollback stays feasible only when blast radius stays narrow.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: