Provisioning a scheduled Amazon price-watch with Terraform means writing one root module around the same tracker.py Lambda handler an existing Lambda/EventBridge price-tracker post already implements, unchanged: aws_lambda_function, aws_cloudwatch_event_rule plus aws_cloudwatch_event_target for the schedule, an aws_iam_role/aws_iam_role_policy scoped to exactly three actions, and an aws_secretsmanager_secret the function reads via boto3 at cold start - never a plaintext Terraform variable, because Terraform writes variable values into its state and plan files in plain text.
Key Takeaways
- tracker.py's handler() and buy_box_price() are byte-identical to the existing Lambda/EventBridge price-tracker post; the only addition is a _load_api_key() bootstrap that runs once per cold start, before sellermagnet.py's unmodified new_session() ever reads os.environ.
- The API key is never a Terraform variable or a Lambda environment variable: the module provisions an aws_secretsmanager_secret container, the function gets only its ARN, and the real value is set out-of-band after apply, with lifecycle.ignore_changes on the placeholder version so that later rotation never shows up as drift.
- aws_cloudwatch_event_target alone does not grant invoke rights - a separate aws_lambda_permission resource with principal events.amazonaws.com and source_arn set to the rule's ARN is required, unlike an EventBridge Scheduler schedule's own RoleArn.
- terraform validate is the offline, no-credentials check this module was run against (syntax, references, required arguments); terraform plan still needs a real AWS account to call GetCallerIdentity, so it fails closed here with no account configured, not a silent pass.
- The IAM policy grants exactly the three actions the handler calls - dynamodb:GetItem/PutItem on this table's own ARN, sns:Publish on this topic's own ARN, secretsmanager:GetSecretValue on this secret's own ARN - plus the AWSLambdaBasicExecutionRole managed policy for CloudWatch Logs, never a wildcard resource.
Why provision the secret container instead of a Terraform variable?
HashiCorp's own documentation is explicit about the state file: "If you are developing with Terraform locally, Terraform stores your state in a plaintext file, which includes any secret values you defined in your configuration." A variable "sellermagnet_api_key" block would put the key into terraform.tfstate the moment it is applied, and into the plan file before that - both files a .gitignore for a Terraform project excludes from version control for exactly this reason, never committed. This module instead declares only an aws_secretsmanager_secret and a placeholder aws_secretsmanager_secret_version; the real value is written after apply, with lifecycle { ignore_changes = [secret_string] } so a manual rotation of that value is never read back as a change the next plan wants to revert.
main.tf - full root module
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.4"
}
}
}
provider "aws" {
region = var.aws_region
}
# --- Secret: the API key itself is never a plaintext Terraform variable. ---
# `terraform plan`/`apply` would otherwise write the value into the state file in plaintext
# (developer.hashicorp.com/terraform/language/manage-sensitive-data: "If you are developing with
# Terraform locally, Terraform stores your state in a plaintext file, which includes any secret
# values you defined in your configuration"). This resource only provisions the secret CONTAINER;
# the value is written out-of-band (console/CLI) after apply, never through a tf variable or
# secret_string argument, and ignore_changes keeps a later manual rotation from drifting the plan.
resource "aws_secretsmanager_secret" "sellermagnet_api_key" {
name = "${var.name_prefix}-sellermagnet-api-key"
description = "SellerMagnet API key, read by the price-watch Lambda at cold start via boto3."
recovery_window_in_days = 7
}
resource "aws_secretsmanager_secret_version" "sellermagnet_api_key_placeholder" {
secret_id = aws_secretsmanager_secret.sellermagnet_api_key.id
secret_string = "REPLACE_AFTER_APPLY"
lifecycle {
ignore_changes = [secret_string]
}
}
# --- State for the price watch. ---
resource "aws_dynamodb_table" "prices" {
name = "${var.name_prefix}-prices"
billing_mode = "PAY_PER_REQUEST"
hash_key = "asin"
attribute {
name = "asin"
type = "S"
}
}
resource "aws_sns_topic" "price_drops" {
name = "${var.name_prefix}-price-drops"
}
# --- Least-privilege execution role: only the three actions the handler actually calls, scoped
# to the specific table/topic/secret ARNs this module creates, never a wildcard resource. ---
data "aws_iam_policy_document" "lambda_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "price_watch" {
name = "${var.name_prefix}-price-watch-role"
assume_role_policy = data.aws_iam_policy_document.lambda_assume.json
}
data "aws_iam_policy_document" "price_watch_inline" {
statement {
sid = "DynamoDbPriceState"
actions = ["dynamodb:GetItem", "dynamodb:PutItem"]
resources = [aws_dynamodb_table.prices.arn]
}
statement {
sid = "PublishPriceDrop"
actions = ["sns:Publish"]
resources = [aws_sns_topic.price_drops.arn]
}
statement {
sid = "ReadApiKeySecret"
actions = ["secretsmanager:GetSecretValue"]
resources = [aws_secretsmanager_secret.sellermagnet_api_key.arn]
}
}
resource "aws_iam_role_policy" "price_watch_inline" {
name = "${var.name_prefix}-price-watch-inline"
role = aws_iam_role.price_watch.id
policy = data.aws_iam_policy_document.price_watch_inline.json
}
# CloudWatch Logs for the handler's print() lines (the same AWS managed policy the owner's
# existing Lambda/EventBridge price-tracker post attaches by hand with `aws iam attach-role-policy`).
resource "aws_iam_role_policy_attachment" "basic_execution" {
role = aws_iam_role.price_watch.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
# --- Function. ---
data "archive_file" "price_watch" {
type = "zip"
source_dir = "${path.module}/src"
output_path = "${path.module}/build/price_watch.zip"
}
resource "aws_lambda_function" "price_watch" {
function_name = "${var.name_prefix}-price-watch"
role = aws_iam_role.price_watch.arn
handler = "tracker.handler"
runtime = "python3.12"
timeout = var.lambda_timeout_seconds
memory_size = 256
filename = data.archive_file.price_watch.output_path
source_code_hash = data.archive_file.price_watch.output_base64sha256
environment {
variables = {
PRICE_TABLE = aws_dynamodb_table.prices.name
SNS_TOPIC_ARN = aws_sns_topic.price_drops.arn
API_KEY_SECRET_ARN = aws_secretsmanager_secret.sellermagnet_api_key.arn
# No SELLERMAGNET_API_KEY here: the bootstrap in tracker.py reads the secret above via
# boto3 at cold start and sets it in-process, so it is never written into a Lambda
# environment variable (visible in the console/CLI/any `terraform show`) or Terraform state.
}
}
}
# --- Schedule: aws_cloudwatch_event_rule + aws_cloudwatch_event_target (the classic rule/target
# pair), not an EventBridge Scheduler schedule. Unlike Scheduler (which invokes the function
# directly using its own RoleArn), a CloudWatch Events rule needs an explicit resource-based
# aws_lambda_permission grant before the rule is allowed to invoke the function at all. ---
resource "aws_cloudwatch_event_rule" "price_watch_schedule" {
name = "${var.name_prefix}-price-watch-schedule"
description = "Fires the Amazon price-watch Lambda on a fixed interval."
schedule_expression = var.schedule_expression
}
resource "aws_cloudwatch_event_target" "price_watch" {
rule = aws_cloudwatch_event_rule.price_watch_schedule.name
arn = aws_lambda_function.price_watch.arn
input = jsonencode({
asins = var.watched_asins
marketplaceId = var.marketplace_id
})
}
resource "aws_lambda_permission" "allow_eventbridge" {
statement_id = "AllowExecutionFromCloudWatchEvents"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.price_watch.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.price_watch_schedule.arn
}
variables.tf - no API-key variable on purpose
variable "aws_region" {
description = "AWS region to provision into."
type = string
default = "eu-central-1"
}
variable "name_prefix" {
description = "Prefix for every resource name/ARN this module creates."
type = string
default = "amazon-price-watch"
}
variable "schedule_expression" {
description = "CloudWatch Events schedule expression, e.g. rate(6 hours) or cron(0 */6 * * ? *)."
type = string
default = "rate(6 hours)"
}
variable "lambda_timeout_seconds" {
description = "Function timeout; size for the whole ASIN loop, not one call (see the post's callout)."
type = number
default = 240
}
variable "watched_asins" {
description = "ASINs the schedule passes to the function as its event payload."
type = list(string)
default = ["B0CL61F39H", "B0BVKV6SFV"]
}
variable "marketplace_id" {
description = "Amazon marketplace ID passed in the event payload."
type = string
default = "ATVPDKIKX0DER"
}
# Deliberately no "sellermagnet_api_key" variable: the key is never a plaintext Terraform
# variable (it would be stored in plaintext in the state/plan files). See
# aws_secretsmanager_secret.sellermagnet_api_key in main.tf.
| Resource | Provisions | Count |
|---|---|---|
| aws_secretsmanager_secret | container for the SellerMagnet API key | one, value set out-of-band |
| aws_dynamodb_table | last known Buy Box price per ASIN | one, PAY_PER_REQUEST |
| aws_sns_topic | fans a price drop out to email/SMS/HTTPS | one |
| aws_iam_role + aws_iam_role_policy | the function's execution role, least privilege | one role, one inline policy |
| aws_lambda_function | runs tracker.py on a schedule | one |
| aws_cloudwatch_event_rule + aws_cloudwatch_event_target | the schedule and its payload | one rule, one target |
| aws_lambda_permission | lets the rule invoke the function at all | one |


What does the Lambda handler itself look like?
tracker.py reuses the existing post's handler() and buy_box_price() functions unchanged, and still imports sellermagnet.py/retry.py from the Python quickstart unmodified. The only new code is _load_api_key(), which runs once at module import time (a Lambda cold start, not every invocation): it calls secretsmanager:GetSecretValue on the ARN the function's API_KEY_SECRET_ARN environment variable points at, then sets os.environ["SELLERMAGNET_API_KEY"] so sellermagnet.py's own new_session() keeps reading that same environment variable exactly as it always has. A warm invocation skips the Secrets Manager call entirely, because the `if "SELLERMAGNET_API_KEY" in os.environ" check short-circuits once the value is already cached in that execution environment.
tracker.py - handler/buy_box_price unchanged; only _load_api_key() is new
"""AWS Lambda handler: look up each ASIN, compare with DynamoDB, publish an SNS
message on a Buy Box price drop. Reuses the quickstart's sellermagnet.py / retry.py
(https://sellermagnet-api.com/blog/amazon-product-api-python) for the API call.
Terraform bootstrap (the only addition versus the plain Lambda/EventBridge price-tracker
post): the API key is never a Lambda environment variable or a Terraform variable. The
module instead provisions an aws_secretsmanager_secret and passes this function only its
ARN (API_KEY_SECRET_ARN); _load_api_key() reads the secret's current value via boto3 at
cold start and sets it into os.environ so sellermagnet.py's new_session() - unmodified -
can keep reading os.environ["SELLERMAGNET_API_KEY"] exactly as it already does in the
quickstart and the plain Lambda post.
"""
import os
from decimal import Decimal
import boto3
import requests
from retry import get_with_retry
from sellermagnet import ApiError, new_session
def _load_api_key() -> None:
"""Cold-start only: one GetSecretValue call, cached for the life of this execution
environment (Lambda re-runs this module-level code only on a cold start, not per
invocation), so a warm invocation never re-reads Secrets Manager."""
if "SELLERMAGNET_API_KEY" in os.environ:
return
secret = boto3.client("secretsmanager").get_secret_value(SecretId=os.environ["API_KEY_SECRET_ARN"])
os.environ["SELLERMAGNET_API_KEY"] = secret["SecretString"]
_load_api_key()
TABLE = boto3.resource("dynamodb").Table(os.environ["PRICE_TABLE"])
TOPIC_ARN = os.environ["SNS_TOPIC_ARN"]
sns = boto3.client("sns")
session = new_session()
def buy_box_price(asin, marketplace_id):
try:
data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=marketplace_id)
except ApiError as err:
print(f"{asin}: {err.status} {err}")
return None, err.status
except requests.RequestException as err: # connection/timeout survives retry.py's 4 attempts
print(f"{asin}: {type(err).__name__}")
return None, type(err).__name__
buy_box = data.get("buyBox") or {} # the featured offer; {} when nobody holds the Buy Box
price = buy_box.get("totalPrice")
# buyBox.totalPrice is not rounded by the API (item + shipping summed as floats): round before comparing
# or storing, or float noise (e.g. 19.009999999999998) can read as a price change that never happened.
return (round(price, 2) if isinstance(price, (int, float)) and price > 0 else None), None
def handler(event, context):
marketplace_id = event.get("marketplaceId", "ATVPDKIKX0DER")
asins = list(dict.fromkeys(event["asins"])) # dedupe: both copies would otherwise be billed
checked, dropped = 0, 0
for asin in asins:
price, err_status = buy_box_price(asin, marketplace_id)
if err_status == 401:
# free, but every remaining ASIN would fail the exact same way: stop the whole invocation early
# instead of sending a request for each one. Lambda retries this error twice by default (also free).
raise RuntimeError("API key rejected (401): stopping the whole invocation, not looping on it")
checked += 1
if price is None:
if isinstance(err_status, int):
label = f" (billed {err_status})" if err_status in (404, 502, 503) else f" (free {err_status})"
elif err_status:
label = f" (network error: {err_status})"
else:
label = ""
print(f"{asin}: no usable price this run{label}")
continue
item = TABLE.get_item(Key={"asin": asin}).get("Item")
before = item["price"] if item else None # Decimal (DynamoDB Number type), not a string
price_dec = Decimal(str(price)) # the API returns a float; DynamoDB Decimals cannot compare to float
is_drop = before is not None and price_dec < before
# Conditional write FIRST, alert only after it succeeds: publishing before the write let two
# overlapping invocations both alert on the same drop while only one write actually won.
# Price is stored as a DynamoDB Number (Decimal), never a string: a string comparison here would be
# exact and byte-sensitive (e.g. "89.5" != "89.50"), which a Number conditional check does not have.
condition = "attribute_not_exists(asin)" if item is None else "price = :before"
kwargs = {"Item": {"asin": asin, "price": price_dec}, "ConditionExpression": condition}
if item is not None:
kwargs["ExpressionAttributeValues"] = {":before": before}
try:
TABLE.put_item(**kwargs)
except TABLE.meta.client.exceptions.ConditionalCheckFailedException:
# another overlapping invocation already wrote a newer price: never alert on a value we lost
print(f"{asin}: baseline changed under us, skipping this write (ConditionalCheckFailedException)")
continue
if is_drop:
sns.publish(TopicArn=TOPIC_ARN, Subject=f"Price drop: {asin}",
Message=f"{asin}: {before:.2f} -> {price_dec:.2f}")
print(f"{asin}: {before:.2f} -> {price_dec:.2f}, SNS message published")
dropped += 1
else:
print(f"{asin}: {price_dec:.2f} USD -> no change" if before is not None
else f"{asin}: first price {price_dec:.2f}")
return {"checked": checked, "dropped": dropped}
Harness output (moto: DynamoDB, SNS, SQS, Secrets Manager; no real AWS account)
B0CL61F39H: first price 444.99 USD
B0BVKV6SFV: 89.50 -> 79.90 USD, SNS message published
Does terraform plan prove this actually deploys?
Not by itself. terraform plan "compares that desired state to the real infrastructure objects being managed" using the provider's own API, so even a read-only plan needs a working AWS credential chain; run with none configured, it fails on the provider's very first call (GetCallerIdentity) rather than silently reporting success. terraform validate" is the check that needs neither an account nor state: it only confirms the configuration is internally consistent - every argument present, every resource reference resolvable - entirely offline. This module was run through both, exactly as that split predicts: validate succeeded, and plan` failed closed on the missing AWS account, not on a configuration mistake.
Real output from this module (terraform 1.9.8, no AWS account configured)
$ terraform init -input=false
Terraform has been successfully initialized!
$ terraform validate
Success! The configuration is valid.
$ terraform plan -input=false
Error: Retrieving AWS account details: validating provider credentials:
retrieving caller identity from STS: operation error STS: GetCallerIdentity,
https response error StatusCode: 403, api error InvalidClientTokenId:
The security token included in the request is invalid.
aws_cloudwatch_event_target needs a matching aws_lambda_permission
Creating the rule and the target without the permission resource below does not fail apply - CloudWatch Events accepts the target either way. The first sign of the missing grant is that the schedule fires on time and nothing happens: no invocation shows up in the function's CloudWatch Logs at all, because the rule was never allowed to call it in the first place.
The permission grant the rule needs to invoke the function
resource "aws_lambda_permission" "allow_eventbridge" {
statement_id = "AllowExecutionFromCloudWatchEvents"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.price_watch.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.price_watch_schedule.arn
}
How is this different from the EventBridge Scheduler version of the same tracker?
The existing Lambda/EventBridge price-tracker post schedules the identical handler with EventBridge Scheduler: a single aws_scheduler_schedule-style resource that invokes the function directly using its own RoleArn, with no separate permission grant needed. The classic aws_cloudwatch_event_rule plus aws_cloudwatch_event_target pair used here is the older, still fully supported path, and it is the one that needs the extra aws_lambda_permission - a resource-based policy on the function itself, not a role the caller assumes. Either schedules the same unchanged handler; the module in this post is the one to reach for when an existing stack already standardises on CloudWatch Events rules rather than Scheduler schedules.
Frequently Asked Questions
Why does this module need an aws_lambda_permission resource at all?
Because aws_cloudwatch_event_target does not grant invoke rights by itself. Unlike an EventBridge Scheduler schedule, which carries its own RoleArn, a CloudWatch Events rule needs a separate resource-based policy statement on the function before events.amazonaws.com is allowed to call it; terraform apply succeeds without it, but the rule then fires into a silent AccessDenied with nothing in CloudWatch Logs.
Why is there no sellermagnet_api_key variable anywhere in this module?
A Terraform variable's value is written into the plan and state files in plain text by default. The module instead provisions only the aws_secretsmanager_secret container; the real value is set after apply (console or aws secretsmanager put-secret-value), and lifecycle.ignore_changes on the placeholder version stops that manual rotation from showing up as configuration drift on the next plan.
Does terraform plan prove this module actually works?
No. terraform plan only computes the diff between the configuration and the last-known state using the provider's API, so it still needs valid AWS credentials and a reachable account - it does not create anything either way. terraform validate is the offline check: syntax, references between resources, and required arguments, with no network call at all.
Why does tracker.py read the key from Secrets Manager instead of a Lambda environment variable?
A Lambda environment variable is visible to anyone who can read the function's configuration (console, CLI, or this module's own state file) and only changes on a redeploy. Reading the secret's current value via boto3 at cold start means the value can rotate in Secrets Manager without the function's configuration - or this module's state - ever holding it.
What would change if the SellerMagnet API key were rotated?
Only the secret's value in Secrets Manager, with no Terraform apply at all: a cold start after the rotation reads the new value, and a warm invocation keeps the one it already cached for that execution environment's lifetime.
Bottom line: provisioning a scheduled Amazon price-watch with Terraform does not need a different Lambda handler, only a module that wires the same tracker.py to aws_cloudwatch_event_rule/aws_cloudwatch_event_target with an explicit aws_lambda_permission, a least-privilege role scoped to the table, topic and secret this module itself creates, and a Secrets Manager container instead of a plaintext variable for the API key. The product offers page documents every field buy_box_price() reads, the Scheduler page covers calling the API on a schedule without running any AWS infrastructure at all, and a free account includes 150 credits to try the lookup this handler makes against real ASINs.