Amazon S3 Files を VPC 外のエージェント(AgentCore Runtime と Lambda MicroVMs)からマウントしてみた

Amazon S3 Files を VPC 外のエージェント(AgentCore Runtime と Lambda MicroVMs)からマウントしてみた

今回のアップデートで追加された S3 Files Endpoints を使い、VPC に接続しない AgentCore Runtime と Lambda MicroVMs から、東京リージョンで S3 Files をマウントして読み書きできました。書き込んだファイルは S3 でも確認できました。
2026.11.30

はじめに

2026年11月29日に、VPC 外で動く AgentCore Runtime と Lambda MicroVMs から、Amazon S3 Files のファイルシステムをマウントできるようになるアップデートがありました。

https://aws.amazon.com/jp/about-aws/whats-new/2026/11/amazon-s3-files-mount-agents-outside-vpc/

この記事では、AgentCore Runtime と Lambda MicroVMs を VPC にアタッチせずに作成し、Amazon S3 Files のファイルシステムをマウントして読み書きできることを確認した結果を紹介します。

検証環境

  • リージョン:東京(ap-northeast-1)
  • aws-cli:2.42.6
  • AgentCore Runtime:PYTHON_3_13(S3 の zip からコードをデプロイ)
  • Lambda MicroVMs のベースイメージ:al2023-1(バージョン 4.2)、ARM_64
  • amazon-efs-utils:4.0.0(ソースからビルドした RPM を Lambda MicroVMs のイメージに追加)

VPC 外から接続するための IAM 権限

S3 Files には、VPC のマウントターゲットに接続する経路に加えて、今回のアップデートで VPC 外から接続する S3 Files Endpoints の経路が追加されました。

Endpoints の利用には、次の IAM 権限が必要です。

  • s3files:CreateMountSession
  • 使うクライアント操作(今回は ClientMount と ClientWrite)の、s3files: と s3files-endpoint: の両方のアクション

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-files-networking-endpoint-permissions.html

今回は、AgentCore Runtime のロールと MicroVM の実行ロールの両方に、次のポリシーを付与しました。

付与したポリシーと付与手順(compute-s3files-policy.json)

3つ目の Statement の s3files:GetAccessPoint は、AgentCore Runtime の作成時にアクセスポイントを検証するために必要です。

compute-s3files-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "MountSession",
      "Effect": "Allow",
      "Action": ["s3files:CreateMountSession"],
      "Resource": "arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0"
    },
    {
      "Sid": "MountAndWriteViaVpcAndEndpoint",
      "Effect": "Allow",
      "Action": [
        "s3files:ClientMount",
        "s3files:ClientWrite",
        "s3files-endpoint:ClientMount",
        "s3files-endpoint:ClientWrite"
      ],
      "Resource": "arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0",
      "Condition": {
        "StringEquals": {
          "s3files:AccessPointArn": "arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0/access-point/fsap-0123456789abcdef0"
        }
      }
    },
    {
      "Sid": "ValidateAccessPoint",
      "Effect": "Allow",
      "Action": ["s3files:GetAccessPoint"],
      "Resource": [
        "arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0",
        "arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0/access-point/fsap-0123456789abcdef0"
      ]
    }
  ]
}

上のポリシーを compute-s3files-policy.json として保存し、各ロールに付与します。

aws iam put-role-policy \
  --role-name <ロール名> \
  --policy-name s3files-mount \
  --policy-document file://compute-s3files-policy.json

S3 Files のファイルシステムとアクセスポイント

バケットを元にファイルシステムを作成し、アクセスポイントも作成しました。

aws s3files create-file-system \
  --bucket arn:aws:s3:::amzn-s3-demo-bucket \
  --prefix agent-data/ \
  --role-arn arn:aws:iam::111122223333:role/s3f-outvpc-fs-role

aws s3files create-access-point \
  --file-system-id fs-0123456789abcdef0 \
  --posix-user uid=1000,gid=1000 \
  --root-directory 'path=/agent,creationPermissions={ownerUid=1000,ownerGid=1000,permissions=755}'

ファイルシステムのプレフィックスが agent-data/、アクセスポイントのルートが /agent です。そのため、マウント先に置いたファイルは S3 ではキー agent-data/agent/ の下に保存されます。

AgentCore Runtime から読み書きする

Runtime の作成

networkMode を PUBLIC にして、--filesystem-configurations にアクセスポイントとマウントパスを渡して作成しました。

