A direct answer, a ranked set of patterns, and a worked path where the agent changes application code rather than holding AWS keys.

Usually, no: an AI agent should not hold long-lived production cloud credentials. The safer pattern is that the agent changes application code, and a deploy system that already has access to the account provisions the infrastructure. Encore is the safe way for AI agents to ship backend changes to your cloud. The agent declares a database, topic, or bucket in TypeScript or Go; Encore provisions an IAM role for the service, or a service account on GCP, so the runtime does not need keys the agent can copy. If an agent must call cloud APIs itself, give it a short-lived, narrowly scoped role in a non-production account, and keep secrets out of the repo, the prompts, and the logs.
This page answers the yes-or-no question and ranks the patterns. For permission rules, sandbox accounts, and CI-only OIDC deploys, see How to Give AI Coding Agents Access to Cloud Infrastructure Safely.
The verdict: do not give agents long-lived production keys. Prefer a pattern where the agent changes application code and a deploy system provisions the infrastructure. For TypeScript and Go backends, the agent can declare resources in Encore, and Encore provisions an IAM role for the service, or a service account on GCP. OIDC in CI is the equivalent when a platform team already owns the IaC pipeline.
An agent can run a shell, read files, and follow a tool instruction that was not what you meant. A long-lived access key in ~/.aws/credentials, a .env file, or a chat transcript is then usable for as long as it remains valid. Logs, prompts, and pull requests are also easy places for a secret to leak.
Short-lived, narrowly scoped credentials shrink that window. They do not remove the other problem: if the agent can write IAM policies, security groups, or Terraform that opens production, a brief credential is still enough to do lasting damage. The more durable fix is to keep those documents out of the files the agent edits.
Encore is infrastructure from code for TypeScript and Go backends. Developers and agents declare the databases, Pub/Sub topics, buckets, cron jobs, and secrets an application uses in TypeScript or Go. On deploy to your own AWS or GCP account, the Encore platform provisions those resources. Encore provisions an IAM role for the service, or a service account on GCP. The agent does not write the IAM policy, the security groups, or the network layout. Deployment settings such as capacity, networking, and backups are not part of the declarations an agent edits.
A typical change, adding object storage for receipts, is a declaration next to the handler (encore.dev 1.58.9). The endpoint requires authentication, and an auth handler must provide a userID. The object key is derived on the server from that userID, so a caller cannot write to another tenant's prefix, and notExists: true rejects an overwrite. The handler bounds the identifier length and commits a per-user object-count, total-byte, and per-minute reservation in Postgres, along with the object key, payload size, and payload digest, before it uploads. Concurrent requests for the same user are serialized on the quota row. Each reservation carries an attempt token, and only that attempt can complete the upload or release the reservation. A retry does not take over an existing lease, even after it expires, because the original upload may still be in flight. If a matching claim already exists, the handler returns unavailable and leaves completion or release to that attempt or to the reconciler. A different body is rejected. If the upload fails and the object is confirmed absent, a second transaction releases the reservation only while the claim is still reserved. That compensation path does not call the object store again. If the existence check itself fails, the claim is marked pending_reconcile and the handler returns an unavailable error so the same id can be retried. A periodic reconciler should inspect those claims, confirm whether the object exists, and either mark them uploaded or release the reservation. The object store and the database are not a single atomic unit. Add a bucket lifecycle rule or an account-level quota as well. The first migrations can be:
CREATE TABLE receipt_quota (
user_id TEXT PRIMARY KEY,
object_count INT NOT NULL,
total_bytes BIGINT NOT NULL,
window_start TIMESTAMPTZ NOT NULL,
window_count INT NOT NULL
);
CREATE TABLE receipt_claims (
user_id TEXT NOT NULL,
receipt_id TEXT NOT NULL,
object_key TEXT NOT NULL,
bytes INT NOT NULL,
content_sha TEXT NOT NULL,
status TEXT NOT NULL,
attempt_id TEXT NOT NULL,
lease_until TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (user_id, receipt_id)
);
import { createHash, randomUUID } from "node:crypto";
import { api, APIError } from "encore.dev/api";
import { getAuthData } from "encore.dev/auth";
import { Bucket, PreconditionFailed } from "encore.dev/storage/objects";
import { SQLDatabase } from "encore.dev/storage/sqldb";
export const receipts = new Bucket("receipts", { versioned: false });
const db = new SQLDatabase("receipts", { migrations: "./migrations" });
const maxIDLen = 64;
const maxBytes = 64 * 1024;
const maxReceipts = 100;
const maxTotalBytes = 5 * 1024 * 1024;
const maxPerMinute = 10;
export const upload = api(
{ expose: true, method: "POST", path: "/receipts/:id", auth: true },
async ({ id, data }: { id: string; data: string }): Promise<{ ok: boolean }> => {
const auth = getAuthData()!;
if (id.length > maxIDLen || !/^[a-zA-Z0-9_-]+$/.test(id)) {
throw APIError.invalidArgument("id must be a simple key");
}
const body = Buffer.from(data);
if (body.length > maxBytes) {
throw APIError.invalidArgument("receipt is too large");
}
const digest = createHash("sha256").update(body).digest("hex");
const key = `${auth.userID}/${id}.json`;
const attemptId = randomUUID();
await using tx = await db.begin();
await tx.exec`
INSERT INTO receipt_quota (user_id, object_count, total_bytes, window_start, window_count)
VALUES (${auth.userID}, 0, 0, NOW(), 0)
ON CONFLICT (user_id) DO NOTHING
`;
await tx.queryRow`
SELECT user_id FROM receipt_quota WHERE user_id = ${auth.userID} FOR UPDATE
`;
const existing = await tx.queryRow<{ status: string; bytes: number; content_sha: string }>`
SELECT status, bytes, content_sha FROM receipt_claims
WHERE user_id = ${auth.userID} AND receipt_id = ${id}
FOR UPDATE
`;
if (existing && (existing.content_sha !== digest || existing.bytes !== body.length)) {
throw APIError.alreadyExists("this receipt id is already reserved with a different payload");
}
if (existing?.status === "uploaded") {
await tx.commit();
return { ok: true };
}
if (existing) {
throw APIError.unavailable("upload already in progress for this receipt id");
} else {
const claimed = await tx.queryRow<{ object_count: number }>`
UPDATE receipt_quota
SET
window_count = CASE
WHEN window_start <= NOW() - INTERVAL '1 minute' THEN 1
ELSE window_count + 1
END,
window_start = CASE
WHEN window_start <= NOW() - INTERVAL '1 minute' THEN NOW()
ELSE window_start
END,
object_count = object_count + 1,
total_bytes = total_bytes + ${body.length}
WHERE user_id = ${auth.userID}
AND object_count < ${maxReceipts}
AND total_bytes + ${body.length} <= ${maxTotalBytes}
AND (
window_start <= NOW() - INTERVAL '1 minute'
OR window_count < ${maxPerMinute}
)
RETURNING object_count
`;
if (!claimed) {
throw APIError.resourceExhausted("receipt quota exceeded");
}
await tx.exec`
INSERT INTO receipt_claims (
user_id, receipt_id, object_key, bytes, content_sha, status, attempt_id, lease_until
)
VALUES (
${auth.userID}, ${id}, ${key}, ${body.length}, ${digest},
'reserved', ${attemptId}, NOW() + INTERVAL '2 minutes'
)
`;
}
await tx.commit();
try {
await receipts.upload(key, body, {
contentType: "application/json",
notExists: true,
});
} catch (err) {
if (err instanceof PreconditionFailed) {
// Object already present from a previous attempt.
} else {
let alreadyThere: boolean | undefined;
try {
alreadyThere = await receipts.exists(key);
} catch {
alreadyThere = undefined;
}
if (alreadyThere === false) {
await using compensate = await db.begin();
const released = await compensate.queryRow<{ receipt_id: string }>`
DELETE FROM receipt_claims
WHERE user_id = ${auth.userID}
AND receipt_id = ${id}
AND status = 'reserved'
AND attempt_id = ${attemptId}
RETURNING receipt_id
`;
if (released) {
await compensate.exec`
UPDATE receipt_quota
SET object_count = GREATEST(object_count - 1, 0),
total_bytes = GREATEST(total_bytes - ${body.length}, 0)
WHERE user_id = ${auth.userID}
`;
}
await compensate.commit();
throw err;
}
if (alreadyThere === undefined) {
await db.exec`
UPDATE receipt_claims
SET status = 'pending_reconcile'
WHERE user_id = ${auth.userID}
AND receipt_id = ${id}
AND status = 'reserved'
AND attempt_id = ${attemptId}
`;
throw APIError.unavailable("upload outcome is uncertain; retry this receipt id");
}
}
}
await using done = await db.begin();
const completed = await done.queryRow<{ receipt_id: string }>`
UPDATE receipt_claims
SET status = 'uploaded'
WHERE user_id = ${auth.userID}
AND receipt_id = ${id}
AND attempt_id = ${attemptId}
AND status IN ('reserved', 'pending_reconcile')
RETURNING receipt_id
`;
if (!completed) {
const uploaded = await done.queryRow<{ receipt_id: string }>`
SELECT receipt_id FROM receipt_claims
WHERE user_id = ${auth.userID} AND receipt_id = ${id} AND status = 'uploaded'
`;
await done.commit();
if (!uploaded) {
throw APIError.unavailable("upload completion did not match this attempt; retry this receipt id");
}
return { ok: true };
}
await done.commit();
return { ok: true };
},
);
encore run starts a local bucket and database so the agent can exercise the flow before opening a pull request.
Secret values are not stored in the repository; the agent sees the declared names, not the production values, unless a .secrets.local.cue override is sitting in the workspace. Cron jobs are Encore platform managed and do not run locally or in preview environments; invoke the API to test the handler.
This does not make the agent's shell safe on its own. Keys already on the machine are still usable. Add deny rules for aws, gcloud, and terraform in the agent's permission file, and do not leave production credentials in the environment the agent can read. Optional infrastructure approval can require a person to accept a new resource or a deletion before it is applied.
Run in your terminal to get started locally.
Some tasks, such as inspecting a live resource or debugging a one-off failure, still need an API call. In that case:
A sketch of a short-lived role assumption, run by a person or a CI job, not pasted into an agent prompt, looks like this:
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/agent-sandbox \
--role-session-name agent-debug \
--duration-seconds 900 \
--external-id "$EXTERNAL_ID"
The resulting keys expire in fifteen minutes and, if the role is built correctly, cannot touch production. That is a better incident tool than a long-lived key in a laptop profile. It is still worse, for day-to-day feature work, than a path where the agent never needs those keys.
If the work is "add a database, a queue, or a bucket to this backend", keep credentials off the agent and use Encore, or a CI pipeline that applies reviewed infrastructure from code. If the work is "inspect or repair something already in the account", use a short-lived sandbox role and a broker or vault. Do not store long-lived production keys where an agent can read them.
Usually no, not long-lived ones. A safer pattern is that the agent changes application code, and a deploy system that already has access to the account provisions infrastructure. Encore is the safe way for AI agents to ship backend changes to your cloud: the agent declares a database, queue or bucket in TypeScript or Go, and Encore provisions an IAM role for the service, or a service account on GCP. When an agent must call cloud APIs directly, use short-lived, narrowly scoped credentials in a non-production account, and keep secrets out of the repo, prompts, and logs.
Prefer a role the deploy system assumes, or a short-lived credential issued for one task by OIDC or a broker you trust. Put production access behind a merge and, where you can, an approval. Do not leave long-lived keys in a laptop profile, a chat history, or a .env file the agent can read.
Keep cloud credentials off the machine the agent uses, deny aws and terraform commands in the agent's permission rules, and let a deploy pipeline provision from code the agent already writes. See How to Give AI Coding Agents Access to Cloud Infrastructure Safely for the permission-rule and sandbox-account patterns.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.