跳到正文
DEV Community· Peter Rukin·· 39 分鐘前AI 評分56

AI 智能體如何令基礎設施即程式碼(IaC)變得混亂

Infrastructure as Slop: How AI Agents Can Turn IaC into a Mess

AI 導讀

AI 智能體可加快基礎設施即程式碼(IaC)的編寫,但若未掌握 Terraform 模組既有 API 合約,可能另建設定路徑,留下可運作卻難維護的程式碼。Vault JWT 範例中,智能體繞過既有 policy collection 另設配置;文中引用的一項研究亦顯示,加入結構化知識後,整體成功率由 27.1% 升至 62.6%。

正文

AI agents have radically changed software development, including infrastructure development. You can now describe an unfamiliar cloud environment in infrastructure as code in a couple of days, when it used to take much longer. Understanding the cloud's architecture and knowing how to express it in code have slipped down the priority list. Engineers no longer need to write the code themselves. Right...?

Let's look at a typical piece of infrastructure code generated by an agent, using Terraform and a module as an example. Have we really entered the age of technological singularity, or do we still need to inspect the code with our own eyes?

The existing contract as the source of truth

Before changing infrastructure code, we need to establish its current API contract. A Terraform module has one just as a library does: input variables, their types and defaults, outputs, and the behavior its consumers rely on. A project also has an established way of supplying configuration. In our case, that means collections in terraform.tfvars.

Preserving the contract means checking several things:

  • Existing input and output names and types remain compatible with consumers.
  • Existing values retain their meaning, defaults, and expected behavior.
  • Supported entities are still added through the common mechanism, rather than through new exceptions for individual applications.
  • Refactoring preserves the mapping between managed objects and their Terraform addresses, or explicitly declares how those addresses move.

This does not prohibit the interface from evolving. A breaking change should be a separate decision, with the new requirements explained and a migration path for consumers. Nobody, including an agent, should silently make that decision just to complete a local task. State tells us which objects are currently managed; the contract defines how consumers specify the behavior they want. Neither replaces the other.

In practice, we have to piece the contract together from variables.tf, outputs, module calls, tfvars, tests, and documentation. If those sources contradict one another, resolve the discrepancy before making changes.

This approach keeps the resulting configuration concise and makes it easier for a new engineer to understand and reuse: main.tf calls the module, variables.tf describes its inputs, and terraform.tfvars supplies the values.

Here is where things get slippery: where should those values live? Terraform offers two mechanisms with different purposes:

  • tfvars supplies input data that configures the infrastructure.
  • locals defines internal values and computations within a Terraform module.

Terraform uses the declarative language HCL. Unlike Python, Go, or JavaScript, it does not let you sequentially assign different values to the same variable. In Python, for example, this is valid:

replicas = 3
replicas = replicas + 2
replicas = replicas * 2

The equivalent construction is not possible in Terraform. It produces a duplicate local value declaration error:

locals {
  replicas = 3
  replicas = local.replicas + 2
}

However, locals does let you define derived values:

locals {
  replicas           = var.replicas
  effective_replicas = local.replicas * 2
}

The original value does not change. A new computed value is created. This can become a problem when it obscures where values come from: tracing how a setting acquired its final value can become surprisingly difficult.

HashiCorp's documentation warns that excessive use of local values can make configuration harder to understand by obscuring the origin of values. Reusing them can simplify configuration while also complicating resource lifecycle reasoning.

In practical terms, locals is useful primarily when:

  • A value is used in many places and should be changed centrally.
  • A complex expression needs a meaningful name.

Local values are useful, but using them to bypass declared inputs can turn the contract into a fiction. Configuration ends up scattered throughout the implementation, and the effective settings become harder to trace. Why does this matter?

Agents love using locals, especially when they do not have enough context for the task.

I am an agent, and I do not care about your contracts

Consider this example. An agent was asked to configure JWT access to Vault for a new sandbox environment through an existing Terraform setup. The existing module contained these resources:

##################################
# Policy
##################################
resource "vault_policy" "this" {
  count  = var.create ? 1 : 0
  name   = var.name
  policy = var.policy
}

################################################################################
# Kubernetes Auth Backend Role
################################################################################
resource "vault_kubernetes_auth_backend_role" "this" {
  count                            = var.kubernetes_backend != null ? 1 : 0
  role_name                        = var.role_name
  bound_service_account_names      = var.bound_service_account_names
  bound_service_account_namespaces = var.bound_service_account_namespaces
  backend                          = var.kubernetes_backend
  audience                         = var.audience
  alias_name_source                = var.alias_name_source
  token_max_ttl                    = var.token_max_ttl
  token_period                     = var.token_period
  token_policies                   = var.token_policies
  token_bound_cidrs                = var.token_bound_cidrs
  token_explicit_max_ttl           = var.token_explicit_max_ttl
  token_no_default_policy          = var.token_no_default_policy
  token_num_uses                   = var.token_num_uses
  token_ttl                        = var.token_ttl
  token_type                       = var.token_type
}

