August 6, 2026

Agentic IaC Explained: How AI Closes the Terraform Drift Gap

Agentic IaC uses AI to continuously detect drift, unmanaged resources, and policy gaps in Terraform. See how the observe-detect-plan-validate loop works.

~ min read
~0 min read
Daniel Caduri

TL;DR

  • A tool that writes Terraform when prompted and stops isn't agentic; the test is whether it keeps comparing declared code against live cloud state on its own schedule, without a human re-triggering the check.
  • Four gaps persist after Day 1, even with full Terraform adoption: drift from console edits, resources that never enter state, cost overruns that go unnoticed until the invoice, and configurations that pass Terraform plan while still violating policy.
  • Every genuinely agentic system runs the same six-step loop: Observe, Detect, Plan, Validate, Apply, Confirm. The loop, not the AI model, is what catches a drifted resource at 3 am before it becomes Monday's incident.
  • Two distinct implementations exist: a coding agent with live cloud context that answers questions when asked, and an autonomous platform that runs the loop continuously with no human starting each cycle.
  • StackGuardian runs this loop through SGCode (discovery, codification) and SGOrchestrator (drift detection, Policy Sets, audit logging) and exposes the same governance data to Claude and ChatGPT via a hosted MCP server, so a query like "why did workflow #1247 fail" returns real data rather than a guess.

"Agentic" has become one of those words that show up in every product announcement this year: agentic AI, agentic workflows, agentic platforms, often applied to anything with a chat interface bolted on. Most of that is marketing gloss on top of ordinary automation. But underneath the noise, something real has changed in how infrastructure gets managed: AI systems that don't just answer a prompt and stop, but keep watching a live environment and acting on it.

Infrastructure as code is one of the clearest places to see the difference between the marketing and the mechanics, because the stakes are concrete. A misconfigured chatbot is embarrassing; a misconfigured production database is an incident. This piece works through what agentic IaC actually means, why static Terraform alone is no longer enough after the first deployment, the six-step loop every agentic system runs, and how StackGuardian implements that loop in practice, including where human approval still has to sit in the process. By the end, the goal is a clear answer to whether a given tool is genuinely agentic or just has a chat window bolted onto a script, and what to look for in a platform that runs the full loop safely.

What is Agentic IaC?

Agentic IaC is infrastructure management in which an AI system continuously compares the live cloud state against the declared infrastructure code, detects any gaps, and closes them without requiring an engineer to first notice the problem and manually trigger a fix. The word "continuously" is doing the real work in that definition. Picture a security group that is manually opened at 11 pm during an on-call incident and never closed. A reactive tool never sees it happen. An agentic system flags it as drift within its next scan cycle, opens a remediation plan, and either applies it automatically or routes it for approval, hours before anyone notices the misconfiguration sitting in production. A tool that generates a Terraform resource when prompted is helpful, but it isn't agentic because it has no ongoing relationship with the environment once it returns an answer.

Reactive AI tools, plain Claude, ChatGPT, and GitHub Copilot, used on their own, work the same way regardless of the task. A prompt goes in, an answer comes out, and the tool stops until the next prompt. Ask one to write a Terraform resource for an S3 bucket, and it will do so based on whatever context you gave it. Ask it what's actually running in your AWS account right now, and it can't answer because it has no live connection to your cloud.

An agentic system flips that relationship, and the difference shows up concretely. A platform engineer doesn't ask "is anything drifted right now" every morning; the system has already been checking overnight and surfaces a ranked list of what changed, what it's costing, and what's waiting on approval. It monitors the environment on its own schedule, decides what needs to change based on its observations, takes action, checks whether the action worked, and repeats the cycle. Applied specifically to infrastructure, that means treating drift, unmanaged resources, and policy violations as things caught by the system overnight, not things an on-call engineer discovers three weeks later while debugging an unrelated incident.

Reactive AI Tools

Agentic IaC Systems

Trigger

Human prompt, every time

Continuous observation of the live state

