AI agent security for cloud infrastructure comes down to one rule: the controls live outside the model. An AI coding agent working on Terraform or a cloud account should be able to do what you would let a new engineer do in week one: read, write code, run checks, and propose changes. Seven controls get you there: short-lived credentials scoped to each agent, a separate agent identity in your logs, a pre-command hook that blocks destructive commands, policy checks on agent-written code, plan review and approval before apply, budget limits, and a record of what each agent tried. Add a few rules for MCP servers and you have a setup a security lead can sign off on.
Instructions in a prompt do not hold under pressure. On 26 February 2026, an AI coding agent cleaning up duplicate resources for a course platform swapped in an older Terraform state file and ran terraform destroy. That removed the production VPC, RDS database, ECS cluster, load balancers, and bastion host, along with the automated database snapshots. AWS Support restored a snapshot exactly 24 hours later. Developers already expect output like this to need checking: in Stack Overflow's 2025 Developer Survey, 45.7% of respondents said they distrust the accuracy of AI tool output and 3.1% said they highly trust it, while 81.4% agreed they have concerns about data security and privacy when using AI agents.
Why Agents Need Their Own Controls
OWASP's Top 10 for LLM Applications names the risk LLM06:2025 Excessive Agency, "the vulnerability that enables damaging actions to be performed." It lists three root causes: tools the system does not need, permissions wider than the task, and high-impact actions that run with no independent check or approval. Each control below removes one of those causes.
None of this slows the engineers who brought agents in. They are usually the first to ask for guardrails, because a guardrail is what lets them hand the agent bigger jobs without watching every keystroke.
1. Short-Lived, Scoped Credentials for Every Agent
Never give an agent long-lived access keys from a credentials file. AWS's IAM best practices say to require workloads to use temporary credentials with IAM roles, and an agent session is a workload. Create a role for agent sessions with read access to resources and the state backend, enough to run terraform plan. In production accounts, deny delete actions and IAM writes to that role with a service control policy, so a bad command fails at the API.
aws sts assume-role \
--role-arn arn:aws:iam::111122223333:role/agent-plan-readonly \
--role-session-name agent-priya-pr842 \
--duration-seconds 3600
The credentials expire after an hour. If they leak into a log or a transcript, they stop working soon after, and they never could delete production in the first place.
2. A Separate Identity So Logs Show Human vs Agent
When an agent uses an engineer's own credentials, every API call looks like the engineer made it. A separate identity fixes the audit trail. The role session name above appears in the assumed-role ARN that CloudTrail records, so a search for sessions starting with agent- lists every call an agent made, and the rest of the name ties it to a person and a pull request. Do the same in Git: agent commits carry a bot author or a commit trailer, so reviewers know which lines a person wrote.
3. A Pre-Command Hook That Blocks Destructive Commands
Coding agents that support hooks run a script before every shell command. The script reads the command the agent is about to run and refuses it before it starts. A minimal version:
#!/bin/sh
# Pre-command hook: the agent passes the proposed command on stdin.
# A non-zero exit blocks it (the exact code depends on the agent).
cmd="$(cat)"
case "$cmd" in
*"terraform destroy"*|*"tofu destroy"*|*"plan -destroy"*|*"state rm"*)
echo "Blocked: destructive command, ask a person to run it" >&2
exit 2 ;;
esac
exit 0
A pattern list only catches what it names, so treat the hook as the first layer and the credentials from control 1 as the backstop. Give people an explicit way to tear down a sandbox on purpose, so nobody switches the hook off. The full set of destroy safeguards is in How to Stop a Coding Agent From Running terraform destroy.
4. Policy Checks on Agent-Written Code Before a Human Reviews
Agents write plausible Terraform that misses your house rules: a bucket without encryption, a security group open to 0.0.0.0/0 on port 22, a resource with no Owner tag. Run validate, lint, a security scan, and your own policies at the end of every agent turn, and send failures back to the agent to fix. By the time a reviewer opens the pull request, the mechanical problems are gone and the review is about design. For checks that need real values, evaluate the plan instead of the source: terraform plan -out=tfplan followed by terraform show -json tfplan > plan.json gives a policy engine the exact changes.
5. The Agent Writes, the Pipeline Applies
Production applies should never run from an agent session. The agent opens a pull request. A pipeline with its own identity runs the plan, a person reads it, and a second person approves before the same pipeline applies it. That second person is separation of duties: the person who starts a change cannot be the one who approves it, so no single person, and no single agent session, can push a change to production alone. This matches OWASP's mitigation for excessive agency: require a human to approve high-impact actions before they are taken.
6. Budget Limits on Agent Changes
Agents often fix a failing test or a slow query by adding capacity: a larger database instance class, provisioned IOPS, a NAT gateway in every availability zone. Each change is reasonable on its own and expensive in total. Price every plan before it merges, compare the monthly delta with the project's budget, and fail the check when it crosses the limit. The agent then has to propose a cheaper design or a person has to accept the cost on the record.
7. A Record of What Agents Tried
Deployment logs show what was applied. The more useful record is what agents attempted and were stopped from doing: the blocked command and the pattern it matched, the failed policy with its file and line, the budget overrun, and the person whose session it was. Review it weekly. The rules agents break most often belong in the agent's instructions and your shared standards, which cuts the same mistakes across every repository.
MCP: The Risks That Come With Agent Tools
MCP, the Model Context Protocol, is an open standard that lets an AI agent call outside tools and data, such as a cloud API, a ticket system, or a policy service, through small connectors called MCP servers. It is how most agents reach beyond the repository, and it brings three risks.
- Tool permissions. An MCP server acts with whatever credentials it holds. A server that wraps a cloud API with admin keys gives the agent admin rights, whatever role you set in control 1. Give each server its own narrow credentials, prefer read-only tools, and turn off write tools nobody needs. The MCP security guidance warns that broad scopes widen the damage when a token leaks.
- Untrusted servers. A local MCP server is a program that runs on the engineer's laptop with the same privileges as the agent. The MCP security guidance lists arbitrary code execution and data exfiltration as risks of servers from untrusted sources. Keep an allowlist of approved servers, pin their versions, and read the startup command before anyone adds one.
- Prompt injection through documents. Prompt injection is text that an agent reads as instructions when it should treat it as data. OWASP ranks it LLM01:2025 and notes that indirect injections come from external sources such as websites or files. For infrastructure, that can be a module README, a ticket, or a comment in a Terraform file that says to run a cleanup command. You cannot filter every document an agent reads, which is why controls 1, 3, and 5 decide what an agent can do whatever it has read.
The 7 Controls at a Glance
| Control | What it stops | Where it lives |
|---|---|---|
| Short-lived, scoped credentials | Leaked keys, deletes in production | Cloud IAM and service control policies |
| Separate agent identity | "Who made this change?" gaps | Role session names, Git authorship |
| Pre-command hook | Destroy commands before they start | Agent configuration |
| Policy checks on agent code | Insecure or untagged code reaching review | End of each agent turn, CI |
| Plan review and approval | Unreviewed applies to production | Deployment pipeline |
| Budget limits | Cost jumps hidden inside a plan | Plan stage |
| Activity record | Repeated mistakes nobody sees | Central log |
How ops0 Puts These Controls in Place
The ops0 CLI is open source under Apache 2.0 and sets up the agent-side controls in one step. Run it once in a Terraform or OpenTofu repository:
ops0 login # paste an API key from ops0 settings
ops0 init
ops0 init adds a governance block to the agent's instructions, a validation hook at the end of every agent turn, a pre-command hook that blocks destroy, and the ops0 MCP server. It works with any MCP-capable coding agent, and your organization's rules apply by default, with no project setup.
- Checks every change the agent writes. At the end of each turn, ops0 runs validate, lint, your policies and security rules, a cost estimate, and the project budget. Failures go back to the agent to fix before anyone reviews. Files are sent over HTTPS for validation and are not stored.
- Blocks destroy before it runs.
terraform destroy,tofu destroy,oxid destroy, andplan -destroyare stopped by the pre-command hook, and each attempt is recorded.
- Serves your rules over MCP. The agent calls
list_policies,check_compliance(policies against a plan),get_finding_details, andget_iac_standards(required tags, README sections, when docs and runbooks are needed) while it writes, so it learns the rules before the check runs.
- Records what agents tried. Every failed check and blocked command is kept with the rule and the file and line it hit, plus the resource and the user. The insights view ranks the top 10 rules agents break over 24 hours, 7 days, or 30 days.
Applies run through ops0's governed deployments. Each deploy gets a plan, a policy check against the real plan that stops the run on errors and warnings with nothing applied, a cost and budget check, and an approval step. With separation of duties on, the person who starts a deployment cannot approve it. Kiwi, ops0's AI assistant, never changes infrastructure on its own: every change it proposes is one a person approves, and it goes through the same deployment gates. See AI agent guardrails for the agent side and Security for how findings across your clouds turn into fixes and guardrails.
For the policy side, see the docs on enforcing security policies and approval workflows.
What is AI agent security?
AI agent security is the set of controls that limit what an AI agent can do with the tools and credentials it is given. For cloud infrastructure, that means scoped short-lived credentials, a separate agent identity, hooks that block destructive commands, policy checks on agent-written code, human approval before apply, budget limits, and a record of what agents tried.
What are AI agent guardrails?
Guardrails are checks that run outside the agent and stop unsafe actions regardless of what the agent decides. Common examples for infrastructure are a pre-command hook that refuses terraform destroy, policy checks that fail insecure or untagged Terraform, a budget check on the plan, and an approval step before anything reaches production.
What is prompt injection, and why does it matter for infrastructure agents?
Prompt injection is text that an agent reads as instructions when it should treat it as data. OWASP ranks it first in its 2025 Top 10 for LLM Applications. An infrastructure agent reads READMEs and tickets all day, so a planted line can ask it to run a destructive command. Scoped credentials, command hooks, and approval before apply limit what an injected instruction can do.
Should AI coding agents have production cloud credentials?
Not for applying changes. Give agents short-lived read and plan access, deny delete actions in production accounts, and let a pipeline with its own identity apply changes after a person reviews the plan and a second person approves it.
How do I see what AI coding agents did in our cloud accounts?
Give agents their own role session names so CloudTrail shows which calls came from an agent, and keep a central record of blocked commands and failed checks. The ops0 CLI records every failed check and blocked destroy with the rule and the user, and ranks the most common mistakes over 24 hours, 7 days, or 30 days.
- How I Dropped Our Production Database and Now Pay 10% More for AWS: Alexey Grigorev. The February 2026 terraform destroy incident and its recovery timeline.
- LLM06:2025 Excessive Agency: OWASP GenAI Security Project. Root causes of damaging agent actions and the human-approval mitigation.
- LLM01:2025 Prompt Injection: OWASP GenAI Security Project. Direct and indirect prompt injection.
- 2025 Developer Survey: AI: Stack Overflow. Developer trust in AI output accuracy and concerns about AI agents.
- Security Best Practices: Model Context Protocol. Local MCP server risks and scope minimization.
- Security best practices in IAM: AWS. Temporary credentials with IAM roles and least privilege.