[Virtual Event] Unifying infra and app promotions with Spacelift, OpenTofu, and Kargo

Sign up ➡️

General

Guardrails for AI-Generated Infrastructure

Guardrails for AI-Generated Infrastructure

AI-assisted and agentic coding is now mainstream for the infrastructure layer. As well as generating infrastructure as code and configurations, agentic tooling can plan, edit, and sometimes apply infrastructure changes with limited human input.

According to the Spacelift 2026 Infrastructure Automation Report, 93% of organizations have experienced at least one AI-caused infrastructure incident. Nonetheless, 76% of infrastructure teams would apply AI-generated HCL to production with minimal or no review, and a third of them would skip review entirely.

AI delivers genuine speed gains, so teams must adapt and figure out how to use them safely. In this blog, we will examine why AI workflows need guardrails and walk through a lifecycle model for applying them, from code generation to post-apply operations.

What we’ll cover:

  1. Why do we need guardrails for AI workflows?
  2. How to apply guardrails at every stage of AI-generated infrastructure
  3. How Spacelift helps govern AI-generated infrastructure

TL;DR

Guardrails for AI-generated infrastructure work in five layers:

 

  • Before generation – golden modules and approved templates, private module and provider registries, policy as code, AI tool configuration
  • At review – mandatory pull requests, CODEOWNERS, static analysis, secret scanning, policy as code enforcement, cost checks, labels on AI-authored changes
  • At apply – one delivery path, approval gates, dedicated agent identities with short-lived credentials, destructive operations denied by default
  • After apply – drift detection, session logs, AI-specific metrics, post-incident loops
  • Across the organization – a formal AI usage policy covering allowed tools, data access, autonomy per environment, and risk ownership

Why do we need guardrails for AI workflows?

AI coding tools started as autocomplete, but now agents open pull requests, run plans, and in some setups execute applies on their own. The Spacelift 2026 Infrastructure Automation Report reveals that 89% of organizations plan to adopt agentic AI for infrastructure. The speed and efficiency gains from leveraging these tools are too big to ignore.

  • Incidents: Few organizations have figured out how to harness their potential safely. AI tools are causing high-profile production incidents, such as deleting a database. Nonetheless, 86% of infrastructure leaders say they are confident in their ability to govern AI, despite only 30% having a formal AI governance policy in place.
  • Misconfigurations: AI tools customize and generate code based on the context you provide. Without the correct context, they won’t know your specific conventions, topologies, standards, and requirements.
  • Security concerns: Hallucinations and incorrectly produced configuration versions could create a new supply chain risk called slopsquatting. A model invents a plausible package or module name; an attacker registers a malicious package under that plausible name or version, and the next run installs it.

Agents also widen the attack surface since they touch module documentation, README files, tickets, and web pages. Any of that content can carry instructions planted by an attacker, and the agent cannot reliably tell instructions apart from data. This is called prompt injection, which OWASP ranks as the top LLM application risk.

The risk multiplies when an agent combines three capabilities: access to private data such as state files and credentials, exposure to untrusted content, and the ability to act externally through API calls.

  • Volume of changes: In the Spacelift survey, 86% of respondents say AI has increased demands on infrastructure teams, 37% mention higher change volume, and 40% report security vulnerabilities appearing more quickly. Review capacity has not scaled in parallel, increasing load on human reviewers, who may skip reviews altogether.

How to apply guardrails at every stage of AI-generated infrastructure

As with all guardrails, a single point of control is not enough for AI-generated changes. Guardrails work best when applied at several layers. In the case of infrastructure, they should be matched to the change lifecycle stages: before generation, at review, at apply, and after apply, plus an organizational layer around all four:

ai guardrails across the infrastructure lifecycle

1. Before generation

Guardrails at this stage define what the AI produces in the first place.

Golden modules and approved templates: Give AI tools pre-approved building blocks to base their code generation on. Vetted modules and templates provide standards such as tagging and rules, and security and compliance mechanisms, such as encryption, baked in.