Awareness of the cloud

Only what's pasted into the prompt

Real-time, from actual cloud APIs

Stops after

One response

Never, until the goal is met

Best fit

Writing new Terraform from a spec

Closing drift, remediating violations

Why Standard IaC Stops Working After Day One

Terraform and tools like it solved a real problem: instead of clicking through a cloud console to build infrastructure by hand, teams could define resources declaratively, store the definitions in Git, and review changes through pull requests. That's what most people mean by "IaC adoption," and it's genuinely valuable at the moment infrastructure is first created.

The problem shows up afterward. Take a Kubernetes cluster provisioned entirely through Terraform on day one, every node group, every IAM role, every security group defined in code and reviewed through a pull request. Six months later, an SRE bumps the node pool's instance type directly through the AWS console to handle a traffic spike, because waiting for a PR review during an active incident isn't an option. The change works, the incident closes, and nobody circles back to update the Terraform. From that point forward, every terraform plan either silently reverts the fix on the next apply or gets excluded from state entirely, and the security group the SRE also opened for debugging that same night never makes it back into code either. Infrastructure keeps changing after that first deployment, through console edits, CLI commands, and CI/CD pipelines other than the one Terraform runs through, while the Terraform code itself stays exactly as written unless someone actively maintains it. Four gaps grow in that space between the code and the cloud:

Gap

What Happens

Drift

A manual change (a security group port opened for debugging, a tag edited by hand) diverges from what the code declares, and nothing reconciles it automatically.

Unmanaged resources

Anything created before IaC adoption, or outside an approved workflow, never enters state, so drift detection and policy checks never apply to it.

Cost overruns

An oversized instance or an overprovisioned node pool reaches production because nothing evaluates cost impact during the actual deployment, only after the invoice arrives.

Policy violations

A configuration can pass terraform plan cleanly while still violating a security or compliance requirement, since plan syntax checks and policy validation are two different things.

These four gaps compound because they're invisible individually. A single drifted security group looks like a minor annoyance. A cloud account with hundreds of drifted resources, a chunk of unmanaged infrastructure, and a handful of policy violations that never got caught looks like a real incident waiting for a trigger. This is the exact problem StackGuardian was built to close; its own positioning puts it plainly: "somewhere in your cloud environment right now, there's infrastructure nobody fully understands."

The SRE's fix from the example above is exactly what SGCode's Cloud Inventory is built to surface before it becomes a six-month-old mystery. It connects to AWS, Azure, and GCP accounts, discovers every resource across the environment, and classifies which resources have IaC coverage against connected state backends and which don't, whether that gap is three days old or three years old.

The Agentic IaC Loop: Six Steps From Observe to Confirm

Every agentic IaC system, whether it's a coding agent wired into live cloud data or a dedicated platform running in the background, executes some version of the same cycle. The names vary slightly between tools, but the shape doesn't change.

Step

What Happens

1. Observe

Read live cloud state directly from provider APIs, not a cached snapshot from the last Terraform refresh.

2. Detect

Compare live state against declared IaC state to surface drift, unmanaged resources, and policy gaps.

3. Plan

Generate the specific code change that closes the gap, including any dependent resources required to maintain consistency.

4. Validate

Run the generated change through policy and guardrail checks before anything gets applied.

5. Apply

Execute the change, either automatically for low-risk cases or after a human approves it for higher-risk ones.

6. Confirm

Verify the applied change produced the expected result, log what happened, and start the cycle again.

The loop running continuously is what separates this from a script. A script executes when triggered and stops; if nobody triggers it, whatever it was supposed to catch sits unnoticed. A drifted resource that shows up at three in the morning stays drifted until someone happens to look, unless something is watching on its own schedule. That gap between "something changed" and "someone noticed" is exactly what the loop is built to close.

What Happens Without the Loop: A Worked Example

Consider a mid-sized platform team running a checkout service on AWS. A customer reports intermittent timeouts, and an engineer picks up the ticket. The obvious first move is to check the load balancer and the service's security group rules, since that's usually where a connectivity issue like this traces back to.

