# Amazon Textract Resources (used in Lab 01: Vision) # Sets up SNS topics and IAM roles for async document processing. locals { enabled = var.enabled name_prefix = "${var.namespace}-${var.lab}-${var.stage}-${var.name}" } # SNS Topic for Textract async job notifications resource "aws_sns_topic" "textract" { count = local.enabled && var.create_sns_topic ? 1 : 0 name = "${local.name_prefix}-notifications" tags = merge(var.tags, { Name = "${local.name_prefix}-notifications" Lab = var.lab }) } # IAM Role for Textract to publish to SNS resource "aws_iam_role" "textract" { count = local.enabled && var.create_sns_topic ? 1 : 0 name = "${local.name_prefix}-textract-role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "textract.amazonaws.com" } } ] }) tags = merge(var.tags, { Name = "${local.name_prefix}-textract-role" Lab = var.lab }) } # Policy for Textract to publish to SNS resource "aws_iam_role_policy" "textract_sns" { count = local.enabled && var.create_sns_topic ? 1 : 0 name = "${local.name_prefix}-sns-publish" role = aws_iam_role.textract[0].id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = "sns:Publish" Resource = aws_sns_topic.textract[0].arn } ] }) } # Policy for Textract to access S3 resource "aws_iam_role_policy" "textract_s3" { # The role only exists when the SNS topic is created. count = local.enabled && var.create_sns_topic && var.s3_bucket_arn != null ? 1 : 0 name = "${local.name_prefix}-s3-access" role = aws_iam_role.textract[0].id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "s3:GetObject", "s3:GetObjectVersion" ] Resource = [ var.s3_bucket_arn, "${var.s3_bucket_arn}/*" ] } ] }) } # SQS Queue for processing results (optional) resource "aws_sqs_queue" "textract" { count = local.enabled && var.create_sqs_queue ? 1 : 0 name = "${local.name_prefix}-results" visibility_timeout_seconds = var.sqs_visibility_timeout message_retention_seconds = var.sqs_message_retention tags = merge(var.tags, { Name = "${local.name_prefix}-results" Lab = var.lab }) } # SNS to SQS subscription resource "aws_sns_topic_subscription" "textract_sqs" { count = local.enabled && var.create_sns_topic && var.create_sqs_queue ? 1 : 0 topic_arn = aws_sns_topic.textract[0].arn protocol = "sqs" endpoint = aws_sqs_queue.textract[0].arn } # SQS policy to allow SNS to send messages resource "aws_sqs_queue_policy" "textract" { count = local.enabled && var.create_sns_topic && var.create_sqs_queue ? 1 : 0 queue_url = aws_sqs_queue.textract[0].id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Principal = { Service = "sns.amazonaws.com" } Action = "sqs:SendMessage" Resource = aws_sqs_queue.textract[0].arn Condition = { ArnEquals = { "aws:SourceArn" = aws_sns_topic.textract[0].arn } } } ] }) }