A private registry makes the approved modules discoverable and versioned for both humans and AI tools. Instruct your agents to pull only from internal registries for your organization’s modules. Pin dependencies with lockfiles so a fabricated or swapped package fails the build. Do not let agents install new packages or modules on their own: route additions through an allowlist or a human approval.

Policy as code: Policy as code provides standards expressed as executable policies that can be referenced during generation and enforced through the infrastructure lifecycle.

AI tool configuration: Coding agents support customization options, such as rules files, skills, or custom instructions. Use them to encode organizational context, such as which registry to pull modules from, which schemes and conventions to apply, and which patterns and practices are forbidden. Well-defined skills give agents repeatable procedures for common tasks. Run agents sandboxed and scope their tool access to the least privilege needed for the task at hand.

For more information on this, check out our detailed guide: Claude Code for Infrastructure as Code: A Practical Guide.

2. At review

Given the volume of code produced by AI, effectively reviewing it is one of the next bottlenecks. There are different approaches here. Some use specialized AI tools for reviews, others are focusing their human reviews only on the most important and critical parts, others skip reviews altogether.

Regardless of how you approach reviews, treat AI output as untrusted contributions, the same way you would treat a pull request from an unknown external contributor.

Mandatory pull request review: Every AI-generated change must go through a pull request. No direct pushes to main, and no agent-initiated merges without human approval.

The same core platform engineering principles that apply to humans should apply to AI-generated code. AI review tools can help with triage and can flag issues humans might miss at scale, but they should not be the only gate. Use AI review to prioritize human attention, and keep a person accountable for the merge.

Targeted review with CODEOWNERS: Use the CODEOWNERS files to require sign-off from designated reviewers when a change touches critical components such as IAM, networking, or state backend configuration. This helps focus human attention where mistakes can have catastrophic consequences.

Static analysis: Tools such as Checkov, Trivy, and KICS scan IaC for misconfigurations, including permissive security groups and missing encryption. These tools are quite effective at catching the classes of mistakes AI tools repeat most often.

Secret scanning: Add a scanner such as TruffleHog next to your misconfiguration checks, both as a pre-commit hook and in CI. Catching a key at review is better than rotating after exposure.

Policy as code enforcement: Frameworks like Open Policy Agent (OPA) evaluate every plan against your rules. Enforcement levels matter here: Advisory policies warn, while mandatory policies could block the merge.

Cost checks: Tools such as Infracost estimate the cost of a change inside the pull request, and cost policies can block oversized configurations.

Labeling AI-generated changes: Tag AI-authored commits and pull requests with metadata. Specific commit messages and pull request labels let you attribute defects, compare error rates against human-written changes, and measure whether your guardrails work.

3. At apply

Even reviewed changes need a controlled path to production. The apply stage is where guardrails limit what can be executed, where, and with which permissions.

One delivery path: All changes, human or AI, flow through the same CI/CD and GitOps delivery process.

Approval gates: Changes for production or protected environments could require explicit human approval before apply.

Dedicated agent identities: Agents receive least-privilege, short-lived credentials scoped to the job. Give every agent its own identity or service account instead of letting it act under users’ credentials. Separate identities keep audit trails clear and also give you a per-agent kill switch.

Deny destructive operations: Deny by default the ability and commands for agentic assistants to destroy critical resources. Agentic assistants should not be able to delete state, drop databases, or destroy resources unless a rule explicitly allows it for that context.

Sandboxes and isolation: AI coding tools often offer options for sandboxing and isolated environments. This is interesting for IaC because it prevents agents from performing destructive operations, even if they attempt to do so. Isolating these agents limits what they can access on filesystems and reach on the network. This matters most when you let agents work with fewer permissions, unattended, or point them at code you do not fully trust.

4. After apply

This stage verifies that what runs still matches what was approved and monitors operational data, creating a feedback loop for better controls.

Drift detection: 35% of organizations already report growing infrastructure drift, and agents that modify resources outside the approved pipelines could exacerbate matters by patching live resources directly without aligning IaC repos.

