Skip to main content

Deploy a durable agent to AgentCore Runtime

Amazon Bedrock AgentCore Runtime runs your agent container in sessions, each in its own microVM, and routes every invocation to its session. This guide deploys the agent from the quickstart to AgentCore Runtime. The agent keeps its Diagrid runner, so every invocation of the Runtime is a durable workflow in your Diagrid project.

A Diagrid-enabled agent in an AgentCore sessionYour AWS accountSession microVMDiagridYour clientAWS credentialsAgentCore RuntimeInvokeAgentRuntimeAgent containerStrands + DiagridSecrets Managerread by the execution roleWorkflowsDiagrid credentials
A Diagrid-enabled agent in an AgentCore sessionThe session only opens outbound connections. As the execution role, it reads the agent's Diagrid credentials from Secrets Manager and calls the model in Amazon Bedrock. It reaches Diagrid with those credentials.

How the hosted agent connects​

ConcernHow it works in AgentCore
ProtocolThe container serves POST /invocations and GET /ping on port 8080 with AgentcoreRunner from the Diagrid package.
Permissions in AWSAgentCore runs the container with an execution role, which the CloudFormation template creates. The role can pull the image, read one secret and invoke Bedrock models. The agent calls its model with the role's credentials, so there is no model API key.
Authentication to DiagridThe agent authenticates with its Diagrid credentials, which are in AWS Secrets Manager. The Runtime gets only the secret's ARN, in AGENT_SECRET_ARN, and AgentcoreRunner loads the secret at startup.
ConnectivityThe Runtime uses the PUBLIC network mode. The container opens outbound connections to the HTTP and gRPC endpoints of your Diagrid project on port 443, and to Amazon Bedrock. Diagrid never connects in to the session.

Prerequisites​

  • The quickstart completed. You need its budget-planner folder and its agentcore-quickstart Diagrid project, and the environment variables from its steps 5 and 6 set in your terminal.
  • An AWS account in a region where AgentCore is available, and permission to create an ECR repository, a secret and a CloudFormation stack with an IAM role and an AgentCore Runtime
  • The AWS CLI v2, logged in to that account
  • Docker with buildx. AgentCore Runtime runs only linux/arm64 images.
  • jq, on macOS and Linux

1. Set the AWS values​

Set your account ID and the ECR repository the steps below use. They use AWS_REGION from the quickstart's step 5: the stack is deployed in that region, and the agent calls Bedrock there.

export AWS_ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"
export ECR_REPO="$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/agentcore-quickstart-budget-planner"

2. Build and push the image​

In the budget-planner folder, create a Dockerfile next to main.py:

Dockerfile
FROM python:3.13-slim

# Pinned, so every build installs with the same uv.
COPY --from=ghcr.io/astral-sh/uv:0.12.21 /uv /uvx /bin/

WORKDIR /app

# Install the locked dependencies into /app/.venv.
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev

COPY main.py ./

# AgentCore Runtime calls the container on port 8080.
EXPOSE 8080

# Run the agent as a user without root privileges.
RUN useradd --uid 1000 --no-create-home app
USER app

CMD ["/app/.venv/bin/python", "main.py"]

Create a .dockerignore file so that your local virtual environment stays out of the image:

.dockerignore
.venv
__pycache__

AgentCore Runtime requires the image to be in Amazon ECR. Create the repository, log in to it, and build and push a linux/arm64 image. docker buildx create --use is needed once, so that buildx can build for another architecture:

aws ecr create-repository --repository-name agentcore-quickstart-budget-planner --region "$AWS_REGION"
aws ecr get-login-password --region "$AWS_REGION" \
| docker login --username AWS --password-stdin "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"
docker buildx create --use
docker buildx build --platform linux/arm64 -t "$ECR_REPO:v1" --push .

To check the image before you deploy it, run it with the values from the quickstart and send it the quickstart's request. -e NAME with no value copies the variable from your terminal, so the secrets don't appear on the command line. The container has no AWS login of its own, so first export your AWS CLI login's temporary credentials into the terminal. On an x86 machine, running a linux/arm64 image needs QEMU emulation, as described in Docker's multi-platform builds. Without it, skip this check:

eval "$(aws configure export-credentials --format env)"
docker run --rm --platform linux/arm64 -p 8080:8080 \
-e DAPR_GRPC_ENDPOINT -e DAPR_HTTP_ENDPOINT -e DAPR_API_TOKEN \
-e AWS_REGION -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_SESSION_TOKEN \
-e BEDROCK_MODEL_ID -e BEDROCK_MAX_TOKENS \
"$ECR_REPO:v1"

3. Store the secret​

Store the agent's Diagrid credentials as a JSON secret. The value goes into a file only you can read, the AWS CLI reads that file, and the file is deleted, so the value doesn't appear on a command line, as the Secrets Manager guidance for the AWS CLI recommends:

(umask 077 && jq -n --arg token "$DAPR_API_TOKEN" '{DAPR_API_TOKEN: $token}' > secret.json)
aws secretsmanager create-secret --name agentcore-quickstart/budget-planner --region "$AWS_REGION" \
--secret-string file://secret.json
shred -u secret.json
export AGENT_SECRET_ARN="$(aws secretsmanager describe-secret --secret-id agentcore-quickstart/budget-planner \
--region "$AWS_REGION" --query ARN --output text)"

If shred isn't installed, delete the file with rm secret.json.

4. Deploy the AgentCore Runtime​

A CloudFormation template creates the execution role and the Runtime. The role's trust policy and permissions are the AgentCore Runtime execution role from the AWS documentation, with three changes:

  • ECR access is limited to the agentcore-quickstart-budget-planner repository.
  • The agent may read its one secret.
  • The workload access token statement is left out, because the agent doesn't use AgentCore Identity.

The BedrockModelInvocation statement is the one from the AWS documentation. It allows foundation models in every region, which a cross-region inference profile needs, and the inference profiles of your account in the stack's region.

The Runtime uses the PUBLIC network mode, because the container connects out to Diagrid. Only the endpoints, the region, the model settings and the secret's ARN go into the Runtime definition.

In the budget-planner folder, create template.yaml:

template.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Execution role and AgentCore Runtime for the budget-planner agent

Parameters:
ImageUri:
Type: String
Description: The agent image in ECR, with its tag
AgentSecretArn:
Type: String
Description: The secret that holds the agent's Diagrid credentials (DAPR_API_TOKEN)
DaprGrpcEndpoint:
Type: String
DaprHttpEndpoint:
Type: String
BedrockModelId:
Type: String
Default: us.amazon.nova-lite-v1:0
BedrockMaxTokens:
Type: String
Default: ""
KeepAlive:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "true keeps each session running until Diagrid stops it or it reaches its maximum lifetime"
LongRunSeconds:
Type: String
Default: "0"
Description: "Seconds each vendor check takes; 0 turns the slow tool off"