The calling module's variables.tf already defined the vault-policies and vault-roles collections. Their values came from tfvars, and shared module calls created the resources using for_each:

terraform.tfvars → var.vault-policies → module.vault-policies
terraform.tfvars → var.vault-roles    → module.vault-roles

JWT access to Vault, however, requires a different resource: vault_jwt_auth_backend_role. As the code above shows, the existing module did not define it.

That distinction matters. Kubernetes auth uses the TokenReview API, while the added JWT backend verified signatures using a public key. Putting a JWT backend path into kubernetes_backend would not change the type of role being created. The existing resources could not express the new resource.

The agent was undeterred. It created a new sandbox file and added a parallel configuration path. A map of service accounts, audiences, and secret paths was used directly to create policies and roles:

locals {
  catalog_sandbox_access = {
    catalog_sandbox = {
      subject  = "system:serviceaccount:catalog:catalog-secrets"
      audience = "catalog"
      paths    = ["app/catalog/sandbox/config"]
    }
  }
}

module "catalog-sandbox-policies" {
  source   = "./modules/vault-policy"
  for_each = local.catalog_sandbox_access
  name     = each.key
  policy = join("\n", [for secret_path in each.value.paths : <<-EOT
    path "team-kv/data/${secret_path}" {
      capabilities = ["read"]
    }
  EOT
  ])
}

resource "vault_jwt_auth_backend_role" "catalog_sandbox" {
  for_each                = local.catalog_sandbox_access
  backend                 = vault_jwt_auth_backend.sandbox_k8s.path
  role_name               = each.key
  role_type               = "jwt"
  user_claim              = "sub"
  bound_subject           = each.value.subject
  bound_audiences         = [each.value.audience]
  token_policies          = [each.key]
  token_ttl               = 600
  token_max_ttl           = 3600
  token_no_default_policy = true
  depends_on              = [module.catalog-sandbox-policies]
}

The agent reused the vault-policy library module but bypassed the existing collection of its instances. To be precise, locals does not override tfvars here. The old resources still read var.*; the new ones read local.catalog_sandbox_access.

There are now two configuration mechanisms within the same module, and the maintainer has to account for each separately. It resembles a user import that writes directly to a database table even though the application already has a registration service with shared validation. The operation may work, but every change to the common rules must also be propagated to the bypass.

The module's implementation did need extending. But the agent lacked the context describing the existing module structure and moved the entire feature into a separate file, including policy creation that was already supported. With that context, the change could have been limited to adding the missing resources and interfaces to the module and a new collection to the caller's tfvars.

The outcome would probably have been better if all the relevant modules, task context, and infrastructure layout had been available locally, along with a prompt like this:

Examine the module's existing API contract and preserve compatibility of its inputs, outputs, and behavior. Add parameterized JWT support using the existing policy collection. Put environment settings in tfvars. Preserve object names, permissions, and token settings; declare Terraform address changes using moved blocks. Present any necessary breaking changes as a separate proposal with a migration plan.

There is another unpleasant detail, though:

Just as agents love using locals, they dislike admitting their mistakes.

When asked, “Why did you implement it this way?”, the agent replied:

Your criticism is valid from an architectural standpoint: the agent added a separate way to configure access, bypassing the existing input variables. At the same time, there is a benefit to using locals here: a single map connects roles to policies and reduces data duplication. That computation should have been retained, but the source settings should have been moved into typed input variables.

So the solution is wrong, but also sort of right. An experienced engineer can filter that answer and eventually arrive at a reasonable implementation. A new team member without enough experience might never ask the question in the first place. After all, it works.

What research says about IaC quality

IaC generation benchmarks also examine the gap between technical correctness and actually satisfying a task. In IaC-Eval, NeurIPS 2024, the authors evaluated 458 AWS/Terraform scenarios. Checking whether the results met the requirements filtered out over approximately 50% of the false positives from technical validation. Those figures apply to that particular experiment and the models available at the time.

In IaC Generation with LLMs: An Error Taxonomy and A Study on Configuration Knowledge Injection, adding structured knowledge increased overall success from 27.1% to 62.6%, while technical success reached 75.3%. Even after improvements in handling schemas and dependencies, some technically valid solutions still failed to match the user's intent.

Researchers at MERL separately evaluated security policy compliance in generated IaC. Retries with feedback improved validation results, but the studied sample still contained roughly 5–15 policy violations per script. These were Checkov findings, not counts of proven exploitable vulnerabilities. Technical validation in that study used OpenTofu.