The engineer opens the console and finds the security group attached to the checkout service, but it references a second security group that isn't present anywhere in the Terraform state file. Following that thread, they find it was created eighteen months ago during a hotfix, along with a handful of dependent resources, a network interface, an IAM role, and an EBS volume, none of which ever made it into code. To safely change anything here without making the drift worse, those resources need to be codified first, which means manually tracing each resource ID across three different AWS console tabs, writing the corresponding Terraform blocks, and running imports until the plan shows zero diff.

The actual fix, once the misconfigured rule was identified, took about fifteen minutes. Finding it took most of an afternoon, not because the problem was hard, but because nobody had visibility into what was and wasn't under management until the incident forced someone to look. An agentic loop running continuously in the background would have flagged those resources as unmanaged the moment they were created, long before a customer noticed anything.

Two Different Paths to Agentic IaC

Agentic IaC isn't one product category with a single implementation. It shows up in two distinct forms, and knowing which one a given tool actually offers is worth checking before evaluating it.

Path 1: AI coding agents with live cloud context. Tools like Claude, Cursor, and GitHub Copilot are reactive by default; they work against the files open in an editor, with no independent view of what's actually running in a cloud account. Connecting a live-data source through an MCP server changes that: the same coding agent can now answer questions like "which resources are drifted in production" using real inventory data instead of guessing from a stale config file. The engineer still starts every query, but the answers reflect the actual environment.

Path 2: A platform running the full loop on its own. This is the harder version to build, a system with no human in the initiation seat at all, continuously scanning, detecting, planning, validating, applying (within approval limits), and confirming, around the clock. This is what catches the drift that happens at three in the morning before it becomes Monday's incident.

Path 1: Coding Agent + Live Context

Path 2: Autonomous Platform

Who starts each cycle

The engineer, with a prompt

The platform, on its own schedule

Best for

Interactive investigation, codifying a specific resource

Catching drift and violations, nobody's actively looking for

Cloud awareness

Live, but only when queried

Live and continuous

These two paths aren't competing with each other. A platform team can use a coding agent with live cloud context for hands-on investigation and codification work, while the same underlying platform runs its autonomous loop in the background for everything nobody's actively watching. Both surfaces drawing from the same data is what makes that combination work, rather than creating two disconnected sources of truth.

The Five Capabilities Every Agentic System Needs

Agentic systems, whether in infrastructure or elsewhere, tend to share the same five underlying capabilities. Naming them makes it easier to evaluate whether a given tool is genuinely agentic or just has a chat window attached to a script.

Capability

What It Does

Perception

Continuous scanning of the live state, not an on-demand refresh triggered by a user.

Planning

Comparing the live state against the declared goal to figure out what's wrong and what sequence of actions fixes it.

Reasoning

Weighing a proposed change against cost, security, and blast-radius constraints before deciding whether to act automatically or ask a human first.

Tool calling

Actually executing the action, running a plan, applying, opening a pull request, sending an alert, and triggering a pipeline.

Memory

A persistent record of what was observed, decided, and done, so the next decision has context from everything that came before it.

A tool missing memory re-flags the same drifted tag every week instead of recognizing it's the same resource a specific team keeps hand-editing, and never surfaces that pattern as something worth fixing at the source. A tool missing reasoning can generate a technically valid Terraform change that also deletes a production RDS instance, because nothing weighed the blast radius before applying it. A rule that blocks any workflow from resizing or deleting a resource tagged env:production without approval is what reasoning looks like in practice, not a policy nobody wrote down. All five need to be present for the loop to run safely, not just quickly.

How StackGuardian Implements the Agentic Loop

StackGuardian maps its own platform directly onto the five capabilities above, rather than treating "AI features" as a separate add-on layered over existing tools. Each piece of the loop lives in a specific part of the product:

Capability

StackGuardian Feature

Perception