Scheduled drift checks compare live infrastructure against code and catch those differences between code and live environments early, while the context is still fresh. Consider revisiting your drift check cadence if you are deploying more due to AI tools.

Audit trails and session logging: According to cloud environment best practices, log every agent action with who triggered it, what changed, and when. Log the agent session, including the instructions it received, the plan it produced, and the tool calls it made. Session logs are helpful for debugging incidents and investigating the agent’s reasoning.

AI-specific metrics: The Spacelift report reveals that only 15% of organizations track the volume of AI-generated IaC in their pipelines, and only 20% track error rates of AI-generated changes. If you measure neither, you cannot say whether AI is helping you move faster or hurting your reliability.

Useful starting points include the share of changes that are AI-generated, their failure and rollback rates compared with human-assisted changes, and the time it takes to detect problems they cause. The labels applied at earlier stages make all of these possible.

Consider extending the labels with which tool and model produced each change. Error rates vary across tools, versions, and even prompt setups, and per-tool numbers could be useful for assessing quality.

Post-incident loops: After every incident involving an AI-generated change, feed the lesson back into the controls. In practice, this means updating policy-as-code configurations, extending to more security scanning checks, adding extra labels and tags, and updating agent skills, rules, and instructions so the same failure cannot repeat.

5. The organizational layer

All the technical controls we described need an overall strategy and organizational frame to hold them together. This is defined in a formal AI usage policy for allowed tools, data classification levels, data access patterns, agent autonomy levels, and risk ownership. Many organizations have skipped this step entirely.

In the Spacelift report, 71% of Pioneer organizations (the top tier for AI maturity and readiness) actively enforce a formal AI governance policy. Among Exposed organizations (the lowest tier for AI maturity and readiness), only 4% do. If you don’t have anything in place, we recommend starting with a simple and concise formal AI usage policy document and expanding progressively. If you are looking for inspiration, check the NIST AI Risk Management Framework.

A practical way to define autonomy levels is to translate them to environments. In sandboxes and ephemeral environments, agents can apply changes on their own. In staging, they can open pull requests that a human merges. In production, they only suggest, and a person owns every step from review to apply.

Ownership of delivering this at the organizational layer is quite important here. Platform engineering teams that own the delivery workflow have started expanding their scope to give both developers and AI agents one paved road to production, with guardrails built into the workflow itself.

Pioneers generate IaC with AI at a higher rate than Exposed organizations, 86% versus 69%, but they do it inside governed pipelines with automated validation and policy enforcement.

Where and how to start?

You cannot start building all of this at once, so take a pragmatic approach: Document existing processes and inventory what you already have that works well and what doesn’t. Draft an overall AI governance and guardrails plan and ask for feedback from inside your org. These efforts are most successful when they are customized according to your needs, processes, and practices.

A pragmatic implementation order for inspiration: Start with review-stage controls, since static analysis and mandatory pull request reviews are cheap and catch the most common failures. Apply gates could be next, as they ultimately guard what goes into production. This includes approvals for protected environments, OIDC credentials, and deny-by-default rules for destructive operations.

With these in place, you could invest in measurement by labeling AI-generated changes and tracking their error rates. Golden modules and registries require the most effort and pay off over the long run, so you can address them as the last step if you don’t have these already.

Leverage each step to gather data to be used as input for the next one: The review-stage controls, such as static analysis findings, show which policies to prioritize and how to set up AI tooling configuration.

Metrics produced at the after-apply-stage from labeled changes show where AI output fails most, which tells you which golden modules to build at the before-generation-stage and so on.

How Spacelift helps govern AI-generated infrastructure

Spacelift is an infrastructure orchestration platform that covers each stage of the lifecycle described above:

Here’s a minimal template example below. A developer or an AI tool fills in two inputs and gets a stack created from a pinned repository and branch, with everything else decided by the platform team:

inputs:
  - id: environment
    name: Environment
    type: select
    options:
      - dev
      - staging
      - prod
  - id: app_name
    name: Application Name
    type: short_text


