
End-to-End AI Agent on AgentCore Runtime with Terraform: A Quick Build
Step-by-step build of a daily reminder agent. A Strands agent on Amazon Nova Pro, deployed to AgentCore Runtime as a zip, with no Docker and no Lambda. EventBridge Scheduler invokes it directly. Bedrock Guardrails blocks prompt injection in the Google Sheet, AgentCore Memory stops duplicate emails, and AgentCore Observability and Evaluations trace and score every run. One terraform apply deploys it all for about $5 a month, with real code and the Scheduler gotchas.
End-to-End AI Agent on AgentCore Runtime with Terraform: A Quick Build
From a Google Sheet to an inbox. A daily AI agent on Amazon Bedrock AgentCore Runtime, deployed with one
terraform apply , for about $5 a month.First version of this reminder agent was built with LangGraph on AWS Lambda ( https://medium.com/@MUmarAmanat/ai-reminder-agent-that-costs-less-than-a-coffee-langgraph-aws-terraform-d6bea79ac6b5 ). Its main limitation was the runtime. As more data sources and conversation history were added, that implementation could no longer handle the increased workload.
The agent was therefore rebuilt on AWS-native agent infrastructure, with the rest of the system kept as close to the original as possible. It now runs on Amazon Bedrock AgentCore Runtime, uses the Strands Agents SDK, calls Amazon Nova Pro with IAM authentication only (no API key), and is triggered by EventBridge Scheduler calling the runtime directly. The solution uses no Lambda function and no Docker image.
This article walks through the build step by step, with the code that matters and the issues encountered along the way. The complete code is available on GitHub at https://github.com/MUmarAmanat/strands-on-agentcore . Cloning the repository, filling in one variables file and running
terraform apply brings up the whole application.Architecture Diagram

Figure 1: Reminder Agent's Architecture, Source: Author
Figure 1 shows the full flow.
- Deploy (top):
terraform applyruns a build script that produces an ARM64 zip, uploads it to S3, and points AgentCore Runtime at it.
- Trigger (left): EventBridge Scheduler calls
InvokeAgentRuntimeonce a day.
- Agent (center): the entry point responds immediately and starts the Strands agent in the background. The agent has two tools.
fetch_tasksreads the sheet, andsend_reminder_emailsends one email through SES.
- Safety (right): a Bedrock Guardrail checks the sheet text before the model reads it, and AgentCore Memory records which dates have already received an email.
- Observe (far right): traces are sent to CloudWatch, failures trigger an SNS email, and AgentCore Evaluations scores every run.
Requirements
- AWS account, with Amazon Nova Pro available in the chosen region (tested in
us-east-1)
- Terraform 1.7 or later
- uv with Python 3.12
- Google Sheet and a Google service account key (steps below)
- GitHub account
Google Sheet and service account
The agent uses a service account, so it can read only the sheet shared with it and nothing else in the Google Drive.
- Create a Google Cloud project and enable the Google Sheets API.
- Create a service account and download its JSON key. Keep the file outside the repository. Terraform stores it in Secrets Manager.
- Share the sheet with the service account's email address as Viewer.
The sheet requires five columns. Headers are matched loosely, so
Priority (1 or high - 5 or low) is still recognized as the priority column.
Figure 2: Task list in Google Sheets, with two prompt-injection test rows (rows 4 and 5, text blurred), Source: Author
In Figure 2, two prompt injection examples are intentionally added. The first instructs the assistant to ignore its existing instructions, while the second asks it to send the task list to an external email address. Since a sheet contains user-editable text, any content read by an LLM could potentially influence its behavior. These two examples are revisited in Step 6.
Why Strands + AgentCore Runtime
- Strands Agents provides the model-and-tools loop in a few lines of code. Tools are plain Python functions marked with
@tool, and the SDK handles tool calling.
- AgentCore Runtime runs the agent as a managed service. It accepts a plain zip from S3 (direct code deploy), so no container image or ECR repository is needed.
- Amazon Nova Pro is a first-party Amazon model on Bedrock. Access is controlled through IAM, so there is no secret to rotate. It is also covered by AWS credits, whereas third-party models on Bedrock are billed through AWS Marketplace. For this reason, the Terraform variable rejects non-Amazon model IDs.
Strands + AgentCore Runtime + Terraform in Action
Step 1: Agent, and its Tools
The agent itself is small. It receives a system prompt, two tools and loop limits.
agent = Agent( model=self._model, tools=self._build_tools(outcome, reference_date), system_prompt=_SYSTEM_PROMPT.format( reference_date=reference_date.isoformat() ), callback_handler=None,)result = agent(_USER_PROMPT, limits={"turns": 5, "total_tokens": 20_000})A normal run takes three turns (fetch, send and final reply). The limits prevent a confused model from looping and consuming tokens.
The key design principle is that the prompt describes the job, but rules that must never break are enforced in code. The model is instructed to send exactly one email, and the tool guarantees it.
@tooldef send_reminder_email(subject: str, body: str) -> str: """Send the reminder email to the user. Call at most once.""" if outcome["blocked"]: return "Task data was blocked; email not sent." if outcome["sent"]: return "Email already sent; not sending again." message_id = self._notifier.send(subject, body) outcome["sent"] = True outcome["message_id"] = message_id self._memory.record_sent(reference_date, message_id, outcome["task_count"]) return f"Email sent (id: {message_id})."Regardless of the model's decisions, it cannot send twice, and it cannot send when the guardrail has blocked the input. The tools are created fresh for each run and closed over a small
outcome dictionary, so the actual result of the run is reported from code rather than taken from the model's final message.The Google Sheets reader, the SES notifier, the configuration and the retry helper were carried over from the LangGraph project almost unchanged. Only the agent layer was replaced.
Step 2: The entry point, say "accepted" fast
EventBridge Scheduler waits for the invoke call to return. If the agent performs all its work inside the request, a slow model call appears as a failed invocation, and Scheduler retries.
The solution is to acknowledge immediately and run the agent in a background thread. The
bedrock-agentcore SDK provides an async-task API for this purpose, so the runtime's /ping health check reports HealthyBusy while the work is in progress.app = BedrockAgentCoreApp()
@app.entrypointdef invoke(payload): config = Config.from_env() reference_date = _parse_reference_date(payload or {}, config.timezone)
task_id = app.add_async_task("reminder_run") threading.Thread( target=_run_agent, args=(task_id, config, reference_date), daemon=True, ).start() return {"status": "accepted", "reference_date": reference_date.isoformat()}_run_agent builds and runs the agent, logs the result, and calls app.complete_async_task(task_id) in a finally block. Without the finally block, a crash would leave the session busy until it times out.The scheduled run sends an empty payload
{} , and the agent uses the current date in the configured timezone. For a manual or backfill run, a date can be passed explicitly.aws bedrock-agentcore invoke-agent-runtime \ --agent-runtime-arn "$ARN" \ --runtime-session-id "$(uuidgen)-manual" \ --payload '{"reference_date": "2026-11-21"}' \ --cli-binary-format raw-in-base64-out \ response.json
Figure 3: Manual invoke returns status 200 immediately, while the agent keeps working in the background, Source: Author
Step 3: Packaging without Docker
AgentCore Runtime runs on Linux ARM64, while development often happens on Windows or macOS. This mismatch usually requires Docker. Instead, a small script,
scripts/build_package.py , uses uv to download wheels for the target platform._run([ "uv", "pip", "install", "--requirement", str(requirements_file), "--target", str(target), "--python-platform", PLATFORM, # Linux ARM64 "--python-version", PYTHON_VERSION, # 3.12 "--only-binary", ":all:", # never build from source])The script then copies the agent package, adds a small
main.py at the zip root as the entry point, and writes the zip deterministically, with files in sorted order, a fixed timestamp and fixed permissions. The same code always produces the same bytes and the same SHA-256 hash, which is important for the next part.Terraform runs the script itself through an
external data source, so no separate build step is required.data "external" "package" { program = ["uv", "run", "python", "scripts/build_package.py"] working_dir = "${path.module}/.."}
resource "aws_s3_object" "agent_zip" { bucket = aws_s3_bucket.artifacts.id key = "agent-${data.external.package.result.sha256}.zip" source = data.external.package.result.path}Note. AgentCore caches the zip by its S3 key. If new code is uploaded to the same key, the runtime keeps running the old code. Including the SHA-256 hash in the key solves this. New code produces a new key, which triggers a runtime update, while unchanged code produces no change at all.
Step 4: Defining the runtime in Terraform
The runtime is a single resource. It points to the zip, sets the Python version, and passes every setting as an environment variable.
resource "aws_bedrockagentcore_agent_runtime" "this" { agent_runtime_name = local.runtime_name role_arn = aws_iam_role.runtime.arn
agent_runtime_artifact { code_configuration { entry_point = ["main.py"] runtime = "PYTHON_3_12" code { s3 { bucket = aws_s3_bucket.artifacts.bucket prefix = aws_s3_object.agent_zip.key } } } }
network_configuration { network_mode = "PUBLIC" }
lifecycle_configuration { idle_runtime_session_timeout = 300 max_lifetime = 28800 }
environment_variables = { BEDROCK_MODEL_ID = var.bedrock_model_id MEMORY_ID = aws_bedrockagentcore_memory.this.id GUARDRAIL_ID = aws_bedrock_guardrail.this.guardrail_id # ... sheet ID, SES addresses, timezone }}Two points are worth noting.
- Idle timeout of 5 minutes. The agent runs once a day for about 10 seconds, so there is no reason to keep a session alive.
-
max_lifetimeis set explicitly to the AWS default (8 hours). When it is omitted, the AWS provider fails with "inconsistent result after apply".
The runtime's IAM role grants only what the agent needs. It can invoke Nova Pro, apply the guardrail, read one secret, send from one SES identity, and read and write its Memory.
Step 5: Scheduling it, straight to the runtime
In the LangGraph version, EventBridge triggered a Lambda function. In this version, the EventBridge Scheduler universal target calls the AgentCore API directly. Any AWS API can be a target, using an ARN of the form
arn:aws:scheduler:::aws-sdk:<service>:<action> .resource "aws_scheduler_schedule" "daily" { name = "${var.project_name}-daily" schedule_expression = "cron(0 16 * * ? *)" schedule_expression_timezone = var.timezone
flexible_time_window { mode = "OFF" }
target { arn = "arn:aws:scheduler:::aws-sdk:bedrockagentcore:invokeAgentRuntime" role_arn = aws_iam_role.scheduler.arn
input = jsonencode({ AgentRuntimeArn = aws_bedrockagentcore_agent_runtime.this.agent_runtime_arn RuntimeSessionId = "reminder-agent-scheduled-daily-run-session" Payload = "{}" ContentType = "application/json" })
retry_policy { maximum_retry_attempts = 2 maximum_event_age_in_seconds = 3600 } }}This integration has three non-obvious details.
- The session ID is fixed. A unique ID per run, using Scheduler's
<aws.scheduler.execution-id>placeholder, would be preferable. However, the universal target does not fill these placeholders, and the text is sent as is. Every scheduled run therefore uses the same ID. This is safe here because the 5-minute idle timeout ends each session long before the next day, and Memory prevents a second email for the same date. The API also requires the ID to be at least 33 characters long.
- The payload is plain JSON, not base64. The CLI requires
--cli-binary-format raw-in-base64-out, but Scheduler passesPayloadthrough as written.
- The trust policy must match the schedule group. When Scheduler assumes its role,
aws:SourceArnis the ARN of the schedule group (schedule-group/default), not of the schedule. A trust policy that uses the schedule's ARN causes every invocation to fail with an access error.
The schedule timezone and the agent's timezone come from the same variable, so "today" refers to the same day for both.
Step 6: Making it safe, a guardrail and memory
Guardrail for untrusted sheet text
This step returns to rows 4 and 5 from Figure 2. Before the model sees the sheet,
fetch_tasks sends the text to a Bedrock Guardrail with a prompt-attack filter and content filters. If the text is blocked, the tool returns a short message instead of the tasks, and send_reminder_email refuses to send, as shown in Step 1.@tooldef fetch_tasks() -> str: """Fetch the user's active tasks with priority and age context.""" active = [t for t in self._source.fetch_tasks() if not t.completed] text = _render_tasks(active) if active and not self._guard.is_safe(text): outcome["blocked"] = True return "Task data was blocked by the safety guardrail. Do not send an email." return text
Figure 4: Runtime logs showing five tasks parsed, the guardrail blocking the task data and no email sent, Source: Author
Figure 4 shows a run with those rows in the sheet. Five tasks are parsed, the guardrail blocks the task data, and
sent stays false . The whole run completed in under 5 seconds. The trade-off is that a single malicious row blocks the entire day's email. For a personal reminder, skipping one email is preferable to sending a manipulated one.Memory so retries never send twice
Scheduler retries on failure, and runs can also be triggered manually. Neither case should produce two emails for the same day. Immediately after SES accepts the email, the tool writes an event to AgentCore Memory. At the start of each run, the agent checks it in plain code, before any model call.
if self._memory.already_sent(reference_date): return RunResult(sent=False, message_id="", task_count=0, skipped=True)A skipped run consumes no tokens.

Figure 5: AgentCore Memory events created by the runtime, at a total cost of $0.0005, Source: Author
Step 7: Seeing what the agent did
An agent that runs unattended requires good visibility. Terraform sets up three components for this.
Traces. The entry point starts OpenTelemetry, and Terraform enables CloudWatch Transaction Search. Every run appears in CloudWatch GenAI Observability, with each model call, tool call and AWS call recorded as a span.

Figure 6: Spans for one run, covering Nova Pro calls, the tools, Memory, SES and the guardrail, Source: Author

Figure 7: One full run with 18 spans, 4.5K tokens and 9.7 seconds of latency, Source: Author
Figure 7 captures a complete run. It reads Memory, runs the agent loop, fetches the secret, applies the guardrail, calls the model and sends the email, using about 3,800 input tokens and 700 output tokens.
Alarms. Two CloudWatch alarms send an email through SNS. One fires when the agent logs
Reminder run failed , and the other fires when Scheduler cannot invoke the runtime.Online evaluation. AgentCore Evaluations scores every run with five built-in LLM-as-a-judge evaluators, covering goal success, instruction following, faithfulness, tool selection and tool parameters. Scores appear about 15 to 20 minutes after a run, once the session becomes idle.

Figure 8: Five built-in evaluators, all with results and no errors, Source: Author

Figure 9: Both tool calls scored 1.0 for tool selection and parameter accuracy, Source: Author

Figure 10: Each score comes with the judge's reasoning, Source: Author
These scores are LLM judgments, not ground truth.
InstructionFollowing grades the user request ("run today's reminder check"), not the formatting rules in the system prompt. Verifying those rules would require a custom evaluator.Reminder Agent in Action
git clone https://github.com/MUmarAmanat/strands-on-agentcore.gitcd strands-on-agentcore/terraformcp terraform.tfvars.example terraform.tfvars # sheet ID, key path, emails, regionterraform initterraform applyterraform apply builds the zip, uploads it, and creates every resource shown in Figure 1. Two manual steps remain that Terraform cannot perform.- SES: click the verification links sent to the sender and recipient addresses. In the SES sandbox, both must be verified.
- SNS: confirm the alert subscription email, otherwise failure alerts are not delivered.
The schedule starts immediately. Set
schedule_enabled = false to test with manual invocations first. To deploy code changes, edit the code and run terraform apply again.The repository includes 91 Python unit tests, 55 Terraform tests (mocked, with no AWS calls), and a least-privilege IAM policy for the deploy user in
docs/deployer-policy.json .Cost and Limitations
For one run per day, the estimated cost is about $5 per month.
Item | Per month |
|---|---|
AgentCore Evaluations (5 evaluators) | ~$4 |
Secrets Manager (1 secret) | $0.40 |
Nova Pro (~4.5K tokens per run) | < $0.20 |
Runtime, Memory, Guardrail, SES, Scheduler, S3, SNS | cents |
CloudWatch logs, spans, alarms | < $1 |
Evaluation accounts for most of the cost. Setting
enable_online_evaluation = false reduces the total to about one dollar per month.The current limitations are listed below.
- One sheet and one recipient, and only Google Sheets is supported.
- A tool error, such as a malformed sheet, is returned to the model and the run ends normally, so the failure alarm does not fire. Traces and evaluation scores reveal such cases.
- The Google key is stored in Terraform state. State is local and git-ignored in this setup. For team use, it should be moved to an encrypted remote backend.
-
terraform destroyleaves the runtime's log group, which AgentCore creates itself. It must be deleted manually if the logs are no longer needed.
Conclusion
Goal of this rebuild was to keep the agent logic that already worked while moving the supporting components to managed AWS services. Strands replaced the custom agent loop, and AgentCore Runtime replaced Lambda and the associated packaging work. Scheduler now invokes the runtime directly, while Nova Pro eliminates the need for a separate API key. The remaining custom code focuses only on what is specific to this use case, which is reading the sheet and composing the email.
This build highlights a few important lessons for scheduled AI agents. Respond quickly to triggers and handle the actual work in the background. Enforce security rules in the tool code rather than relying only on prompts. Treat all user-provided data as untrusted, and make sure retries do not cause duplicate actions. Following these practices helps build a reliable daily AI agent with tracing, alerts, and automatic evaluation using just a few Terraform files, at a cost of around $5 per month.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article