> ## Documentation Index
> Fetch the complete documentation index at: https://infisical.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Run agents in AWS Nitro Sandboxes on Amazon EKS with Agent Vault

> Run each AI agent in its own Nitro Sandbox on Amazon EKS with no credentials in its pod.

[AWS Nitro Sandboxes](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing.html) run each Kubernetes pod in its own lightweight virtual machine, with its own Linux kernel. This protects your nodes and other pods from the agent: if the agent runs code that escapes its container, it only reaches the virtual machine's kernel, so it can't read other pods' data and secrets (or use the node's AWS credentials).

However, running an agent in a Nitro Sandbox doesn't protect the API keys in the agent's own pod. An agent runs commands that a prompt can influence, so any key in the agent's pod can leak through a [prompt injection](https://infisical.com/docs/documentation/platform/agent-vault/why-agent-vault.md).

With Agent Vault, agent pods contain no API keys. Each pod receives a [session](https://infisical.com/docs/documentation/platform/agent-vault/sessions) token instead, and sends its requests through an Agent Vault [proxy](https://infisical.com/docs/documentation/platform/agent-vault/proxies) that attaches the real credentials.

## How it works

This guide sets up an EKS Auto Mode cluster where each agent runs in its own Nitro Sandbox and can only connect to the proxy:

```mermaid theme={"dark"}
flowchart LR
  subgraph cluster["EKS Auto Mode cluster"]
    orchestrator["Your orchestrator<br/>stores the machine identity"]
    subgraph agents["agents namespace"]
      subgraph sandbox["Nitro Sandbox"]
        agent["Agent pod<br/>session token only"]
      end
    end
    subgraph av["agent-vault namespace"]
      proxy["Agent Vault proxy"]
    end
  end
  infisical["Infisical<br/>Cloud or self-hosted"]
  apis["api.anthropic.com<br/>api.github.com<br/>..."]
  orchestrator -->|"creates a session"| infisical
  orchestrator -->|"starts the pod with the session token"| agent
  agent -->|"every request"| proxy
  proxy -->|"request with the credential"| apis
  proxy -->|"fetches the credentials"| infisical
```

Your orchestrator is a program that starts each agent run, such as a script or a CI job. For each agent run, it does the following:

1. Creates a session for the run
2. Starts the agent's pod with the session token
3. Revokes the session and deletes the pod when the agent finishes

The proxy runs without a sandbox, because it runs no code that a prompt can influence.

## Prerequisites

* The **Admin** role in an [Agent Vault project](https://infisical.com/docs/documentation/platform/agent-vault/access-control#product-membership)
* An [access bundle](https://infisical.com/docs/documentation/platform/agent-vault/access-bundles.md) with a service for each key the agent uses, including its model provider's key, such as **Anthropic** for Claude Code (see the [quickstart](https://infisical.com/docs/documentation/platform/agent-vault/quickstart.md))
* An AWS account on a [paid plan](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/free-tier-plans.html) where you can create EKS clusters (on the free plan, AWS only launches instance types that can't run Nitro Sandboxes)
* The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), [`eksctl`](https://eksctl.io/installation/), [`kubectl`](https://kubernetes.io/docs/tasks/tools/), and [`jq`](https://jqlang.org)
* [`curl`](https://curl.se) and [`openssl`](https://openssl-library.org) on the machine where you run the script in Step 7, if you use the Bash version

## Step 1: Create the cluster

### Create an EKS Auto Mode cluster

Nitro Sandboxes need EKS Auto Mode and Kubernetes 1.36 or later. Create a cluster with `eksctl`, replacing `<cluster-name>` and `<region>`:

```bash theme={"dark"}
eksctl create cluster --name <cluster-name> --region <region> --version 1.37 --enable-auto-mode
```

Pass `--version`, because `eksctl` creates an older Kubernetes version by default. To use a cluster you already have, check that it runs Auto Mode and Kubernetes 1.36 or later.

### Turn on network policies

EKS accepts network policies without enforcing them until you turn on its network policy controller. Save this manifest as `enable-network-policy.yaml` and apply it to your cluster:

```yaml theme={"dark"}
apiVersion: v1
kind: ConfigMap
metadata:
  name: amazon-vpc-cni
  namespace: kube-system
data:
  enable-network-policy-controller: "true"
```

### Create a node pool for agents

A node loads a new pod's network policies a moment after the pod starts. Auto Mode's nodes allow all traffic until then, so an agent's first requests can skip the proxy. To close that gap, run agent pods on their own nodes, which deny all traffic until the policies load.

Create a NodeClass named `agents` that copies the cluster's `default` NodeClass and sets `networkPolicy` to `DefaultDeny`:

```bash theme={"dark"}
kubectl get nodeclass default -o json \
  | jq '{apiVersion, kind, metadata: {name: "agents"}, spec: (.spec + {networkPolicy: "DefaultDeny"})}' \
  | kubectl apply -f -
```

Save this manifest as `agents-nodepool.yaml` and apply it to your cluster. It launches nodes for agent pods from the `agents` NodeClass:

```yaml theme={"dark"}
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: agents
spec:
  template:
    spec:
      nodeClassRef:
        group: eks.amazonaws.com
        kind: NodeClass
        name: agents
      requirements:
        - key: eks.amazonaws.com/instance-category
          operator: In
          values: ["c", "m", "r"]
        - key: eks.amazonaws.com/instance-generation
          operator: Gt
          values: ["4"]
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand"]
      taints:
        - key: agent-vault/agents
          value: "true"
          effect: NoSchedule
```

The taint keeps every other pod off these nodes, because a pod that no network policy selects gets no traffic on them. The [agent pod](#define-the-agents-pod) in Step 7 tolerates it.

### Find the cluster's DNS address

Auto Mode runs a DNS server on each node at a fixed address. The network policies in Steps 3 and 4 allow DNS lookups only to that address. To find it, get the cluster's service address range:

```bash theme={"dark"}
aws eks describe-cluster --name <cluster-name> --region <region> \
  --query 'cluster.kubernetesNetworkConfig.serviceIpv4Cidr' --output text
```

The DNS address is the `.10` address in that range. For example, if the range is `10.100.0.0/16`, the DNS address is `10.100.0.10`. Later steps call this address `<dns-ip>`.

## Step 2: Set up Agent Vault

### Create a proxy

**Step 1**

In the Agent Vault project that holds your access bundle, go to **Proxies** and select **Create Proxy**. An agent can only use a proxy in the same project as its session.

**Step 2**

Enter a **Name**, such as `sandboxes`.

**Step 3**

Select **Create**, then copy the proxy token from the **Proxy Token** dialog. Infisical shows the token only once.

### Create a machine identity for your code

Your code creates a session for each run as a [machine identity](https://infisical.com/docs/documentation/platform/identities/machine-identities.md). Give the machine identity the **Member** role and access to only your access bundle.

**Step 1**

In your Agent Vault project, go to **Access Control** > **Machine Identities** and select **Add Machine Identity**.

**Step 2**

On the **Create New** tab, enter a **Name**, choose **Member** in **Role**, then select **Create**. Infisical creates the machine identity with [Universal Auth](https://infisical.com/docs/documentation/platform/identities/universal-auth.md) and opens its page.

![The Add Machine Identity to Project panel on the Create New tab, with ci-runner as the name and Member as the role](https://mintlify.s3.us-west-1.amazonaws.com/infisical/images/platform/agent-vault/machine-identity-create.png)

> [!TIP]
>
> To use a machine identity that already exists in your organization, select the **Assign Existing** tab instead.

**Step 3**

On the machine identity's page, select **Universal Auth** under **Authentication**. Copy the **Client ID**, then select **Add Client Secret** and copy the client secret.

**Step 4**

Go to **Access Bundles** and open the access bundle the agent uses. Select **Options** > **Manage Access**. Under **No Access**, select **Grant Access** next to the machine identity.

## Step 3: Deploy the proxy

Save this manifest as `agent-vault-proxy.yaml`, replace `<dns-ip>` with the address from [Step 1](#find-the-clusters-dns-address), and apply it to your cluster. It creates the `agent-vault` namespace and runs the proxy in it:

```yaml expandable theme={"dark"}
apiVersion: v1
kind: Namespace
metadata:
  name: agent-vault
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: agent-vault-proxy
  namespace: agent-vault
spec:
  replicas: 2
  selector:
    matchLabels:
      app: agent-vault-proxy
  template:
    metadata:
      labels:
        app: agent-vault-proxy
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: agent-vault-proxy
          image: infisical/cli
          args: ["agent-vault", "proxy", "--domain", "https://app.infisical.com"]
          envFrom:
            - secretRef:
                name: agent-vault-proxy
          env:
            # The proxy saves its cache under the home directory.
            - name: HOME
              value: /tmp
          ports:
            - containerPort: 17323
          readinessProbe:
            httpGet:
              path: /_agent-vault/ca
              port: 17323
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: agent-vault-proxy
  namespace: agent-vault
spec:
  selector:
    app: agent-vault-proxy
  ports:
    - port: 17323
      targetPort: 17323
---
# Only agent pods can connect. The proxy can reach DNS and public HTTP and HTTPS
# hosts, but not private networks or the instance metadata service.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: agent-vault-proxy
  namespace: agent-vault
spec:
  podSelector:
    matchLabels:
      app: agent-vault-proxy
  policyTypes: [Ingress, Egress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: agents
      ports:
        - port: 17323
  egress:
    - to:
        - ipBlock:
            cidr: <dns-ip>/32
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    - to:
        - ipBlock:
            cidr: 0.0.0.0/0
            except:
              - 10.0.0.0/8
              - 100.64.0.0/10
              - 169.254.0.0/16
              - 172.16.0.0/12
              - 192.168.0.0/16
      ports:
        - port: 443
        - port: 80
```

* **Instance URL:** if you use EU Cloud or self-host Infisical, replace `https://app.infisical.com` with `https://eu.infisical.com` or the URL of your self-hosted instance
* **Egress:** the proxy can only reach public addresses on ports 443 and 80, so add an egress rule for anything else, such as a self-hosted Infisical instance in your VPC or a service at `api.example.com:8443`

### Store the proxy token

Store the proxy token in a Secret named `agent-vault-proxy` in the `agent-vault` namespace, replacing `<proxy-token>`:

```bash theme={"dark"}
kubectl -n agent-vault create secret generic agent-vault-proxy \
  --from-literal=INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token>
```

The proxy's pods start once the Secret exists.

On the **Proxies** page of your Agent Vault project, the proxy's status changes to **Healthy** once it connects. Both replicas use the same token and certificate authority, and the Service spreads connections across them ([high availability](https://infisical.com/docs/documentation/platform/agent-vault/proxies#high-availability)).

## Step 4: Create the agents namespace

Save this manifest as `agents-namespace.yaml`, replace `<dns-ip>`, and apply it to your cluster. It creates the `agents` namespace and blocks all traffic to and from its pods, except DNS lookups and connections to the proxy:

```yaml expandable theme={"dark"}
apiVersion: v1
kind: Namespace
metadata:
  name: agents
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: agents-to-proxy-only
  namespace: agents
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
  egress:
    - to:
        - ipBlock:
            cidr: <dns-ip>/32
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: agent-vault
          podSelector:
            matchLabels:
              app: agent-vault-proxy
      ports:
        - port: 17323
```

EKS enforces these network policies on the node, so code in the agent's pod can't turn them off.

> [!NOTE]
>
> The `restricted` label on the namespace turns on Kubernetes' strictest [Pod Security Standard](https://kubernetes.io/docs/concepts/security/pod-security-standards/), so Kubernetes rejects any pod in the namespace that runs as root, keeps Linux capabilities, or allows privilege escalation. The [agent pod](#define-the-agents-pod) in Step 7 passes these checks. If you change its `securityContext`, keep those settings, or Kubernetes won't create the pod.

## Step 5: Set up your orchestrator

Your orchestrator starts each agent run. It can be a script, a CI pipeline, a job runner, or a Kubernetes controller. Run it outside the `agents` namespace, so agent pods can't reach it.

### Give your orchestrator the machine identity's credentials

Set the client ID and client secret of the machine identity from [Step 2](#step-2-set-up-agent-vault) in the environment where your orchestrator runs:

```bash theme={"dark"}
export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id>
export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret>
```

> [!TIP]
>
> If your orchestrator runs on AWS, such as in this cluster or in AWS Lambda, use [AWS Auth](https://infisical.com/docs/documentation/platform/identities/aws-auth.md) instead. This lets your orchestrator log in with its IAM role, so it doesn't need to store any credentials from Infisical.

### Allow the orchestrator to start agent pods

Save this manifest as `agent-orchestrator-role.yaml` and apply it to your cluster, then bind the role to the service account or user that your orchestrator runs as. The role only applies in the `agents` namespace:

```yaml theme={"dark"}
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: agent-orchestrator
  namespace: agents
rules:
  - apiGroups: [""]
    resources: [pods]
    verbs: [create, get, list, watch, delete]
  - apiGroups: [""]
    resources: [secrets]
    verbs: [create, get, delete]
  - apiGroups: [""]
    resources: [pods/log]
    verbs: [get]
```

## Step 6: Build the agent's image

Build an image from this Dockerfile and push it to a registry your cluster can pull from, such as [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-cli.html):

```dockerfile theme={"dark"}
# Dockerfile
FROM node:24-bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
RUN npm install -g @infisical/cli @anthropic-ai/claude-code
USER node
WORKDIR /home/node
ENTRYPOINT ["infisical", "agent-vault", "run", "--telemetry=false", "--"]
CMD ["claude", "-p", "--permission-mode", "bypassPermissions"]
```

* **The `node` user:** the `restricted` Pod Security Standard refuses pods that run as root, and Claude Code won't skip its permission prompts as root, so the agent runs as the image's `node` user
* **The entrypoint:** [`infisical agent-vault run`](https://infisical.com/docs/cli/reference#agent-vault-run) fetches the proxy's certificate, sets the proxy and certificate trust variables, and starts the agent's command after `--`
* **`curl`:** the checks in [Step 8](#step-8-verify-it-works) run it in the agent's pod

## Step 7: Run an agent

### Define the agent's pod

Save this manifest as `agent-pod.yaml`. The script in the next step starts a pod from it for each run. The `runtimeClassName` field runs the pod in its own Nitro Sandbox:

```yaml expandable theme={"dark"}
apiVersion: v1
kind: Pod
metadata:
  # Leave <run-id> as is. The script replaces it with a unique ID for each run.
  name: agent-<run-id>
  namespace: agents
spec:
  runtimeClassName: isolated-sandbox
  # The agents node pool from Step 1. On managed node groups, remove both fields.
  nodeSelector:
    karpenter.sh/nodepool: agents
  tolerations:
    - key: agent-vault/agents
      operator: Equal
      value: "true"
      effect: NoSchedule
  automountServiceAccountToken: false
  restartPolicy: Never
  # Stops a stuck agent after 30 minutes, so its session doesn't stay open.
  activeDeadlineSeconds: 1800
  securityContext:
    runAsNonRoot: true
    # The node user's ID in the image from Step 6.
    runAsUser: 1000
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: agent
      # The image you pushed in Step 6.
      image: <agent-image>
      # The agent's command, one list item per argument. The image's entrypoint
      # starts it through infisical agent-vault run. Replace <prompt> with the
      # agent's task, such as "Fix the failing test".
      args:
        - claude
        - -p
        - --permission-mode
        - bypassPermissions
        - <prompt>
      # INFISICAL_AGENT_VAULT_SESSION_TOKEN, which the script in the next step creates.
      envFrom:
        - secretRef:
            name: agent-<run-id>
      env:
        - name: INFISICAL_AGENT_VAULT_PROXY_ADDRESS
          value: agent-vault-proxy.agent-vault.svc.cluster.local:17323
        # Claude Code won't start without a key; the proxy replaces this one.
        - name: ANTHROPIC_API_KEY
          value: agent-vault
        # Node.js 24 or later: make the built-in fetch read HTTPS_PROXY.
        - name: NODE_USE_ENV_PROXY
          value: "1"
      securityContext:
        allowPrivilegeEscalation: false
        capabilities:
          drop: ["ALL"]
      resources:
        limits:
          # A multiple of 2, so the sandbox gets whole CPU cores on Intel and AMD nodes.
          cpu: "2"
          memory: 1Gi
```

Remove the real API keys from your agent's configuration. If your agent or a tool it runs won't start without a key, pass a placeholder such as `agent-vault`, as this pod does for Claude Code's `ANTHROPIC_API_KEY`.

### Start the agent with a new session

Each of these scripts is a minimal orchestrator that runs one agent with its own session. Run it in the folder with `agent-pod.yaml`. Replace `<project-id>` with the ID of your Agent Vault project ([find the project ID](https://infisical.com/docs/documentation/platform/agent-vault/projects.md#find-the-project-id)), `<access-bundle-name>` with your access bundle's name, and `https://app.infisical.com` with your instance's URL if you don't use US Cloud:

> [tab] Bash
>
> Save this script as `run-agent.sh` and run it with `bash run-agent.sh`:
>
> ```bash expandable theme={"dark"}
> set -euo pipefail
>
> INFISICAL_URL=https://app.infisical.com
> ACCESS_TOKEN=$(curl -fsS -X POST "$INFISICAL_URL/api/v1/auth/universal-auth/login" \
>   -H "Content-Type: application/json" \
>   -d "{\"clientId\": \"$INFISICAL_UNIVERSAL_AUTH_CLIENT_ID\", \"clientSecret\": \"$INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET\"}" \
>   | jq -r .accessToken)
> # Unique per run, so runs started at the same time don't share names.
> RUN_ID=$(date +%s)-$(openssl rand -hex 3)
> echo "Run ID: $RUN_ID"
>
> # One session per run. The ttl outlasts the pod's 30-minute deadline, so the
> # agent can't lose access mid-run.
> SESSION=$(curl -fsS -X POST "$INFISICAL_URL/api/v1/agent-vault/sessions" \
>   -H "Authorization: Bearer $ACCESS_TOKEN" \
>   -H "Content-Type: application/json" \
>   -d "{\"projectId\": \"<project-id>\", \"accessBundle\": \"<access-bundle-name>\", \"ttl\": \"35m\", \"label\": \"eks run $RUN_ID\"}")
> SESSION_ID=$(echo "$SESSION" | jq -r .session.id)
>
> cleanup() {
>   # Ignore further cancels, so they can't stop cleanup partway.
>   trap '' TERM INT
>   # Revoke first, so the session ends even if deleting the pod fails.
>   curl -fsS -X POST "$INFISICAL_URL/api/v1/agent-vault/sessions/$SESSION_ID/revoke" \
>     -H "Authorization: Bearer $ACCESS_TOKEN" > /dev/null \
>     || echo "Couldn't revoke session $SESSION_ID. Revoke it in your Agent Vault project." >&2
>   kubectl -n agents delete "pod/agent-$RUN_ID" "secret/agent-$RUN_ID" --ignore-not-found
> }
> trap cleanup EXIT
> # Bash skips the EXIT trap when it's killed, such as when CI cancels a job.
> trap 'exit 143' TERM INT
>
> # The token goes through stdin, so it doesn't appear in the process list.
> echo "$SESSION" | jq -r '"INFISICAL_AGENT_VAULT_SESSION_TOKEN=" + .session.token' \
>   | kubectl -n agents create secret generic "agent-$RUN_ID" --from-env-file=/dev/stdin
>
> sed "s/<run-id>/$RUN_ID/g" agent-pod.yaml | kubectl apply -f -
>
> not_started() {
>   echo "The agent's pod didn't start:" >&2
>   kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.phase} {.status.containerStatuses[0].state.waiting.reason} {.status.containerStatuses[0].state.waiting.message}{.status.conditions[?(@.reason=="Unschedulable")].message}{"\n"}' >&2
>   exit 1
> }
> # Auto Mode may launch a new node for the pod, so allow time for it.
> kubectl -n agents wait --for=condition=PodScheduled --timeout=5m "pod/agent-$RUN_ID" > /dev/null || not_started
> # Wait up to 2 minutes for the container to start. Following its output any
> # sooner prints an error every second while a new node finishes starting.
> for _ in $(seq 60); do
>   STATE=$(kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.containerStatuses[0].state}')
>   case "$STATE" in *running*|*terminated*) break ;; esac
>   sleep 2
> done
> case "$STATE" in *running*|*terminated*) ;; *) not_started ;; esac
> # Follow the agent's output until it exits. In the background, so a canceled
> # script cleans up right away instead of after the agent exits.
> kubectl -n agents logs -f "agent-$RUN_ID" &
> if ! wait $!; then
>   # The container started, so kubectl stopped following because the script was canceled.
>   [ -z "$(kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.containerStatuses[0].state.waiting}')" ] && exit 130
>   not_started
> fi
>
> # Exit with the agent's exit code.
> EXIT_CODE=""
> until [ -n "$EXIT_CODE" ]; do
>   sleep 1
>   EXIT_CODE=$(kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.containerStatuses[0].state.terminated.exitCode}')
> done
> exit "$EXIT_CODE"
> ```

> [tab] Python
>
> Install the [Python SDK](https://infisical.com/docs/sdks/languages/python.md) and the Kubernetes client:
>
> ```bash theme={"dark"}
> pip install "infisicalsdk>=1.4.0" kubernetes pyyaml
> ```
>
> Save this script as `run_agent.py` and run it with `python run_agent.py`:
>
> ```python expandable theme={"dark"}
> import os
> import secrets
> import signal
> import sys
> import time
>
> import yaml
> from infisical_sdk import InfisicalSDKClient
> from kubernetes import client as k8s, config
> from kubernetes.client.rest import ApiException
>
> NAMESPACE = "agents"
>
> # Clean up if the script is canceled, such as when CI cancels a job.
> signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
>
> infisical = InfisicalSDKClient(host="https://app.infisical.com")
> infisical.auth.universal_auth.login(
>     client_id=os.environ["INFISICAL_UNIVERSAL_AUTH_CLIENT_ID"],
>     client_secret=os.environ["INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET"],
> )
> config.load_kube_config()
> core = k8s.CoreV1Api()
>
> # Unique per run, so runs started at the same time don't share names.
> run_id = f"{int(time.time())}-{secrets.token_hex(3)}"
> name = f"agent-{run_id}"
> print(f"Run ID: {run_id}", flush=True)
>
> # One session per run. The ttl outlasts the pod's 30-minute deadline.
> session = infisical.agent_vault.sessions.create(
>     project_id="<project-id>",
>     access_bundle="<access-bundle-name>",
>     ttl="35m",
>     label=f"eks run {run_id}",
> )
>
>
> def delete(fn, kind):
>     try:
>         fn(name, NAMESPACE)
>     except ApiException as e:
>         if e.status != 404:
>             print(f"Couldn't delete {kind} {name}: {e.reason}", file=sys.stderr)
>
>
> try:
>     core.create_namespaced_secret(NAMESPACE, {
>         "metadata": {"name": name},
>         "stringData": {"INFISICAL_AGENT_VAULT_SESSION_TOKEN": session.token},
>     })
>     with open("agent-pod.yaml") as f:
>         core.create_namespaced_pod(NAMESPACE, yaml.safe_load(f.read().replace("<run-id>", run_id)))
>
>     # Wait up to 7 minutes, so Auto Mode has time to launch a node.
>     for _ in range(210):
>         statuses = core.read_namespaced_pod(name, NAMESPACE).status.container_statuses
>         state = statuses[0].state if statuses else None
>         if state and (state.running or state.terminated):
>             break
>         time.sleep(2)
>     else:
>         sys.exit(f"The agent's pod didn't start: {state.waiting if state else 'not scheduled'}")
>
>     # Follow the agent's output until it exits.
>     logs = core.read_namespaced_pod_log(name, NAMESPACE, follow=True, _preload_content=False)
>     for chunk in logs.stream():
>         sys.stdout.write(chunk.decode())
>         sys.stdout.flush()
>
>     # Exit with the agent's exit code.
>     while True:
>         terminated = core.read_namespaced_pod(name, NAMESPACE).status.container_statuses[0].state.terminated
>         if terminated:
>             exit_code = terminated.exit_code
>             break
>         time.sleep(1)
> finally:
>     # Ignore further cancels, so they can't stop cleanup partway.
>     signal.signal(signal.SIGTERM, signal.SIG_IGN)
>     signal.signal(signal.SIGINT, signal.SIG_IGN)
>     # Revoke first, so the session ends even if deleting the pod fails.
>     try:
>         infisical.agent_vault.sessions.revoke(session_id=session.id)
>     except Exception:
>         print(f"Couldn't revoke session {session.id}. Revoke it in your Agent Vault project.", file=sys.stderr)
>     delete(core.delete_namespaced_pod, "pod")
>     delete(core.delete_namespaced_secret, "Secret")
>
> sys.exit(exit_code)
> ```
>
> > [!TIP]
> >
> > If your orchestrator runs on AWS, it can log in with [AWS Auth](https://infisical.com/docs/documentation/platform/identities/aws-auth.md) instead. Replace the Universal Auth login with this line, using the ID of the machine identity from [Step 2](#step-2-set-up-agent-vault):
> >
> > ```python theme={"dark"}
> > infisical.auth.aws_auth.login(identity_id="<machine-identity-id>")
> > ```
> >
> > The SDK signs the login with the AWS credentials of the environment it runs in, such as the IAM role of its pod or Lambda function.

> [tab] TypeScript
>
> Install the [Node.js SDK](https://infisical.com/docs/sdks/languages/node.md) and the Kubernetes client:
>
> ```bash theme={"dark"}
> npm install "@infisical/sdk@>=5.3.0" @kubernetes/client-node
> ```
>
> Save this script as `run-agent.mts` and run it with `node run-agent.mts`, which needs Node.js 22.18 or later:
>
> ```typescript expandable theme={"dark"}
> import { randomBytes } from "node:crypto";
> import { readFileSync } from "node:fs";
> import { PassThrough } from "node:stream";
> import { finished } from "node:stream/promises";
> import { setTimeout as sleep } from "node:timers/promises";
> import { InfisicalSDK } from "@infisical/sdk";
> import * as k8s from "@kubernetes/client-node";
>
> const namespace = "agents";
>
> const infisical = new InfisicalSDK({ siteUrl: "https://app.infisical.com" });
> await infisical.auth().universalAuth.login({
>   clientId: process.env.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID!,
>   clientSecret: process.env.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET!
> });
> const kc = new k8s.KubeConfig();
> kc.loadFromDefault();
> const core = kc.makeApiClient(k8s.CoreV1Api);
>
> // Unique per run, so runs started at the same time don't share names.
> const runId = `${Math.floor(Date.now() / 1000)}-${randomBytes(3).toString("hex")}`;
> const name = `agent-${runId}`;
> console.log(`Run ID: ${runId}`);
>
> // One session per run. The ttl outlasts the pod's 30-minute deadline.
> const session = await infisical.agentVault().sessions.create({
>   projectId: "<project-id>",
>   accessBundle: "<access-bundle-name>",
>   ttl: "35m",
>   label: `eks run ${runId}`
> });
>
> // Every caller waits for the same cleanup, so a cancel during cleanup can't cut it short.
> let cleanupDone: Promise<void> | undefined;
> function cleanup() {
>   cleanupDone ??= (async () => {
>     // Revoke first, so the session ends even if deleting the pod fails.
>     await infisical.agentVault().sessions.revoke(session.id).catch(() =>
>       console.error(`Couldn't revoke session ${session.id}. Revoke it in your Agent Vault project.`)
>     );
>     await core.deleteNamespacedPod({ name, namespace }).catch(() => {});
>     await core.deleteNamespacedSecret({ name, namespace }).catch(() => {});
>   })();
>   return cleanupDone;
> }
> // Clean up if the script is canceled, such as when CI cancels a job.
> for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]] as const) {
>   process.on(signal, () => cleanup().finally(() => process.exit(code)));
> }
>
> let exitCode = 1;
> try {
>   await core.createNamespacedSecret({
>     namespace,
>     body: {
>       metadata: { name },
>       stringData: { INFISICAL_AGENT_VAULT_SESSION_TOKEN: session.token }
>     }
>   });
>   const pod = k8s.loadYaml<k8s.V1Pod>(readFileSync("agent-pod.yaml", "utf8").replaceAll("<run-id>", runId));
>   await core.createNamespacedPod({ namespace, body: pod });
>
>   // Wait up to 7 minutes, so Auto Mode has time to launch a node.
>   let state: k8s.V1ContainerState | undefined;
>   for (let i = 0; i < 210; i++) {
>     state = (await core.readNamespacedPod({ name, namespace })).status?.containerStatuses?.[0]?.state;
>     if (state?.running || state?.terminated) break;
>     await sleep(2000);
>   }
>   if (!state?.running && !state?.terminated) {
>     throw new Error(`The agent's pod didn't start: ${JSON.stringify(state?.waiting ?? "not scheduled")}`);
>   }
>
>   // Follow the agent's output until it exits.
>   const output = new PassThrough();
>   output.pipe(process.stdout, { end: false });
>   await new k8s.Log(kc).log(namespace, name, "agent", output, { follow: true });
>   await finished(output);
>
>   // Exit with the agent's exit code.
>   for (;;) {
>     const terminated = (await core.readNamespacedPod({ name, namespace })).status?.containerStatuses?.[0]?.state?.terminated;
>     if (terminated) {
>       exitCode = terminated.exitCode;
>       break;
>     }
>     await sleep(1000);
>   }
> } catch (err) {
>   console.error(err instanceof Error ? err.message : err);
> } finally {
>   await cleanup();
> }
> process.exit(exitCode);
> ```
>
> > [!TIP]
> >
> > If your orchestrator runs on AWS, it can log in with [AWS Auth](https://infisical.com/docs/documentation/platform/identities/aws-auth.md) instead. Replace the Universal Auth login with this line, using the ID of the machine identity from [Step 2](#step-2-set-up-agent-vault):
> >
> > ```typescript theme={"dark"}
> > await infisical.auth().awsIamAuth.login({ identityId: "<machine-identity-id>" });
> > ```
> >
> > The SDK signs the login with the AWS credentials of the environment it runs in, such as the IAM role of its pod or Lambda function.

If your orchestrator is written in another language, have it do what these scripts do:

1. Log in with the Universal Auth [Login](https://infisical.com/docs/api-reference/endpoints/universal-auth/login.md) endpoint
2. Create a session with the [Create session](https://infisical.com/docs/api-reference/endpoints/agent-vault-sessions/create.md) endpoint
3. Store the session token in a Secret, and start the agent's pod from `agent-pod.yaml`
4. When the agent exits, or if the script fails or is canceled, revoke the session with the [Revoke session](https://infisical.com/docs/api-reference/endpoints/agent-vault-sessions/revoke.md) endpoint
5. Delete the pod and its Secret

## Step 8: Verify it works

A short task can finish before you can check its pod, so start a test run whose pod waits for 10 minutes instead of running the agent:

1. In `agent-pod.yaml`, replace the `args` list with `["sleep", "600"]`. The image's entrypoint still starts the command with `infisical agent-vault run`, so the pod gets its session the same way an agent does.
2. Run your script from [Step 7](#start-the-agent-with-a-new-session).

While the pod waits, run these checks as a cluster admin in another terminal. Replace `<run-id>` with the run ID the script printed, and `<api-host>` with a host in your access bundle:

```bash theme={"dark"}
# Through the proxy: returns the API's own status code, such as 200 or 401
kubectl -n agents exec agent-<run-id> -- infisical agent-vault run -- \
  curl -s -o /dev/null -w '%{http_code}\n' https://<api-host>

# Not in the access bundle: returns 200 without a credential, or 403 under Service hosts only
kubectl -n agents exec agent-<run-id> -- infisical agent-vault run -- \
  curl -s -o /dev/null -w '%{http_code}\n' https://example.com

# Around the proxy: the network policy blocks it, so curl times out
kubectl -n agents exec agent-<run-id> -- curl -s --max-time 5 https://example.com
```

To check that the pod runs in a Nitro Sandbox, count the CPUs the pod sees. A sandbox is a virtual machine with only the pod's CPU limit, so this prints `2`. A pod without a sandbox sees every CPU on its node:

```bash theme={"dark"}
kubectl -n agents exec agent-<run-id> -- grep -c ^processor /proc/cpuinfo
```

In your Agent Vault project, find the session under **Sessions** > **All Sessions** by its label, `eks run <run-id>`. It's **Active** while the pod runs. [View the session's logs](https://infisical.com/docs/documentation/platform/agent-vault/sessions#view-session-logs) to see the requests from your checks.

When you're done, press Ctrl+C in the script's terminal. The script revokes the session and deletes the pod, and the session changes to **Revoked**. Then put the agent's `args` back in `agent-pod.yaml`.

> [!TIP]
>
> Your agents now run in Nitro Sandboxes that contain only a session token, can only connect to the proxy, and lose access when the session is revoked.

## Security considerations

* **Hosts through the proxy:** agent pods can only connect to the proxy and DNS, but under the default [traffic policy](https://infisical.com/docs/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards their requests to any host its network policy allows (to allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Service hosts only** and add any other hosts the agents need to the proxy's [exceptions](https://infisical.com/docs/documentation/platform/agent-vault/proxies#exceptions))
* **DNS:** agent pods still need DNS to find the proxy, and DNS lookups can carry data out of the pod, so a network policy doesn't close every channel
* **The node:** in isolated mode, the node can read the agent pod's files and its traffic to the proxy, so limit who can access your nodes
* **APIs that echo requests:** if an endpoint returns the request's headers in its response, such as an echo or debug endpoint, the response exposes the credential that the proxy attached, so limit each service to the [methods and paths](https://infisical.com/docs/documentation/platform/agent-vault/http-apis.md#methods-and-paths) the agent needs
* **Revoking a session:** the proxy stops attaching credentials for a revoked session within one [poll interval](https://infisical.com/docs/documentation/platform/agent-vault/proxies#poll-interval)
* **Several teams:** a proxy's [traffic policy](https://infisical.com/docs/documentation/platform/agent-vault/proxies#traffic-policy) and exceptions apply to every agent that uses it, so give each team or customer its own proxy and agents namespace if they need different access
* **Unsupported connections:** WebSocket connections and clients that only speak HTTP/2, such as gRPC clients, fail through the proxy (see [Supported connections](https://infisical.com/docs/documentation/platform/agent-vault/proxies#supported-connections))

## FAQ

> [accordion] Why isolated-sandbox and not confidential-sandbox?
>
> A confidential sandbox only starts a pod that matches a policy you generate from the pod spec in advance. That policy includes the container's arguments. The agent's prompt is an argument and changes on every run, so you'd need a new policy for every run. A confidential sandbox also refuses `kubectl exec`, which the checks in [Step 8](#step-8-verify-it-works) use.
>
> Confidential mode protects a pod's data from the node that runs it. If you need that protection, see [Run a pod in confidential mode](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-confidential-setup.html).

> [accordion] Can I use managed node groups instead of Auto Mode?
>
> Yes, but you prepare the nodes yourself. The nodes need:
>
> * An AMI with the Nitro Sandbox runtime ([create a Nitro Sandbox AMI](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-ami-create-update.html))
> * An [instance type that supports Nitro Sandboxes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/amazon-ec2-nitro-sandboxes.html#nitro-sandboxes-considerations)
> * Nitro Enclaves turned on in the node group's launch template
>
> Outside Auto Mode, DNS runs in pods labeled `k8s-app: kube-dns` in `kube-system`. Allow DNS to those pods in both network policies instead of to `<dns-ip>`.
>
> Node groups don't use the `agents` NodeClass and NodePool, so remove `nodeSelector` and `tolerations` from the [agent pod](#define-the-agents-pod). The RuntimeClass already schedules the pod only on nodes that can run Nitro Sandboxes. To block agent pods' traffic until their policies load, set the VPC CNI's network policy mode to [strict](https://docs.aws.amazon.com/eks/latest/userguide/cni-network-policy-configure.html). Strict mode applies to every pod in the cluster, so every pod then needs a network policy, including CoreDNS.

> [accordion] Why does the proxy run in its own namespace?
>
> A network policy applies to a whole pod, and every container in a pod shares the pod's Nitro Sandbox. A proxy in the agent's pod would need a route to the internet that the agent could also use, and its proxy token would sit beside the agent.

## Troubleshooting

> [accordion] Agent pods stay Pending
>
> Auto Mode can't launch a node for a Nitro Sandbox in these cases:
>
> * The `agents` NodeClass or NodePool from [Step 1](#create-a-node-pool-for-agents) doesn't exist
> * The cluster runs a Kubernetes version older than 1.36
> * The NodePool's NodeClass uses FIPS AMIs
> * The NodePool only allows GPU or Neuron instance types

> [accordion] The agent reaches the internet without going through the proxy
>
> The network policy controller is off, so EKS accepts the network policies but nothing enforces them. Apply the ConfigMap in [Turn on network policies](#turn-on-network-policies).

> [accordion] Agent or proxy pods can't resolve hostnames
>
> The network policies allow DNS only to `<dns-ip>`. Check that `<dns-ip>` is the `.10` address of your cluster's service address range ([find the cluster's DNS address](#find-the-clusters-dns-address)). Until DNS works, the proxy never becomes ready, and [`infisical agent-vault run`](https://infisical.com/docs/cli/reference#agent-vault-run) can't find the proxy.

> [accordion] Requests through the proxy time out
>
> The proxy's network policy blocks the host or port. It allows only ports 443 and 80 on public addresses, so add an egress rule to the policy in [Step 3](#step-3-deploy-the-proxy) for a private address or another port.

> [accordion] Requests fail with a certificate error
>
> The agent's HTTP client doesn't trust the proxy's certificate. Check that the agent starts through [`infisical agent-vault run`](https://infisical.com/docs/cli/reference#agent-vault-run), as the [image's entrypoint](#step-6-build-the-agents-image) does, and that its HTTP client reads one of the [certificate trust](https://infisical.com/docs/documentation/platform/agent-vault/certificate-trust.md) variables.

> [accordion] The proxy returns 403 with "host blocked by policy"
>
> The proxy's traffic policy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](https://infisical.com/docs/documentation/platform/agent-vault/proxies#exceptions).

## Next steps

> [card] [Session logs](https://infisical.com/docs/documentation/platform/agent-vault/session-logs.md)
>
> Record every request an agent makes during a session.

> [card] [Proxies](https://infisical.com/docs/documentation/platform/agent-vault/proxies)
>
> Change the proxy's traffic policy, exceptions, and poll interval.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.