ステップ 6 / 6 - 約 60 分
Lab 06 - Integrated pipeline with Lambda
An S3-triggered AWS Lambda function that routes uploaded files to the right AWS AI service and writes the results back to S3.
Time: about 60 minutes.
Overview
In this lab you deploy one stack that combines the services from Labs 01-03 with a Lambda orchestrator:
- You upload a file to a folder under
input/in the lab bucket. - S3 invokes the Lambda function
for every new object under
input/. - The function looks at the folder, calls one AI service for that file,
and writes a JSON result under
output/.
The handler is
components/terraform/lambda/src/index.py.
Terraform zips it at plan time (data.archive_file), so there is no separate
build step. Each file goes to one service; the function does not chain
services together. Chaining is an exercise at the end of this guide.
What the function does
| Upload to | Service call | Result written to |
|---|---|---|
input/images/ |
Rekognition DetectLabels (up to 10) and DetectFaces |
output/vision/<basename>.json |
input/documents/ |
Textract DetectDocumentText (synchronous) |
output/vision/<basename>.json |
input/text/ |
Comprehend DetectSentiment and DetectKeyPhrases (first 5,000 bytes) |
output/language/<basename>.json |
input/audio/ |
Transcribe StartTranscriptionJob (asynchronous, en-US) |
output/speech/orchestrator-<timestamp>-<hex>.json, written by Transcribe when the job finishes |
<basename> is the file name without its extension: input/images/cat.jpg
becomes output/vision/cat.json. Images and documents both write to
output/vision/, so give them different base names. Empty files, folder
markers, and files in other folders under input/ are skipped.
What gets created
<account-id> is your 12-digit AWS account ID.
| Component | Resources |
|---|---|
s3-bucket |
Bucket ai-06-integrated-test-integrated-data-<account-id> with input/images/, input/documents/, input/audio/, input/text/, output/vision/, output/language/, output/speech/ |
iam-role |
Role ai-06-integrated-test-integrated-services, trusted by Lambda, with Rekognition, Textract, Comprehend, Transcribe, Polly, Translate, CloudWatch Logs, and S3 access to the lab bucket |
lambda |
Function ai-06-integrated-test-ai-orchestrator (Python 3.12, 1024 MB, 300 s timeout), log group /aws/lambda/ai-06-integrated-test-ai-orchestrator, S3 invoke permission, and the bucket notification for input/ |
rekognition |
Collection ai-06-integrated-test-rekognition and an SNS topic |
textract |
SNS topic, SQS queue, and the role Textract uses to publish |
comprehend |
Role for Comprehend async jobs |
translate |
Role for Translate batch jobs |
transcribe |
Custom vocabulary ai-06-integrated-test-transcribe-vocabulary and a role for Transcribe |
polly |
Lexicon ai06integratedtest |
The function calls the service APIs directly and does not use the collection, SNS/SQS, vocabulary, or lexicon. Those components are in the stack so you can repeat the Lab 01-03 CLI exercises against the same bucket. They are optional: you can skip them and the pipeline still works.
Architecture
+---------------------------------------------------------------+
| S3 bucket |
| input/images/ input/documents/ input/text/ input/audio/ |
+-------------------------------+-------------------------------+
| s3:ObjectCreated:* on input/
v
+---------------------------------------------------------------+
| Lambda: ai-06-integrated-test-ai-orchestrator |
| 1. read the folder from the S3 key |
| 2. call one AI service for that folder |
| 3. write the JSON result to output/ |
+------+--------------+-----------------+--------------+--------+
| | | |
v v v v
+-------------+ +-------------+ +---------------+ +-----------------+
| Rekognition | | Textract | | Comprehend | | Transcribe |
| labels, | | document | | sentiment, | | async job |
| faces | | text | | key phrases | | |
+------+------+ +------+------+ +-------+-------+ +--------+--------+
| | | |
v v v v
+---------------------------------------------------------------+
| output/vision/ output/vision/ output/language/ |
| output/speech/ (Transcribe)|
+---------------------------------------------------------------+Before you start
- Complete the Prerequisites in the README.
- Have test files in the lab folder:
sample-image.jpg,sample-document.pdf(one page), andsample-audio.mp3(Lab 03 shows how to make one with Polly).
Deploy
The stack stacks/labs/06-integrated/test.yaml wires outputs between
components with
!terraform.output:
iam-role reads the bucket ARN, and lambda reads the role ARN and the
bucket name and ARN. Atmos reads those values from the state of the other
components when it plans lambda, so they must be applied first (see
Connecting Components).
Apply in this order:
cd atmos-aws-ai-infra # the lab folder
# Check the stack (YAML functions off: nothing is applied yet)
atmos validate stacks
atmos describe stacks -s lab-06-integrated-test --process-functions=false
# 1. Bucket, then the role that reads its ARN
atmos terraform apply s3-bucket -s lab-06-integrated-test
atmos terraform apply iam-role -s lab-06-integrated-test
# 2. Optional service components (any order)
atmos terraform apply rekognition -s lab-06-integrated-test
atmos terraform apply textract -s lab-06-integrated-test
atmos terraform apply comprehend -s lab-06-integrated-test
atmos terraform apply translate -s lab-06-integrated-test
atmos terraform apply transcribe -s lab-06-integrated-test
atmos terraform apply polly -s lab-06-integrated-test
# 3. The Lambda function last
atmos terraform apply lambda -s lab-06-integrated-testSet shell variables
STACK=lab-06-integrated-test
BUCKET=$(atmos terraform output s3-bucket -s $STACK --skip-init -- -raw bucket_id)
FUNCTION=$(atmos terraform output lambda -s $STACK --skip-init -- -raw function_name)
LOG_GROUP=$(atmos terraform output lambda -s $STACK --skip-init -- -raw log_group_name)
echo "$BUCKET $FUNCTION"Keep the function's log open in a second terminal while you test:
aws logs tail "$LOG_GROUP" --follow --region us-east-1Test
The function usually finishes within a few seconds of the upload. If a result is not there yet, wait a moment and list the folder again.
Image
aws s3 cp sample-image.jpg "s3://$BUCKET/input/images/"
aws s3 ls "s3://$BUCKET/output/vision/"
aws s3 cp "s3://$BUCKET/output/vision/sample-image.json" - | jq '{source, labels: [.labels[].Name], faces: (.faces | length), timestamp}'The file has source, labels (Rekognition label objects), faces
(face details with the default attributes), and timestamp.
Document
aws s3 cp sample-document.pdf "s3://$BUCKET/input/documents/"
aws s3 cp "s3://$BUCKET/output/vision/sample-document.json" - | jq -r '.text'The result has source, text (all detected lines), block_count, and
timestamp. The synchronous Textract API accepts JPEG, PNG, TIFF, and
single-page PDF files; a multi-page PDF fails (see the log).
Text
echo "This is a great product! I love using AWS AI services. The documentation is excellent and easy to follow." > sample-text.txt
aws s3 cp sample-text.txt "s3://$BUCKET/input/text/"
aws s3 cp "s3://$BUCKET/output/language/sample-text.json" - | jq '{sentiment: .sentiment.Sentiment, key_phrases: [.key_phrases[].Text]}'The function reads only the first 5,000 bytes of a text file, the
per-request limit of Comprehend DetectSentiment, and assumes English.
Audio
aws s3 cp sample-audio.mp3 "s3://$BUCKET/input/audio/"
# The function starts a job named orchestrator-<timestamp>-<hex>
aws transcribe list-transcription-jobs \
--job-name-contains orchestrator \
--region us-east-1 \
--query 'TranscriptionJobSummaries[].[TranscriptionJobName,TranscriptionJobStatus]' \
--output tableWhen the job is COMPLETED, Transcribe has written the transcript to
output/speech/<job-name>.json:
aws s3 ls "s3://$BUCKET/output/speech/"
JOB=$(aws transcribe list-transcription-jobs --job-name-contains orchestrator \
--region us-east-1 --query 'TranscriptionJobSummaries[0].TranscriptionJobName' --output text)
aws s3 cp "s3://$BUCKET/output/speech/$JOB.json" - | jq -r '.results.transcripts[0].transcript'The function picks the media format from the file extension (mp3, mp4, wav, flac, ogg, amr, webm, m4a) and falls back to mp3.
Several files at once
mkdir -p test-files/images test-files/text
cp sample-image.jpg test-files/images/photo2.jpg
echo "The support team was slow and unhelpful." > test-files/text/review2.txt
aws s3 cp test-files/ "s3://$BUCKET/input/" --recursive
aws s3 ls "s3://$BUCKET/output/" --recursiveS3 invokes the function once per object.
Monitoring
# Recent log lines and errors
aws logs tail "$LOG_GROUP" --since 1h --region us-east-1
aws logs filter-log-events \
--log-group-name "$LOG_GROUP" \
--filter-pattern "ERROR" \
--region us-east-1 \
--query 'events[].message'
# Invocations in the last hour (works with GNU date on Linux and BSD date on macOS)
START=$(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name Invocations \
--dimensions Name=FunctionName,Value="$FUNCTION" \
--start-time "$START" --end-time "$END" \
--period 300 --statistics Sum \
--region us-east-1Try --metric-name Errors and --metric-name Duration (with
--statistics Average) as well.
How the Terraform fits together
lambdausesrole_arn: !terraform.output iam-role role_arn, so the function runs with the least-privilege role fromiam-roleinstead of a default role.iam-roleusess3_bucket_arns: [!terraform.output s3-bucket bucket_arn], so the role can read the uploads and write the results (Rekognition, Textract, and Transcribe read S3 with the caller's permissions).- A precondition in the
lambdacomponent stops the apply if the S3 trigger is on but no role was passed in. - The function
depends_onits log group, so the group exists before the first invocation and is deleted only after the function is gone. aws_s3_bucket_notificationreplaces any existing notification configuration on the bucket. Only thelambdacomponent manages it here.
Run atmos describe component lambda -s lab-06-integrated-test after the
apply to see the values Atmos resolved
(describe component).
Cleanup
Destroy lambda first (it removes the bucket notification), then the rest
in reverse order:
atmos terraform destroy lambda -s lab-06-integrated-test
atmos terraform destroy polly -s lab-06-integrated-test
atmos terraform destroy transcribe -s lab-06-integrated-test
atmos terraform destroy translate -s lab-06-integrated-test
atmos terraform destroy comprehend -s lab-06-integrated-test
atmos terraform destroy textract -s lab-06-integrated-test
atmos terraform destroy rekognition -s lab-06-integrated-test
atmos terraform destroy iam-role -s lab-06-integrated-test
atmos terraform destroy s3-bucket -s lab-06-integrated-testSkip any optional component you did not apply. Then delete the transcription jobs the function started, and your local test files:
for j in $(aws transcribe list-transcription-jobs --job-name-contains orchestrator \
--region us-east-1 --query 'TranscriptionJobSummaries[].TranscriptionJobName' --output text); do
aws transcribe delete-transcription-job --transcription-job-name "$j" --region us-east-1
done
rm -rf test-files sample-text.txtTroubleshooting
- No output file - check the log (
aws logs tail "$LOG_GROUP"). The function logsprocessing failed for s3://...with the error for each file it could not handle. - AccessDenied in the log - the
iam-rolewas applied befores3-bucket, or with an old bucket ARN. Applyiam-roleagain, thenlambda. lambdaplan fails reading!terraform.output- applys3-bucketandiam-rolein this stack first.- UnsupportedDocumentException for a PDF - the synchronous Textract API takes one page. Use a single-page PDF or an image.
- The function runs twice for one file - S3 delivers events at least once. The function is safe to rerun: results overwrite the same key, and each Transcribe job gets a unique name.
Cost
You pay for each service call the function makes (per image, page, text unit, or audio second), for Lambda requests and duration, and for S3 storage and requests. A few test files cost very little, but an upload loop or a large batch adds up. See the pricing pages of Lambda, Rekognition, Textract, Comprehend, and Transcribe. Free Tier terms depend on your account; see AWS Free Tier.
Next steps
- Previous: Lab 05 - Generative AI: Bedrock and guardrails
- Back to the lab overview.
- Extend
index.py(and the IAM role) to chain services: translate the Textract text with Translate, run Comprehend on a finished transcript, or summarize results with Bedrock (addbedrock_enabled: truetoiam-role). - Add a dead-letter queue or Lambda destinations for failed events, or move multi-step processing to AWS Step Functions.
Atmos docs
- Connecting Components - passing outputs from
s3-bucketandiam-roleintolambda. - !terraform.output reference - the syntax used in this stack, and why the source component must be applied first.
- atmos describe component - see the resolved
role_arnand bucket values. - atmos terraform - the apply and destroy commands, in dependency order.
- State Backends - this lab keeps local state; use a remote backend for shared pipelines.
Exam connection
This lab practices:
- AIF-C01, Fundamentals of AI and ML - matching each input type (image, document, text, audio) to the managed AI service that handles it.
- AIF-C01, Security, Compliance, and Governance for AI Solutions - a least-privilege execution role scoped to one bucket, and CloudWatch logs for auditing what the pipeline did.
- MLA-C01, Deployment and Orchestration of ML Workflows - event-driven orchestration with S3 events and Lambda, deployed with infrastructure as code.
- MLA-C01, ML Solution Monitoring, Maintenance, and Security - CloudWatch logs and Lambda metrics (invocations, errors, duration), and IAM for the pipeline.
- Terraform Associate (004), Implement and Maintain State - reading outputs from the state of separately applied configurations, and the apply and destroy order that this creates.
- Terraform Associate (004), Read, Generate, and Modify Configuration -
data sources such as
archive_file, variable validation, lifecycle preconditions, anddepends_on.
Related certification pages: AIF-C01, MLA-C01, Terraform Associate (004).
Practice exam-style questions on these topics on CertLabPro: on the web at https://certlabpro.com/cert/aws-mla-c01, or in the app: https://certlabpro.com/mobile.