stacks:
  - key: main
    name: ${{ inputs.app_name }}-${{ inputs.environment }}
    vcs:
      reference:
        value: main
        type: branch
      repository: my-infrastructure
      provider: GITHUB
    vendor:
      terraform:
        manage_state: true
        version: "1.5.0"
  • At review: An OPA-based policy engine evaluates every change, with policies triggered at various lifecycle stages. For example, plan policies inspect proposed resources and control how code enters the pipeline.Here’s a plan policy that blocks the creation of static AWS credentials, a pattern that AI tools can produce:
package spacelift

deny contains sprintf(message, [resource.address]) if {
  message := "static AWS credentials are not allowed (%s)"

  some resource in input.terraform.resource_changes
  some action in resource.change.actions
  action == "create"

  resource.type == "aws_iam_access_key"
}

Plugins extend Spacelift’s functionality, allowing you to integrate with third-party services, automate tasks, and enhance your workflows. For example, integrating with TruffleHog for secret and credential detection (800+ types).

Here’s an example of an approval policy that requires two approvals and no rejections before an unconfirmed run can proceed:

package spacelift

approve if input.run.state != "UNCONFIRMED"

approve if {
  count(input.reviews.current.approvals) > 1
  count(input.reviews.current.rejections) == 0
}

You could further customize this and require approval from a specific team for protected environments.

  • After apply: Scheduled drift detection reconciles live infrastructure with code, and audit trails record every action for investigation and compliance.
  • Across the organization: One governed workflow across various tooling such as Terraform, OpenTofu, CloudFormation, Pulumi, and Ansible. The same guardrails apply whether a human or an AI wrote the code, and they are enforced in one place.

Spacelift Intelligence is a family of AI-powered features in Spacelift. These AI features work inside the guardrails described above and under the same policies, state management, and audit trails:

  1. Intent: Provision and manage infrastructure by describing what you want, directly from your own AI client such as Claude Code, Cursor, or VS Code. You connect through the Spacelift MCP server, and resources live in Intent projects that hold their state, operation history, policies, and cloud integrations.Intent can also deploy modules straight from your module registry, which connects AI provisioning back to the golden modules from the before-generation stage. Intent has its own policies, OPA-based rules, that define what the AI is allowed to do. Every write operation is checked against them before it executes. This is the deny-by-default control from the apply stage, applied to conversational provisioning.
  2. Infra Assistant: An AI chat panel inside the Spacelift UI. In Ask mode, it answers questions about your infrastructure, explains failed runs, and searches the documentation. In Build mode, it creates and manages resources through conversation, governed by the same Intent policies. Admins enable it in settings and choose between ask-only and ask-and-build modes.

If you want to see what this looks like on your own stacks, start a free trial or book a demo with our engineers.

Key takeaways

AI-generated infrastructure code is already in production at most organizations, often getting there without proper review. The failure modes and patterns of AI-assisted code generation and operations are more or less known, but so are the controls. It’s just a matter of applying the core platform engineering principles and adjusting them for the AI reality. Control what gets generated, verify at review, gate the apply, and measure what happens after.

Solve your infrastructure challenges

Spacelift is a flexible orchestration solution for IaC development. It delivers enhanced collaboration, automation, and controls to simplify and accelerate the provisioning of cloud-based infrastructures.

Learn more

Frequently asked questions

  • What are guardrails for AI-generated infrastructure?

    Guardrails are the controls that keep AI-written code inside your standards, applied before generation, at review, at apply, and after apply. No single control point is enough, so they work best layered and backed by a formal AI usage policy.

  • What are the biggest risks of AI-generated Terraform code?

    Misconfiguration leads, because AI tools generate from whatever context they get and rarely know your conventions or topologies. Add hallucinated module names that invite slopsquatting, prompt injection through untrusted content, and change volume that outpaces review, and you get the incident 93% of organizations have already had.

  • What is the difference between policy as code and AI guardrails?

    Policy as code is one guardrail, a set of executable rules that evaluate every plan and block what violates your standards. AI guardrails are the wider set it sits inside, from golden modules and agent configuration through scoped credentials, drift detection, and error-rate metrics.