Terraform for Amazon Bedrock in a Closed Network: Endpoints, Policies, Logging, Offline Apply
Build a closed-network Bedrock environment by hand in the console once, and you are left with a problem: when you repeat the work in a second account, you cannot tell what you missed. One endpoint, one security group rule, or one KMS key on a log group is enough to change the outcome of a security review. This article moves the setup built by hand in Part 1 into Terraform modules. It also covers how to run Terraform itself where there is no internet, and a CI check that fails the pipeline the moment an internet path appears.
Field notes · Terraform · Amazon Bedrock · Closed network · IaC
The reasons behind the setup and what each control does are covered in Using Amazon Bedrock in a closed network (Part 1). This article focuses on turning that setup into code.

Decide first: what goes into code, and what stays outside
Put everything in one state file and a single mistake has a wide blast radius. Split things that change at different speeds and have different owners.
- Built as code in this article: the workload VPC, endpoints and their policies, the application role, invocation logging and its KMS key.
- Owned by other stacks or teams: Direct Connect and Transit Gateway, corporate DNS forwarding, SCPs. Here they come in only as input variables, such as the corporate CIDR ranges.
- Versions: the examples assume Terraform 1.10 or later and AWS provider v5. Some arguments and attributes changed in v6, so check the upgrade guide before you move up.
Module layout
Use one root module per environment and one child module per function. Modules talk to each other only through outputs.
envs/
prod/ main.tf versions.tf backend.tf prod.tfvars
modules/
network/ # VPC, private subnets, route tables (no IGW or NAT)
endpoints/ # interface endpoints (for_each), S3 gateway, endpoint policies
iam/ # application role: approved models only, deny calls outside the endpoints
logging/ # KMS key, log group, Bedrock logging role, invocation logging config
Dependencies run in one line, network → endpoints → iam, and logging stands alone. The order follows from iam needing the endpoint IDs to use the aws:SourceVpce condition.
Step 1: the network module, a VPC without internet
The point is what is missing. Do not create aws_internet_gateway, aws_nat_gateway, or a 0.0.0.0/0 route. Instead, always turn on the VPC's two DNS attributes so private DNS works for interface endpoints. If either one is off, endpoint creation fails.
resource "aws_vpc" "this" {
cidr_block = var.cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = var.name }
}
resource "aws_subnet" "private" {
for_each = var.subnets # { "ap-northeast-2a" = "10.20.1.0/24", ... }
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = each.value
}
resource "aws_route_table" "private" {
vpc_id = aws_vpc.this.id
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}
# Strip every rule from the VPC default security group (declared with no rule blocks)
resource "aws_default_security_group" "this" {
vpc_id = aws_vpc.this.id
}
Add the path to the corporate network separately, as an aws_route that sends only corporate ranges to the Transit Gateway. The outputs are vpc_id, vpc_cidr, the list of subnet IDs ([for s in aws_subnet.private : s.id]), and the list of route table IDs.
Step 2: the endpoints module, stamping out endpoints with for_each
Endpoints differ only by service name, so manage them from one list. The security group allows only inbound TCP 443 from the VPC range and the corporate ranges.
variable "interface_services" {
type = list(string)
default = ["bedrock-runtime", "bedrock", "sts", "logs", "kms"]
}
resource "aws_security_group" "endpoints" {
name_prefix = "vpce-"
description = "HTTPS to VPC endpoints"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "https" {
for_each = toset(var.allowed_cidrs) # VPC range + corporate ranges
security_group_id = aws_security_group.endpoints.id
cidr_ipv4 = each.key
ip_protocol = "tcp"
from_port = 443
to_port = 443
}
resource "aws_vpc_endpoint" "interface" {
for_each = toset(var.interface_services)
vpc_id = var.vpc_id
service_name = "com.amazonaws.${var.region}.${each.key}"
vpc_endpoint_type = "Interface"
subnet_ids = var.subnet_ids
security_group_ids = [aws_security_group.endpoints.id]
private_dns_enabled = true
policy = each.key == "bedrock-runtime" ? data.aws_iam_policy_document.runtime.json : null
tags = { Name = "vpce-${each.key}" }
}
resource "aws_vpc_endpoint" "s3" {
vpc_id = var.vpc_id
service_name = "com.amazonaws.${var.region}.s3"
vpc_endpoint_type = "Gateway"
route_table_ids = var.route_table_ids
}
The security group has no egress rules on purpose. AWS adds an allow-all egress rule to every new security group, but Terraform's aws_security_group deletes that default rule right after creation. An endpoint ENI only has to answer incoming connections, and security groups are stateful, so it works without egress.
Field tip: Do the same thing with count = length(var.interface_services) and the resources are keyed by index. Remove bedrock from the middle of the list and the sts, logs and kms endpoints after it all shift by one and get replaced, so calls to those services break during the apply. With for_each = toset(...) the service name is the key, so only the one you removed is deleted. If the plan shows must be replaced on an endpoint, stop and find out why first.
Export the output as a map keyed by service name, such as { for k, v in aws_vpc_endpoint.interface : k => v.id }, and the root module can pick IDs by name, as in endpoint_ids["bedrock-runtime"].
Step 3: take the endpoint policy as a variable
The approved-model list changes with every security review, so it lives in a variables file, not in code. Add validation so a malformed value is stopped before the plan.
variable "approved_model_arns" {
type = list(string)
validation {
condition = alltrue([for a in var.approved_model_arns : startswith(a, "arn:aws:bedrock:")])
error_message = "Only Bedrock model ARNs are allowed."
}
}
data "aws_iam_policy_document" "runtime" {
statement {
effect = "Allow"
actions = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]
resources = var.approved_model_arns
principals {
type = "*"
identifiers = ["*"]
}
}
}
A foundation model ARN has the form arn:aws:bedrock:<region>::foundation-model/<model-id>, with the account ID field left empty. If you call a model through an inference profile, you must allow the profile ARN too, and a cross-Region profile also involves the model ARNs in every Region that may serve the request. Test allow and deny with the call pattern you actually use before you lock in the list.
Going deeper: what people miss when adding aws:SourceVpce in the iam module
The application role gets an allow for approved models, plus "deny bedrock:* if aws:SourceVpce is not one of our endpoints." If you put only the bedrock-runtime endpoint ID in that value, the same role is also denied on calls that go through the bedrock (control plane) or bedrock-agent-runtime endpoints, because each endpoint has its own ID. Collect every Bedrock-family endpoint ID from the map output in Step 2 and pass them all as the condition value. This condition also blocks test calls from the console, so do not put human roles and application roles under the same policy.
Step 4: the logging module, KMS key and invocation logging
The AWS provider has an aws_bedrock_model_invocation_logging_configuration resource, so invocation logging can be turned on in code too. The order is: KMS key, log group, the role Bedrock assumes, then the logging configuration.
data "aws_iam_policy_document" "kms" {
statement {
sid = "AccountAdmin"
actions = ["kms:*"]
resources = ["*"]
principals {
type = "AWS"
identifiers = ["arn:aws:iam::${local.account_id}:root"]
}
}
statement {
sid = "CloudWatchLogs"
actions = ["kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*"]
resources = ["*"]
principals {
type = "Service"
identifiers = ["logs.${var.region}.amazonaws.com"]
}
condition {
test = "ArnLike"
variable = "kms:EncryptionContext:aws:logs:arn"
values = ["arn:aws:logs:${var.region}:${local.account_id}:log-group:${var.log_group_name}"]
}
}
}
resource "aws_kms_key" "logs" {
description = "Bedrock invocation logs"
enable_key_rotation = true
policy = data.aws_iam_policy_document.kms.json
lifecycle { prevent_destroy = true }
}
resource "aws_cloudwatch_log_group" "invocations" {
name = var.log_group_name
retention_in_days = var.retention_days
kms_key_id = aws_kms_key.logs.arn
}
resource "aws_bedrock_model_invocation_logging_configuration" "this" {
depends_on = [aws_iam_role_policy.bedrock_logging]
logging_config {
text_data_delivery_enabled = true
image_data_delivery_enabled = false
embedding_data_delivery_enabled = false
cloudwatch_config {
log_group_name = aws_cloudwatch_log_group.invocations.name
role_arn = aws_iam_role.bedrock_logging.arn
}
}
}
The Bedrock logging role (aws_iam_role.bedrock_logging) trusts bedrock.amazonaws.com and uses an aws:SourceAccount condition to allow only its own account. For permissions, logs:CreateLogStream and logs:PutLogEvents on this log group are enough. If the key policy leaves out the CloudWatch Logs service principal, log group creation fails with a KMS permission error. The error message makes it look like a problem with the Terraform execution role, and that sends you down the wrong path for a long time.
Field tip: The invocation logging configuration is a single setting per account per Region. If two stacks declare this resource in the same account and Region, they overwrite each other on every apply, and a terraform destroy in either one turns off invocation logging for the whole Region. Keep it in one account-wide stack only, and have other stacks reference its outputs. Most incidents where audit records vanish start with "cleaning up the test environment."
Step 5: running Terraform without internet
Even with the code ready, you cannot start if terraform init cannot fetch providers from the registry. In a closed network, prepare three things up front.
- Provider mirror: on an internet-connected staging machine used for bringing files in, run
terraform providers mirror -platform=linux_amd64 ./mirrorand move the result inside. Bring in the Terraform binary at the same time. - CLI config: in the runner's CLI config file (you can point to it with
TF_CLI_CONFIG_FILE), tell Terraform to use only the mirror. If you serve it from an internal HTTPS server, usenetwork_mirror. - State backend: use the S3 backend with an S3 lock file. You get locking without a DynamoDB table, which means one less endpoint.
# The runner's CLI config file
provider_installation {
filesystem_mirror {
path = "/opt/terraform/mirror"
include = ["registry.terraform.io/hashicorp/*"]
}
# No direct block, so the internet registry is never tried
}
# envs/prod/backend.tf
terraform {
backend "s3" {
bucket = "corp-tfstate-bedrock"
key = "prod/bedrock.tfstate"
region = "ap-northeast-2"
encrypt = true
use_lockfile = true # Terraform 1.10 or later. Older versions use dynamodb_table
}
}
There are two traps. First, .terraform.lock.hcl stores provider hashes per platform. Commit a lock file generated on a developer laptop and init on the Linux runner can fail with a checksum mismatch. Generate the lock file with every platform you use, for example terraform providers lock -fs-mirror=/opt/terraform/mirror -platform=linux_amd64 -platform=darwin_arm64. Second, an S3 gateway endpoint attaches to VPC route tables, so it cannot be used from the corporate network. If the runner is on premises, add a separate S3 interface endpoint or move the runner into a VPC. The provider and the backend also call STS, so the sts endpoint must be reachable from the runner's side as well.
Going deeper: where does the Terraform that creates the endpoints run?
Terraform creates the workload VPC's endpoints. If Terraform runs inside that same VPC, it needs ec2 and sts endpoints that do not exist yet, which is a chicken-and-egg problem. The usual fix is to put the runner in a separate management VPC (or a shared services account) and create endpoints there once, up front, for the AWS APIs Terraform calls (ec2, sts, kms, logs, bedrock, s3 and so on). This management VPC rarely changes, so manage it in its own state file. For services with global endpoints such as IAM, whether a VPC endpoint can reach them varies by service and Region, so check the path in the AWS documentation before creating IAM resources from the runner. The fastest way to find a missing endpoint is to see which service times out on connection during the plan.
Step 6: make CI fail when an internet path appears
Do not assume reviewers read every plan carefully. Run terraform fmt -check, terraform validate and the plan, then stop the pipeline if the plan JSON contains forbidden resources. Tools like OPA (conftest), Checkov or Sentinel work, but if the rules fit in a few lines, jq is enough.
terraform plan -out=tfplan -var-file=prod.tfvars
terraform show -json tfplan > plan.json
BAD=$(jq -r '
.resource_changes[]
| select(.change.actions | any(. == "create" or . == "update"))
| select(
.type == "aws_internet_gateway" or .type == "aws_nat_gateway"
or (.type == "aws_route" and .change.after.destination_cidr_block == "0.0.0.0/0")
or (.type == "aws_vpc_security_group_egress_rule" and .change.after.cidr_ipv4 == "0.0.0.0/0")
or (.type == "aws_security_group"
and ([.change.after.egress[]?.cidr_blocks[]?] | any(. == "0.0.0.0/0"))))
| .address' plan.json)
if [ -n "$BAD" ]; then echo "Closed-network rule violation:"; echo "$BAD"; exit 1; fi
Replacements (["delete","create"]) are caught too. But this check only sees changes from this code. An IGW attached from the console or another stack is blocked by an SCP that denies ec2:CreateInternetGateway and ec2:AttachInternetGateway, and watched with AWS Config. If you use IPv6, add ::/0 as well.
Step 7: catching drift
Adding a security group rule in the console during an incident and forgetting about it is common. Run terraform plan -refresh-only -detailed-exitcode daily and exit code 2 tells you there is drift (0 means no difference, 1 means an error). A person decides whether to revert it or bring it into the code.
- Give the check role mostly read access, but note that plan also takes the state lock by default, so it fails without write access to the lock file. If you use
-lock=false, schedule it away from applies. - Drift where invocation logging gets turned off or an endpoint policy gets wider is a security incident, so alert on it in a separate channel.
prevent_destroyon hard-to-reverse resources like KMS keys stops the accident where someone approves a replacement plan while trying to "fix" drift.
Checklist
- Separate modules: network, endpoints, iam, logging, plus a root module per environment
- Both VPC DNS attributes on, no IGW, NAT or
0.0.0.0/0route, default security group emptied - Endpoints with
for_each = toset(...), security group allows 443 only from VPC and corporate ranges - Approved model ARNs as a validated variable, and if you use inference profiles, check whether profile ARNs are included
- Every Bedrock-family endpoint ID in the
aws:SourceVpcecondition - CloudWatch Logs principal in the KMS key policy, invocation logging config in only one stack per account and Region
- Provider mirror, CLI config, multi-platform lock file, S3 backend with locking
- An S3 path that fits where the runner lives (gateway or interface), plus an sts endpoint
- CI: fmt, validate, plan, forbidden-resource check, account-level SCPs and Config
- Daily refresh-only drift check, with separate alerts for security resources
Resource arguments and behaviour change between provider versions. Before you apply, check each resource page and the upgrade guide in the Terraform AWS provider docs, the Terraform docs on CLI configuration and the S3 backend, and the AWS docs on VPC endpoints and Bedrock model invocation logging. If you are studying for an exam, the same topics come up in TF-TA004 and SAA-C03: you can practice related questions on cert-bank.
Comments
Post a Comment