SGCode's Cloud Inventory continuously scans AWS, Azure, and GCP accounts for every resource, managed or not

Planning

SGCode's AI-powered codification, cross-referencing discovered resources against connected state backends to generate the specific Terraform or OpenTofu needed to close the gap

Reasoning

Policy Sets (Tirith or OPA), evaluating every planned change against cost, security, and compliance rules before it's allowed to proceed

Tool calling

SGOrchestrator Workflows, executing the plan, applying changes, opening pull requests, and triggering webhooks on success, failure, or drift detection

Memory

Audit Logs, capturing every policy evaluation and platform action, exportable to JSON or CSV

The "tool calling" step has more going on underneath it than just "the workflow runs." Every Workflow specifies a Runtime Container, a Docker image that pinpoints the exact Terraform or OpenTofu version, CLI tools, and init scripts used for execution. That matters specifically for agentic remediation: a fix generated for a Terraform 1.5 codebase needs to run against Terraform 1.5, not whatever version happens to be on a shared runner, or the applied change and the declared code will silently diverge again.

Take the checkout service example from earlier and run it through StackGuardian's actual mechanics. Every workflow has an Automated Drift Check toggle configured to run on a schedule rather than waiting for someone to manually trigger a plan. When that hotfix-era security group was created eighteen months ago, a scheduled drift check against the connected AWS account would have surfaced it the same week, not eighteen months later during an incident. Drift runs are queued at lower priority than user-initiated runs, so they don't compete with active deployments for execution capacity, but they still run continuously in the background regardless of whether anyone is watching.

Cost sits inside the same loop, not as an afterthought. Take a developer self-provisioning a database through StackGuardian's Dev Portal for a new feature branch, nobody's watching that request, and it's easy to pick an oversized instance type out of habit or uncertainty about what the workload actually needs. A Policy Set that evaluates that plan against InfraCost data catches it before the workflow applies, either blocking the request outright or flagging it for approval, rather than the oversized instance quietly running for a month until someone notices the bill. That same signal rolls up into the Discover dashboards, providing separate Compliance, Cost, and Security views that continuously evaluate the connected cloud estate, so a platform team isn't just catching one oversized instance at plan time; they can see cost drift across every workflow in the organization from a single view instead of checking each one individually.

The practical effect is that a question like "which resources should get codified first" doesn't require opening three separate dashboards and manually correlating the results. SGCode's Cloud Inventory identifies what's unmanaged; the IaC Adoption Matrix tracks coverage as a measurable percentage across the estate; and Policy Sets flag what's already violating a compliance rule, giving the platform team a single ranked view instead of three disconnected lists.

That same underlying data is available outside the platform too, through StackGuardian's hosted MCP server, added in v1.31.4. It connects tools like Claude and ChatGPT directly to StackGuardian's read-only APIs, so a query like "why did workflow run #1247 fail" or "what's the current status of all stacks in my organization" run from inside an AI assistant pulls from the same drift, compliance, and execution data the platform itself uses. The same server handles more targeted questions too: "which workflows are still using template revision 2" surfaces exactly which deployments need updating before a rollout, and "assess the health of every workflow in this group before we ship" aggregates status across a whole Workflow Group instead of checking each one by hand. No dashboard-hopping required to get an answer either way.

The Governance Layer an Agentic System Needs Before Production

None of the automation above is safe to run unsupervised without a governance layer sitting in front of it. An AI agent with unrestricted Terraform access can run terraform destroy against production resources just as easily as it can fix a drifted tag, faster than any human could intervene. The capability to act autonomously and the judgment to know when not to are two separate things, and only one of them comes for free with a capable model.

StackGuardian's Policy Sets sit exactly at this boundary, evaluating every planned change through Tirith or OPA before anything applies. Each policy rule has two configurable outcomes, an action when the policy passes and an action when it errors, with five possible statuses: Pass, Fail, Warn, Approval Required, or Unevaluated. A violation can block the deployment outright, log a warning and proceed, or route to a named approver for exceptional cases, rather than defaulting to either full autonomy or full manual review for every single change. Policies scope at three levels: organization-wide, Workflow Group, or Connector, which is the practical version of a blast-radius limit: a policy governing a sandbox Workflow Group doesn't need, and shouldn't have, the same restrictions as one governing production.