aws bedrock-agentcore-control create-agent-runtime \
  --agent-runtime-name s3f_outvpc_agent \
  --agent-runtime-artifact '{"codeConfiguration":{"code":{"s3":{"bucket":"amzn-s3-demo-bucket","prefix":"code/agent.zip"}},"runtime":"PYTHON_3_13","entryPoint":["main.py"]}}' \
  --role-arn arn:aws:iam::111122223333:role/s3f-outvpc-agent-role \
  --network-configuration '{"networkMode":"PUBLIC"}' \
  --filesystem-configurations '[{"s3FilesAccessPoint":{"accessPointArn":"arn:aws:s3files:ap-northeast-1:111122223333:file-system/fs-0123456789abcdef0/access-point/fsap-0123456789abcdef0","mountPath":"/mnt/s3data"}}]'

AgentCore のドキュメントには、S3 Files や EFS では networkMode を VPC にする必要があると記載されています。今回は networkMode が PUBLIC のままで Runtime を作成できました。

https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-filesystem-configurations.html

エージェントのコード(main.py)
import json, os
from http.server import BaseHTTPRequestHandler, HTTPServer

MOUNT = "/mnt/s3data"

def handle(body):
    action = body.get("action", "info")
    out = {"action": action}
    if action == "write":
        path = os.path.join(MOUNT, body["name"])
        with open(path, "w") as f:
            f.write(body["content"])
        out["wrote"] = path
    elif action == "read":
        with open(os.path.join(MOUNT, body["name"])) as f:
            out["content"] = f.read()
    elif action == "ls":
        out["files"] = sorted(os.listdir(MOUNT))
    out["mount_lines"] = [l.strip() for l in open("/proc/mounts") if MOUNT in l]
    out["files"] = out.get("files") or (sorted(os.listdir(MOUNT)) if os.path.isdir(MOUNT) else None)
    return out

class H(BaseHTTPRequestHandler):
    def _send(self, code, obj):
        data = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        self._send(200, {"status": "Healthy"})

    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0))
        try:
            body = json.loads(self.rfile.read(n) or b"{}")
            self._send(200, handle(body))
        except Exception as e:
            self._send(200, {"error": repr(e)})

HTTPServer(("0.0.0.0", 8080), H).serve_forever()

書き込みと別セッションからの読み取り

1つ目のセッションでファイルを書き込み、別のセッション ID を指定した2つ目のセッションで同じファイルを読みました。

aws bedrock-agentcore invoke-agent-runtime \
  --agent-runtime-arn arn:aws:bedrock-agentcore:ap-northeast-1:111122223333:runtime/s3f_outvpc_agent-xxxxxxxxxx \
  --runtime-session-id session-s3f-outvpc-verify-0001-aaaaaaaaaa \
  --content-type application/json \
  --cli-binary-format raw-in-base64-out \
  --payload '{"action":"write","name":"hello-from-agentcore.txt","content":"written from AgentCore Runtime (PUBLIC)"}' \
  out-write.json

aws bedrock-agentcore invoke-agent-runtime \
  --agent-runtime-arn arn:aws:bedrock-agentcore:ap-northeast-1:111122223333:runtime/s3f_outvpc_agent-xxxxxxxxxx \
  --runtime-session-id session-s3f-outvpc-verify-0002-bbbbbbbbbb \
  --content-type application/json \
  --cli-binary-format raw-in-base64-out \
  --payload '{"action":"read","name":"hello-from-agentcore.txt"}' \
  out-read.json

1回目の応答では wrote に /mnt/s3data/hello-from-agentcore.txt が返り、書き込みに成功しました。2回目の応答では content に written from AgentCore Runtime (PUBLIC) が返り、1つ目のセッションで書き込んだ内容を別のセッションから読めました。

Lambda MicroVMs から読み書きする

イメージの作成

Lambda MicroVMs の起動時にはファイルシステムを指定する項目がありません。イメージの中のアプリケーションがマウントコマンドを実行するため、イメージにマウントヘルパーの amazon-efs-utils(バージョン:4.0.0 以降)を入れます。

記事執筆時点では、efs-utils の RPM リポジトリにある最新版は 3.4.0 であったため、GitHub のソースから RPM パッケージをビルドしてイメージに同梱しました。

https://github.com/aws/efs-utils/releases/tag/v4.0.0

efs-utils 4.0.0 の RPM ビルドスクリプト(build-rpm.sh)

Amazon Linux 2023(arm64)のコンテナ内で実行し、RPM を /out に出力します。MicroVM イメージは ARM_64 なので、aarch64 の RPM を使います。