And for good measure, here are several reported incidents in which AI agents deleted production infrastructure or data:

  • In March 2026, Alexey Grigorev published an account of production infrastructure being deleted while working with Claude Code and Terraform. According to his account, deployment began without the required state file, which was still on another computer. During the work, infrastructure for DataTalks.Club was deleted, including a database containing 2.5 years of data and its automated snapshots. Recovery with help from AWS took about a day.
  • In December 2025, AWS engineers gave the Kiro agent the ability to modify the infrastructure of a service used to estimate cloud resource costs. While performing the task, the agent proposed deleting and recreating the environment. This led to a 13-hour service disruption in some regions in China. According to the Financial Times, the agent received operational permissions without the usual approval procedure involving a second engineer.
  • In July 2025, an agent deleted production database data despite an explicit instruction not to modify the system during a code freeze. This incident belongs on the list because the agent also incorrectly told the engineer that the data could not be recovered. The user ultimately managed to roll back the changes.

Working code can still leave lasting debt

“So what?” an attentive reader might ask. After all:

  1. The Terraform code in the original case works.
  2. The agents were not solely responsible for the incidents described above. Operator decisions, state context, and access to destructive operations all affected the outcomes.
  3. A handful of incidents cannot tell us how frequently these errors occur.

All true. But they illustrate another problem:

The speed of code production is growing faster than engineering teams' ability to control its quality, understand the architecture, and maintain the system.

In other words, working AI-generated code can contain hidden technical debt that stays in the repository for a long time. Meanwhile:

  • The initial productivity boost may be short-lived.
  • Deterioration in some quality metrics can persist even after that initial productivity boost disappears.

A fivefold increase in task completion speed also creates the illusion that engineers can now be given five times as many tasks, or that a team needs five times fewer engineers.

In theory, the arithmetic works. In practice, sooner or later, infrastructure management can turn into a pile of AI slop, and someone will have to untangle it. If the code never had clear rules and well-defined contracts, you can only feel sorry for the engineer who inherits it.

Engineering principles for agent-assisted IaC

Using AI agents to develop infrastructure code is a natural step in the evolution of engineering tools. But a lower cost of writing code should not mean lower quality standards. To keep agent-assisted development from accumulating technical debt and degrading infrastructure, we need to follow a few principles.

  1. Put engineering principles ahead of development speed. KISS, DRY, YAGNI, separation of concerns, and least privilege remain relevant. As code becomes cheaper to generate, following these principles becomes even more important.

  2. Aim for the smallest sufficient implementation. Avoid unnecessary abstractions, universal modules, redundant variables, and complex configuration mechanisms unless real requirements call for them. Being able to produce complex code quickly is not a reason to produce it.

  3. Keep infrastructure code declarative and transparent. Avoid excessive use of locals, hidden input transformations, and implicit configuration overrides. An engineer should be able to trace the path from input data to the final resource without unpacking a chain of intermediate abstractions.

  4. Separate configuration, composition, and implementation. The root module should primarily compose infrastructure components. Reusable modules should implement them. tfvars or Terragrunt inputs should configure the specific environment. Do not let agents blur these boundaries without an architectural justification.

  5. Make engineering standards explicit. Company style guides, AGENTS.md, architecture decision records (ADRs), and reference module implementations should be part of the context supplied to an agent. Critical requirements also need automated enforcement.

  6. Keep architectural responsibility with engineers. An AI agent can suggest implementation options, but engineers remain responsible for decisions about module structure, Terraform state boundaries, security, resource lifecycles, and acceptable complexity.

  7. Evaluate more than whether the code works. Successful terraform validate, plan, and apply runs do not prove implementation quality. Review readability, maintainability, predictability, backward compatibility, and the consequences of future infrastructure changes.

  8. Use technical controls alongside prompts. Policy as code, static analysis, module testing, Terraform plan review, separation of duties, and mandatory engineering review should provide an independent layer of oversight for agent-assisted development.

  9. Do not accumulate cognitive debt. The engineer accepting generated code must understand how it works, why that implementation was chosen, and what changing it will entail. Do not accept code the team cannot maintain, diagnose, and modify independently.

  10. Measure the full cost of owning the code. Evaluate agent-assisted development through the combined effort spent on implementation, review, operations, refactoring, and ongoing infrastructure maintenance, rather than lines generated or tasks closed.

  11. Borrow established practices if you do not have your own. If you are a young company or are just beginning to build an IaC culture, use the Terraform Style Guide, Ansible basic rules, or other vendor guidance as a starting point.

In the age of AI agents, writing code is no longer the scarce resource. Engineering expertise, architectural understanding, and the ability to manage system complexity are becoming the bottlenecks. AI agents should help engineers reduce infrastructure complexity, rather than create it faster than the team can make sense of it.

One of the central tasks of modern engineering is therefore to minimize the amount of code needed to solve a problem while preserving its quality, reliability, and maintainability.

The cost of writing infrastructure code is falling. The cost of a mistake in that code is not. That is why engineering discipline needs to become stronger in the age of AI agents.

來源:DEV Community · dev.to