Every action, whether it ran automatically or waited for approval, is logged in StackGuardian's Audit Logs, including what changed, who evaluated it, and the outcome, and can be exported to JSON or CSV. That audit trail is what turns "the platform did something" into an answerable question after the fact, instead of a black box nobody can reconstruct.

Why Trust Remains the Real Blocker

The technology to run an agentic loop exists today; the harder problem is convincing teams to let it act without a human double-checking every step. This gap between what's technically possible and what teams are willing to trust isn't irrational; it's the same reason approval gates for production Terraform apply in the first place. An engineer who wouldn't approve their own unreviewed pull request to production shouldn't be expected to trust an unreviewed AI-generated one either.

Terraform, OpenTofu, and similar tools remain the execution layer regardless of how much of the surrounding work becomes agentic. Nothing about this shift replaces terraform apply as the mechanism for provisioning infrastructure. What changes is the manual work that used to happen around that command, tracing dependencies, noticing drift, writing the fix, checking it against policy, all of which historically fell on an engineer to catch by hand. The trust gap closes as guardrails, approval gates, and audit trails mature, not as agents get better at generating code in isolation.

Conclusion: Where Should You Start With Agentic IaC?

Agentic IaC isn't a single feature to turn on. It's a combination of continuous visibility into what's actually running, a policy layer that evaluates changes before they apply, and an audit trail that makes every autonomous action reviewable after the fact. Teams evaluating this space should look for all three together rather than a chat interface bolted onto an existing IaC tool, since a system that can generate a fix but can't see live state, or can see live state but has no guardrails, isn't actually running the loop.

The fastest way to know where an environment stands is to check how much of it is genuinely unmanaged today, rather than assume the answer.

FAQs

What is agentic IaC?

Agentic IaC is infrastructure management in which an AI system continuously compares the live cloud state against declared infrastructure code, detects drift or policy gaps, and generates and applies fixes within defined guardrails, without requiring a human to notice the problem and manually trigger a fix.

What does "agentic" mean in AI?

An agentic AI system pursues a goal continuously rather than responding to a single prompt and stopping. It observes an environment, decides what needs to change, takes action, checks the result, and repeats the cycle on its own, compared to a standard tool that waits for input and produces output once.

Will AI agents replace Terraform?

No. Terraform, OpenTofu, and similar tools remain the execution layer through which agentic systems generate and apply changes. What AI changes is the manual investigation and remediation work that used to sit between the code and the live cloud, not the underlying IaC engine itself.

How does StackGuardian implement agentic IaC?

StackGuardian runs the observe-detect-plan-validate-apply-confirm loop across its own platform: SGCode's Cloud Inventory for continuous discovery, AI-powered codification for planning, Policy Sets (Tirith or OPA) for validation, SGOrchestrator Workflows for execution, and Audit Logs for the record of what happened. The same live data is exposed to external tools such as Claude and ChatGPT via StackGuardian's hosted MCP server.

Does StackGuardian's MCP integration work with Claude and ChatGPT?

Yes. StackGuardian's hosted MCP server, added in v1.31.4, connects AI tools directly to StackGuardian's read-only APIs, so a query like "show me drifted resources in production" or "which workflows are using an outdated template revision" returns real data from a connected organization instead of a guess based on local files.

What stops an AI agent from making a destructive change by mistake?

Policy Sets evaluate every planned change against cost, security, and compliance rules before it applies, and policies scoped to a Workflow Group or Connector can specifically restrict which resources an agent-driven workflow is allowed to touch. Combined with Approval Required gates for higher-risk changes and a full audit trail of every action in Audit Logs, this is what keeps autonomy bounded rather than open-ended.

Share article