Resources:
ExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: agentcore-quickstart-budget-planner
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AssumeRolePolicy
Effect: Allow
Principal:
Service: bedrock-agentcore.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:*
Policies:
- PolicyName: agentcore-quickstart-budget-planner
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: ECRImageAccess
Effect: Allow
Action: [ecr:BatchGetImage, ecr:GetDownloadUrlForLayer]
Resource: !Sub arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/agentcore-quickstart-budget-planner
- Sid: ECRTokenAccess
Effect: Allow
Action: ecr:GetAuthorizationToken
Resource: "*"
- Effect: Allow
Action: [logs:DescribeLogStreams, logs:CreateLogGroup]
Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/bedrock-agentcore/runtimes/*
- Effect: Allow
Action: logs:PutResourcePolicy
Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/bedrock-agentcore/runtimes/agentcore_quickstart_budget_planner-*
- Effect: Allow
Action: logs:DescribeLogGroups
Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*
- Effect: Allow
Action: [logs:CreateLogStream, logs:PutLogEvents]
Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*
- Effect: Allow
Action: [xray:PutTraceSegments, xray:PutTelemetryRecords, xray:GetSamplingRules, xray:GetSamplingTargets]
Resource: "*"
- Effect: Allow
Action: cloudwatch:PutMetricData
Resource: "*"
Condition:
StringEquals:
cloudwatch:namespace: bedrock-agentcore
- Sid: BedrockModelInvocation
Effect: Allow
Action: [bedrock:InvokeModel, bedrock:InvokeModelWithResponseStream]
Resource:
- arn:aws:bedrock:*::foundation-model/*
- !Sub arn:aws:bedrock:${AWS::Region}:${AWS::AccountId}:*
- Sid: ReadAgentSecret
Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref AgentSecretArn

Runtime:
Type: AWS::BedrockAgentCore::Runtime
Properties:
AgentRuntimeName: agentcore_quickstart_budget_planner
AgentRuntimeArtifact:
ContainerConfiguration:
ContainerUri: !Ref ImageUri
NetworkConfiguration:
NetworkMode: PUBLIC
RoleArn: !GetAtt ExecutionRole.Arn
EnvironmentVariables:
DAPR_GRPC_ENDPOINT: !Ref DaprGrpcEndpoint
DAPR_HTTP_ENDPOINT: !Ref DaprHttpEndpoint
AGENT_SECRET_ARN: !Ref AgentSecretArn
AWS_REGION: !Ref AWS::Region
BEDROCK_MODEL_ID: !Ref BedrockModelId
BEDROCK_MAX_TOKENS: !Ref BedrockMaxTokens
AGENT_WORKER_KEEPALIVE: !Ref KeepAlive
LONG_RUN_SECONDS: !Ref LongRunSeconds

Outputs:
RuntimeArn:
Value: !GetAtt Runtime.AgentRuntimeArn

Deploy the stack, and read the Runtime's ARN from its outputs. The template names the role, so deploying it needs CAPABILITY_NAMED_IAM. Run the lookup again in any new terminal before the steps below:

aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
--template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides "ImageUri=$ECR_REPO:v1" "AgentSecretArn=$AGENT_SECRET_ARN" \
"DaprGrpcEndpoint=$DAPR_GRPC_ENDPOINT" "DaprHttpEndpoint=$DAPR_HTTP_ENDPOINT" \
"BedrockModelId=$BEDROCK_MODEL_ID" "BedrockMaxTokens=$BEDROCK_MAX_TOKENS"
export RUNTIME_ARN="$(aws cloudformation describe-stacks --region "$AWS_REGION" \
--stack-name agentcore-quickstart-budget-planner \
--query "Stacks[0].Outputs[?OutputKey=='RuntimeArn'].OutputValue" --output text)"
echo "$RUNTIME_ARN"
aws bedrock-agentcore-control get-agent-runtime --region "$AWS_REGION" \
--agent-runtime-id "${RUNTIME_ARN##*/}" --query status --output text

The ARN starts with arn:aws:bedrock-agentcore:, and the status is READY. An empty RUNTIME_ARN makes the invocation below fail with 404 UnknownOperationException.

5. Invoke the hosted agent​

A request waits for the run's answer. Send {} in the same session to collect the result of a run whose request failed or timed out. The reference lists every request and its answer.

The runtime session ID must be at least 33 characters long. Invoke the Runtime with a new session ID:

export SESSION_ID="budget-planner-$(uuidgen)"
aws bedrock-agentcore invoke-agent-runtime \
--region "$AWS_REGION" \
--agent-runtime-arn "$RUNTIME_ARN" \
--runtime-session-id "$SESSION_ID" \
--content-type text/plain \
--accept application/json \
--cli-binary-format raw-in-base64-out \
--payload 'Calculate the budget for a corporate event with venue, catering, and entertainment' \
response.json && jq . response.json

The first request of a session takes longer, because AgentCore starts a microVM for it. The CLI prints the call's metadata, and the response holds the workflow ID, its status and the agent's answer:

{
"instance_id": "budget-planner-50e0376b-0d63-438d-bb5d-e6c44f6360a1",
"status": "COMPLETED",
"result": "Here's the budget breakdown for your corporate event:\n\n- **Venue**: $3,500\n- **Catering**: $2,250\n- **Entertainment**: $1,500\n\n**Total**: $7,250 …"
}

The exact wording of result depends on the model. For example, Amazon Nova models start it with their reasoning in a <thinking> block.

