components/terraform/bedrock/main.tf
17 KB - 元のファイルを表示
# Amazon Bedrock Resources (used in Lab 05: GenAI)
# Sets up a guardrail, optional model invocation logging, and an optional
# Knowledge Base backed by OpenSearch Serverless.
# Account/region lookups - used for the KB confused-deputy guards, the
# account-unique bucket name, and to default the embedding model ARN to
# whatever region the stack runs in.
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
locals {
enabled = var.enabled
name_prefix = "${var.namespace}-${var.lab}-${var.stage}-${var.name}"
# Resolve the embedding model ARN against the live region so we don't pin
# users to us-east-1 when the stack deploys elsewhere. Titan Text
# Embeddings V2 returns 1024-dimension vectors by default; the vector index
# you create for the Knowledge Base must use the same dimension.
resolved_embedding_model_arn = var.embedding_model_arn != null ? var.embedding_model_arn : "arn:aws:bedrock:${data.aws_region.current.name}::foundation-model/amazon.titan-embed-text-v2:0"
# Principals allowed to use the OpenSearch Serverless collection. The
# caller ARN works for IAM users and roles; for SSO or other assumed-role
# sessions set var.kb_admin_principal_arns to the IAM role ARN instead.
kb_admin_principals = length(var.kb_admin_principal_arns) > 0 ? var.kb_admin_principal_arns : [data.aws_caller_identity.current.arn]
# The Knowledge Base itself needs a vector index that Terraform does not
# create (see the Lab 05 guide). It is only created once you set
# knowledge_base_index_ready = true after creating the index.
create_kb_resource = local.enabled && var.create_knowledge_base && var.knowledge_base_index_ready
}
# IAM Role for Bedrock service operations
resource "aws_iam_role" "bedrock" {
count = local.enabled ? 1 : 0
name = "${local.name_prefix}-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "bedrock.amazonaws.com"
}
}
]
})
tags = merge(var.tags, {
Name = "${local.name_prefix}-role"
Lab = var.lab
})
}
# Policy for Bedrock to access S3 (for Knowledge Base)
resource "aws_iam_role_policy" "bedrock_s3" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.name_prefix}-s3-access"
role = aws_iam_role.bedrock[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:ListBucket"
]
Resource = var.data_source_bucket_arn != null ? [
var.data_source_bucket_arn,
"${var.data_source_bucket_arn}/*"
] : ["*"]
}
]
})
}
# Policy for Bedrock to invoke foundation models
resource "aws_iam_role_policy" "bedrock_models" {
count = local.enabled ? 1 : 0
name = "${local.name_prefix}-model-access"
role = aws_iam_role.bedrock[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
]
Resource = "arn:aws:bedrock:*::foundation-model/*"
}
]
})
}
# Bedrock Guardrail for content filtering
resource "aws_bedrock_guardrail" "this" {
count = local.enabled && var.create_guardrail ? 1 : 0
name = replace(local.name_prefix, "-", "_")
description = "Content guardrail for AI Lab exercises"
blocked_input_messaging = var.guardrail_blocked_input_message
blocked_outputs_messaging = var.guardrail_blocked_output_message
content_policy_config {
filters_config {
type = "HATE"
input_strength = var.content_filter_config.hate_input_strength
output_strength = var.content_filter_config.hate_output_strength
}
filters_config {
type = "INSULTS"
input_strength = var.content_filter_config.insults_input_strength
output_strength = var.content_filter_config.insults_output_strength
}
filters_config {
type = "SEXUAL"
input_strength = var.content_filter_config.sexual_input_strength
output_strength = var.content_filter_config.sexual_output_strength
}
filters_config {
type = "VIOLENCE"
input_strength = var.content_filter_config.violence_input_strength
output_strength = var.content_filter_config.violence_output_strength
}
filters_config {
type = "MISCONDUCT"
input_strength = var.content_filter_config.misconduct_input_strength
output_strength = var.content_filter_config.misconduct_output_strength
}
}
tags = merge(var.tags, {
Name = local.name_prefix
Lab = var.lab
})
}
# Numbered guardrail version. Bedrock's runtime APIs require an explicit
# version (or the literal "DRAFT"); creating a numbered version here lets
# callers reference a stable identifier instead of always using DRAFT.
resource "aws_bedrock_guardrail_version" "this" {
count = local.enabled && var.create_guardrail ? 1 : 0
guardrail_arn = aws_bedrock_guardrail.this[0].guardrail_arn
description = "Initial published version"
}
# CloudWatch Log Group for model invocation logging
resource "aws_cloudwatch_log_group" "bedrock" {
count = local.enabled && var.enable_model_invocation_logging ? 1 : 0
name = "/aws/bedrock/${local.name_prefix}"
retention_in_days = var.log_retention_days
tags = merge(var.tags, {
Name = "${local.name_prefix}-logs"
Lab = var.lab
})
}
# IAM role that lets Bedrock write to the log group above.
resource "aws_iam_role" "bedrock_logging" {
count = local.enabled && var.enable_model_invocation_logging ? 1 : 0
name = "${local.name_prefix}-logging"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "sts:AssumeRole"
Principal = {
Service = "bedrock.amazonaws.com"
}
Condition = {
StringEquals = {
"aws:SourceAccount" = data.aws_caller_identity.current.account_id
}
}
}]
})
tags = merge(var.tags, {
Name = "${local.name_prefix}-logging"
Lab = var.lab
})
}
resource "aws_iam_role_policy" "bedrock_logging" {
count = local.enabled && var.enable_model_invocation_logging ? 1 : 0
name = "${local.name_prefix}-logging"
role = aws_iam_role.bedrock_logging[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = [
"logs:CreateLogStream",
"logs:PutLogEvents",
]
Resource = "${aws_cloudwatch_log_group.bedrock[0].arn}:*"
}]
})
}
# Account-level Bedrock model invocation logging. This is a singleton per
# account and region: it logs the prompts and responses of EVERY model call in
# the region, not only this lab's calls. It is off by default; turn it on only
# in an account where that is acceptable, and destroy it after the lab.
resource "aws_bedrock_model_invocation_logging_configuration" "this" {
count = local.enabled && var.enable_model_invocation_logging ? 1 : 0
logging_config {
embedding_data_delivery_enabled = true
image_data_delivery_enabled = true
text_data_delivery_enabled = true
cloudwatch_config {
log_group_name = aws_cloudwatch_log_group.bedrock[0].name
role_arn = aws_iam_role.bedrock_logging[0].arn
}
}
depends_on = [aws_iam_role_policy.bedrock_logging]
}
# S3 bucket for Knowledge Base documents (optional)
resource "aws_s3_bucket" "kb_data" {
count = local.enabled && var.create_s3_data_source ? 1 : 0
# S3 bucket names are global, so the name ends with the account ID.
bucket = "${local.name_prefix}-kb-data-${data.aws_caller_identity.current.account_id}"
force_destroy = true
tags = merge(var.tags, {
Name = "${local.name_prefix}-kb-data"
Lab = var.lab
})
}
resource "aws_s3_bucket_server_side_encryption_configuration" "kb_data" {
count = local.enabled && var.create_s3_data_source ? 1 : 0
bucket = aws_s3_bucket.kb_data[0].id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_public_access_block" "kb_data" {
count = local.enabled && var.create_s3_data_source ? 1 : 0
bucket = aws_s3_bucket.kb_data[0].id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# =============================================================================
# OpenSearch Serverless Collection (Vector Store for Knowledge Base)
# =============================================================================
locals {
opensearch_collection_name = var.opensearch_collection_name != null ? var.opensearch_collection_name : "${local.name_prefix}-kb"
# OpenSearch collection names must be lowercase and can only contain alphanumeric and hyphens
opensearch_collection_name_sanitized = lower(replace(local.opensearch_collection_name, "_", "-"))
# OpenSearch Serverless policy names are limited to 32 characters, so the
# prefix is trimmed to leave room for the 4-character "-enc", "-net", and
# "-acc" suffixes. With the default name ("ai-05-genai-test-bedrock-kb")
# "-access" would make the data access policy name 34 characters long.
aoss_policy_prefix = substr(local.opensearch_collection_name_sanitized, 0, 28)
}
# OpenSearch Serverless encryption policy (required before collection)
resource "aws_opensearchserverless_security_policy" "encryption" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.aoss_policy_prefix}-enc"
type = "encryption"
policy = jsonencode({
Rules = [
{
Resource = ["collection/${local.opensearch_collection_name_sanitized}"]
ResourceType = "collection"
}
]
AWSOwnedKey = true
})
}
# OpenSearch Serverless network policy (required before collection)
resource "aws_opensearchserverless_security_policy" "network" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.aoss_policy_prefix}-net"
type = "network"
policy = jsonencode([
{
Rules = [
{
Resource = ["collection/${local.opensearch_collection_name_sanitized}"]
ResourceType = "collection"
}
]
AllowFromPublic = true
}
])
}
# OpenSearch Serverless collection for vector storage
resource "aws_opensearchserverless_collection" "kb" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = local.opensearch_collection_name_sanitized
description = "Vector store for ${var.knowledge_base_name}"
type = "VECTORSEARCH"
standby_replicas = var.opensearch_standby_replicas
depends_on = [
aws_opensearchserverless_security_policy.encryption,
aws_opensearchserverless_security_policy.network
]
tags = merge(var.tags, {
Name = local.opensearch_collection_name_sanitized
Lab = var.lab
})
}
# OpenSearch Serverless data access policy
resource "aws_opensearchserverless_access_policy" "kb" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.aoss_policy_prefix}-acc"
type = "data"
policy = jsonencode([
{
Rules = [
{
Resource = ["collection/${local.opensearch_collection_name_sanitized}"]
ResourceType = "collection"
Permission = [
"aoss:CreateCollectionItems",
"aoss:DeleteCollectionItems",
"aoss:UpdateCollectionItems",
"aoss:DescribeCollectionItems"
]
},
{
Resource = ["index/${local.opensearch_collection_name_sanitized}/*"]
ResourceType = "index"
Permission = [
"aoss:CreateIndex",
"aoss:DeleteIndex",
"aoss:UpdateIndex",
"aoss:DescribeIndex",
"aoss:ReadDocument",
"aoss:WriteDocument"
]
}
]
Principal = concat(
[aws_iam_role.bedrock_kb[0].arn],
local.kb_admin_principals
)
}
])
}
# =============================================================================
# IAM Role for Knowledge Base
# =============================================================================
resource "aws_iam_role" "bedrock_kb" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.name_prefix}-kb-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "bedrock.amazonaws.com"
}
Condition = {
StringEquals = {
"aws:SourceAccount" = data.aws_caller_identity.current.account_id
}
ArnLike = {
"aws:SourceArn" = "arn:aws:bedrock:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:knowledge-base/*"
}
}
}
]
})
tags = merge(var.tags, {
Name = "${local.name_prefix}-kb-role"
Lab = var.lab
})
}
# Policy for Knowledge Base to access OpenSearch Serverless
resource "aws_iam_role_policy" "bedrock_kb_aoss" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.name_prefix}-kb-aoss"
role = aws_iam_role.bedrock_kb[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"aoss:APIAccessAll"
]
Resource = aws_opensearchserverless_collection.kb[0].arn
}
]
})
}
# Policy for Knowledge Base to access S3
resource "aws_iam_role_policy" "bedrock_kb_s3" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.name_prefix}-kb-s3"
role = aws_iam_role.bedrock_kb[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:ListBucket"
]
Resource = var.create_s3_data_source ? [
aws_s3_bucket.kb_data[0].arn,
"${aws_s3_bucket.kb_data[0].arn}/*"
] : var.data_source_bucket_arn != null ? [
var.data_source_bucket_arn,
"${var.data_source_bucket_arn}/*"
] : ["arn:aws:s3:::*"]
}
]
})
}
# Policy for Knowledge Base to invoke embedding model
resource "aws_iam_role_policy" "bedrock_kb_model" {
count = local.enabled && var.create_knowledge_base ? 1 : 0
name = "${local.name_prefix}-kb-model"
role = aws_iam_role.bedrock_kb[0].id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"bedrock:InvokeModel"
]
Resource = local.resolved_embedding_model_arn
}
]
})
}
# =============================================================================
# Bedrock Knowledge Base
# =============================================================================
# Created only after the vector index exists (knowledge_base_index_ready).
# CreateKnowledgeBase fails if the index named below is missing.
resource "aws_bedrockagent_knowledge_base" "this" {
count = local.create_kb_resource ? 1 : 0
name = var.knowledge_base_name
description = var.knowledge_base_description
role_arn = aws_iam_role.bedrock_kb[0].arn
knowledge_base_configuration {
type = "VECTOR"
vector_knowledge_base_configuration {
embedding_model_arn = local.resolved_embedding_model_arn
}
}
storage_configuration {
type = "OPENSEARCH_SERVERLESS"
opensearch_serverless_configuration {
collection_arn = aws_opensearchserverless_collection.kb[0].arn
vector_index_name = var.kb_vector_index_name
field_mapping {
metadata_field = "AMAZON_BEDROCK_METADATA"
text_field = "AMAZON_BEDROCK_TEXT_CHUNK"
vector_field = var.kb_vector_field_name
}
}
}
depends_on = [
aws_opensearchserverless_access_policy.kb,
aws_iam_role_policy.bedrock_kb_aoss,
aws_iam_role_policy.bedrock_kb_s3,
aws_iam_role_policy.bedrock_kb_model
]
tags = merge(var.tags, {
Name = var.knowledge_base_name
Lab = var.lab
})
}
# =============================================================================
# Knowledge Base Data Source (S3)
# =============================================================================
resource "aws_bedrockagent_data_source" "s3" {
count = local.create_kb_resource && (var.create_s3_data_source || var.data_source_bucket_arn != null) ? 1 : 0
name = "${local.name_prefix}-s3-source"
knowledge_base_id = aws_bedrockagent_knowledge_base.this[0].id
data_deletion_policy = "DELETE"
data_source_configuration {
type = "S3"
s3_configuration {
bucket_arn = var.create_s3_data_source ? aws_s3_bucket.kb_data[0].arn : var.data_source_bucket_arn
inclusion_prefixes = length(var.data_source_inclusion_prefixes) > 0 ? var.data_source_inclusion_prefixes : null
}
}
vector_ingestion_configuration {
chunking_configuration {
chunking_strategy = var.chunking_strategy
dynamic "fixed_size_chunking_configuration" {
for_each = var.chunking_strategy == "FIXED_SIZE" ? [1] : []
content {
max_tokens = var.chunk_max_tokens
overlap_percentage = var.chunk_overlap_percentage
}
}
}
}
}