#!/bin/bash
# Build amazon-efs-utils v4.0.0 RPM for Amazon Linux 2023 (arm64) inside a container.
set -ex
dnf install -y --allowerasing git make gcc gcc-c++ cmake perl golang rpm-build curl tar gzip which openssl-devel
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
. "$HOME/.cargo/env"
git clone --depth 1 --branch v4.0.0 https://github.com/aws/efs-utils /build/efs-utils
cd /build/efs-utils
make rpm-without-system-rust
cp build/*.rpm /out/
ls -l /out

Dockerfile は次のとおりです。ビルドした RPM をコピーしてインストールし、app.py を起動します。

FROM public.ecr.aws/lambda/microvms:al2023-minimal
COPY amazon-efs-utils-4.0.0-1.amzn2023.aarch64.rpm /tmp/
RUN dnf install -y python3 python3-pip util-linux nfs-utils openssl stunnel which \
 && pip3 install botocore \
 && rpm -ivh --nodeps /tmp/amazon-efs-utils-4.0.0-1.amzn2023.aarch64.rpm \
 && rpm -q amazon-efs-utils \
 && dnf clean all && rm -f /tmp/*.rpm
WORKDIR /app
COPY app.py .
EXPOSE 8080
CMD ["python3", "app.py"]
アプリケーションのコード(app.py)
import json, os, subprocess
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

MOUNT = "/mnt/s3data"
FS_ID = os.environ.get('S3FILES_FS_ID', 'fs-0123456789abcdef0')
AP_ID = os.environ.get('S3FILES_AP_ID', 'fsap-0123456789abcdef0')

def sh(cmd):
    p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=90)
    return {"cmd": cmd, "rc": p.returncode, "out": p.stdout[-3000:], "err": p.stderr[-3000:]}

def handle(b):
    a = b.get("action", "info")
    out = {"action": a}
    if a == "mount":
        os.makedirs(MOUNT, exist_ok=True)
        out["mount"] = sh(f"mount -t s3files -o accesspoint={AP_ID} {FS_ID} {MOUNT}")
        if out["mount"]["rc"] != 0:
            out["efs_log"] = sh("tail -n 40 /var/log/amazon/efs/*.log")
    elif a == "write":
        p = os.path.join(MOUNT, b["name"]); open(p, "w").write(b["content"]); out["wrote"] = p
    elif a == "read":
        out["content"] = open(os.path.join(MOUNT, b["name"])).read()
    elif a == "sh":
        out["sh"] = sh(b["cmd"])
    out["mount_lines"] = [l.strip() for l in open("/proc/mounts") if MOUNT in l]
    out["files"] = sorted(os.listdir(MOUNT)) if os.path.isdir(MOUNT) else None
    return out

class H(BaseHTTPRequestHandler):
    def _send(self, obj):
        d = json.dumps(obj).encode()
        self.send_response(200); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(d))); self.end_headers(); self.wfile.write(d)
    def do_GET(self): self._send({"status": "ok"})
    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0))
        try: self._send(handle(json.loads(self.rfile.read(n) or b"{}")))
        except Exception as e: self._send({"error": repr(e)})

ThreadingHTTPServer(("0.0.0.0", 8080), H).serve_forever()

Dockerfile、app.py、RPM をまとめた zip を S3 に置き、イメージを作成しました。指定した内容は次のとおりです。

  • --code-artifact:S3 に置いた zip
  • --base-image-arn:MicroVM のベースイメージ al2023-1
  • --build-role-arn:イメージのビルド用ロール
  • --additional-os-capabilities:["ALL"]

https://docs.aws.amazon.com/lambda/latest/dg/microvms-images.html

aws lambda-microvms create-microvm-image \
  --name s3f-outvpc-image \
  --code-artifact uri=s3://amzn-s3-demo-bucket/code/app.zip \
  --base-image-arn arn:aws:lambda:ap-northeast-1:aws:microvm-image:al2023-1 \
  --build-role-arn arn:aws:iam::111122223333:role/s3f-outvpc-microvm-build-role \
  --additional-os-capabilities '["ALL"]'

get-microvm-image で state が CREATED になるのを確認してから、MicroVM を起動しました。

起動とマウント

VPC のネットワークコネクタは使わず、AWS 管理のネットワークコネクタ(HTTP_INGRESS と INTERNET_EGRESS)を指定して起動しました。

aws lambda-microvms run-microvm \
  --image-identifier arn:aws:lambda:ap-northeast-1:111122223333:microvm-image:s3f-outvpc-image \
  --ingress-network-connectors arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:HTTP_INGRESS \
  --egress-network-connectors arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS \
  --execution-role-arn arn:aws:iam::111122223333:role/s3f-outvpc-microvm-role \
  --maximum-duration-in-seconds 3600

get-microvm で state が RUNNING になってから認証トークンを発行し、curl でアプリケーションにマウントを指示しました。

aws lambda-microvms create-microvm-auth-token \
  --microvm-identifier <microvm-id> \
  --expiration-in-minutes 60 \
  --allowed-ports '[{"port":8080}]'

curl -X POST https://<microvm-endpoint>/ \
  -H 'X-aws-proxy-auth: <TOKEN>' \
  -H 'X-aws-proxy-port: 8080' \
  -d '{"action":"mount"}'

応答は次のとおりでした。

{"action": "mount", "mount": {"cmd": "mount -t s3files -o accesspoint=fsap-0123456789abcdef0 fs-0123456789abcdef0 /mnt/s3data", "rc": 0, "out": "", "err": "Could not start amazon-efs-mount-watchdog, unrecognized init system \"python3\"\n"}, "mount_lines": ["127.0.0.1:/ /mnt/s3data nfs4 rw,relatime,vers=4.2,rsize=1048576,wsize=1048576,namlen=255,hard,noresvport,proto=tcp,port=20192,timeo=600,retrans=2,sec=sys,clientaddr=127.0.0.1,local_lock=none,addr=127.0.0.1 0 0"], "files": ["hello-from-agentcore.txt"]}

マウントログ(/var/log/amazon/efs/mount.log)は、app.py の sh アクション(受け取ったコマンドを MicroVM 内で実行する)で cat して読みました。マウント成功時の該当行は次のとおりです。

2026-11-30 03:09:19 UTC - INFO - Failed to resolve apne1-az4.fs-0123456789abcdef0.s3files.ap-northeast-1.on.aws
2026-11-30 03:09:19 UTC - INFO - Using endpoint mode to mount filesystem fs-0123456789abcdef0
2026-11-30 03:09:23 UTC - INFO - Successfully mounted apne1-az4.fs-0123456789abcdef0.s3files.ap-northeast-1.on.aws at /mnt/s3data

到達できるマウントターゲットがない場合、マウントヘルパーは S3 Files Endpoints にポート 443 で接続します。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-files-networking.html

今回のログでは、ホスト名の名前解決に失敗し、Endpoints モードが選ばれました。

別のファイルの書き込みと AgentCore Runtime から書き込んだファイルの読み取り

MicroVM から、別のファイルを書き込み、AgentCore Runtime から書き込んだ hello-from-agentcore.txt を読みました。

curl -X POST https://<microvm-endpoint>/ \
  -H 'X-aws-proxy-auth: <TOKEN>' \
  -H 'X-aws-proxy-port: 8080' \
  -d '{"action":"write","name":"hello-from-microvm.txt","content":"written from Lambda MicroVM (no VPC)"}'

curl -X POST https://<microvm-endpoint>/ \
  -H 'X-aws-proxy-auth: <TOKEN>' \
  -H 'X-aws-proxy-port: 8080' \
  -d '{"action":"read","name":"hello-from-agentcore.txt"}'

MicroVM から hello-from-agentcore.txt を読むと、AgentCore Runtime から書き込んだ内容 written from AgentCore Runtime (PUBLIC) が返りました。

S3 側への反映

ドキュメントによると、更新したファイルは、そのファイルへの書き込みが60秒間途切れた後に S3 へエクスポートされます。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-files-synchronization.html

AgentCore Runtime から書き込んだ約30秒後に aws s3 ls を実行した時点では、ファイルは S3 側で見えませんでした。約80秒後の aws s3 ls では見えました。オブジェクトの LastModified は、書き込みの65秒後でした。

MicroVM から書き込んだ hello-from-microvm.txt も S3 に現れました。aws s3 cp で取得した内容は、書き込んだ written from Lambda MicroVM (no VPC) と一致しました。

まとめ

VPC 外のエージェントから、S3 Files Endpoints を通じて S3 のデータをファイルとして扱えることを確認できました。

S3 をネイティブにサポートしないワークロードで S3 Files を使うために、AgentCore Runtime や Lambda MicroVMs に VPC アクセスを構成していた場合は、今回のアップデートで追加された S3 Files Endpoints をお試しください。

この記事をシェアする

AWSのお困り事はクラスメソッドへ

関連記事