Invocations with the same SESSION_ID go to the same AgentCore session and continue its conversation, as in the quickstart.

6. View the workflow in Diagrid​

The invocation ran as a workflow under the budget-planner ID, the agent's workload identity, with the session ID as its workflow ID:

diagrid workflow list --project agentcore-quickstart --id budget-planner
diagrid workflow get "$SESSION_ID" --id budget-planner --project agentcore-quickstart

The steps in the history ran inside the AgentCore session, and their results are stored in your Diagrid project. The quickstart explains what to look at in the output.

Update the image​

Pushing a new image doesn't change the Runtime. Each update to the Runtime creates a new version, and the DEFAULT endpoint that invoke-agent-runtime uses moves to it. A session that started before the update keeps running the version it started with, so invoke with a new session ID to reach the new image.

Build and push the image with a new tag, such as v2, as in step 2. The ECR login is valid for 12 hours, so log in again if it has expired. Then deploy the stack again with the new image. A parameter you leave out keeps its current value:

aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
--template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides "ImageUri=$ECR_REPO:v2"

Check that the Runtime is READY and runs the new image:

aws bedrock-agentcore-control get-agent-runtime --region "$AWS_REGION" --agent-runtime-id "${RUNTIME_ARN##*/}" \
--query '{status: status, version: agentRuntimeVersion, image: agentRuntimeArtifact.containerConfiguration.containerUri}'

Rotate the credentials​

The container reads the secret when an AgentCore session starts. To rotate the agent's Diagrid credentials, set the new value in DAPR_API_TOKEN, and write it to the secret as in step 3, with put-secret-value in place of create-secret. Sessions that start after the update use the new value:

(umask 077 && jq -n --arg token "$DAPR_API_TOKEN" '{DAPR_API_TOKEN: $token}' > secret.json)
aws secretsmanager put-secret-value --region "$AWS_REGION" --secret-id "$AGENT_SECRET_ARN" \
--secret-string file://secret.json
shred -u secret.json

How sessions run​

  • Each session is a workflow worker. Each session's container connects to Diagrid as a worker of budget-planner on its first invocation. Diagrid gives a run to any connected worker of the ID, so a session's run can execute in another session's container.
  • AgentCore ends idle sessions. AgentCore stops a session after 15 minutes without activity, or 8 hours after it started. Both are defaults that the Runtime's lifecycle configuration can change. A request waiting for a run keeps the session active. When no request is waiting, the idle timeout stops the session, even if its worker is executing a run. The run keeps its state in Diagrid, and resumes as soon as a container of the Runtime is connected, or, if none is, when the next invocation starts one.
  • A request waits for its run, up to 14 minutes. AgentCore allows a synchronous request 15 minutes, so AgentcoreRunner answers before that. A run that takes longer keeps running in Diagrid, and the request returns 202 with {"status": "RUNNING"}. Send {} in the same session to collect the result. See the reference.
  • The conversation is stored in Diagrid. The Strands runner keeps each session's messages, tool calls and tool results included, in the project's kvstore state store, so a new session container continues the same conversation.
  • Usage events. The Diagrid package sends one anonymous usage event per process, so one for each session's container. It holds versions, the platform and the agent framework, and no prompts, IDs or hostnames. To turn it off, add DO_NOT_TRACK: "1" to the Runtime's EnvironmentVariables in template.yaml, and deploy the stack again.

To start and stop sessions only when the agent has work, and keep them running while it does, use Diagrid-managed sessions.

Clean up​

If you continue with Diagrid-managed sessions, skip this section: that guide uses everything you created here and deletes it at its end. Otherwise, delete the stack, which deletes the Runtime and the execution role, and the secret:

aws cloudformation delete-stack --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws secretsmanager delete-secret --region "$AWS_REGION" --secret-id "$AGENT_SECRET_ARN" --force-delete-without-recovery
rm -f response.json

Delete the image repository and the Diagrid project:

aws ecr delete-repository --repository-name agentcore-quickstart-budget-planner --region "$AWS_REGION" --force
diagrid project delete agentcore-quickstart

Next steps​

Was this page helpful?