Improvements to KMS encryption stance on ALB logs (#185)
This commit is contained in:
1 parent
7c957c4656
commit
d5da95f5a9
9 files changed
+1104
-25
No files matched your search
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.zip
|
||||
@@ -1,11 +1,19 @@
|
||||
# ALB Logging Addon
|
||||
This addon creates alb logging bucket(s) in s3 and optionally an athena database for those logs.
|
||||
This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key.
|
||||
|
||||
## How it works
|
||||
|
||||
1. **ALB writes** log objects to the S3 bucket using SSE-S3 (the only encryption ALB supports).
|
||||
2. **Event-driven Lambda** triggers on `s3:ObjectCreated:Put` and re-encrypts each object in-place to SSE-KMS via `CopyObject`. The Lambda's `CopyObject` emits `s3:ObjectCreated:Copy` which does not re-trigger the notification (loop prevention).
|
||||
3. **Daily sweep Lambda** runs via EventBridge and scans the last 2 days of ALB log prefixes. If any SSE-S3 objects are found (missed by the event-driven Lambda), it generates a CSV manifest and submits an S3 Batch Operations `S3PutObjectCopy` job to re-encrypt them.
|
||||
|
||||
Optionally creates Athena resources for querying the logs.
|
||||
|
||||
# Example Configuration
|
||||
|
||||
This assumes your fleet module is `main` and is configured with it's default documentation.
|
||||
This assumes your fleet module is `main` and is configured with its default documentation.
|
||||
|
||||
See https://github.com/fleetdm/fleet/blob/main/terraform/example/main.tf for details.
|
||||
See https://github.com/fleetdm/fleet/blob/main/terraform/example/main.tf for details.
|
||||
|
||||
```
|
||||
module "main" {
|
||||
@@ -32,7 +40,7 @@ module "logging_alb" {
|
||||
prefix = "fleet"
|
||||
enable_athena = true
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
# Additional Information
|
||||
|
||||
@@ -44,3 +52,25 @@ For this implementation, the S3 pattern for the `CREATE TABLE` query should look
|
||||
s3://your-alb-logs-bucket/<PREFIX>/AWSLogs/<ACCOUNT-ID>/elasticloadbalancing/<REGION>/
|
||||
```
|
||||
|
||||
## Migration from previous versions
|
||||
|
||||
If upgrading from a previous version that used a separate archive bucket, use the provided script to re-encrypt existing SSE-S3 objects in-place. The script uses S3 Batch Operations with `S3PutObjectCopy` to re-encrypt objects at scale.
|
||||
|
||||
1. Apply Terraform so the new Lambda functions and Batch Operations IAM role are in place.
|
||||
2. Run the migration script to re-encrypt existing objects:
|
||||
|
||||
```
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--source-bucket fleet-alb-logs
|
||||
```
|
||||
|
||||
The script auto-detects the KMS key by deriving a prefix from the bucket name (stripping the `-alb-logs` suffix) and looking up a KMS alias matching `alias/<prefix>-logs`. Use `--kms-key-arn` to specify the key explicitly. Use `--batch-role-arn` to pass the Terraform-managed Batch Operations role ARN.
|
||||
|
||||
3. Wait for the batch job to finish and validate that objects are now SSE-KMS encrypted.
|
||||
4. Optionally clean up the script-created IAM role:
|
||||
|
||||
```
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--cleanup-role \
|
||||
--source-bucket fleet-alb-logs
|
||||
```
|
||||
@@ -1,9 +1,17 @@
|
||||
# ALB Logging Addon
|
||||
This addon creates alb logging bucket(s) in s3 and optionally an athena database for those logs.
|
||||
This addon creates an S3 bucket for ALB access logs with in-place SSE-KMS re-encryption via Lambda. ALB access logging requires SSE-S3 (AES256), so objects are written with SSE-S3 and immediately re-encrypted to SSE-KMS using a customer-managed KMS key.
|
||||
|
||||
## How it works
|
||||
|
||||
1. **ALB writes** log objects to the S3 bucket using SSE-S3 (the only encryption ALB supports).
|
||||
2. **Event-driven Lambda** triggers on `s3:ObjectCreated:Put` and re-encrypts each object in-place to SSE-KMS via `CopyObject`. The Lambda's `CopyObject` emits `s3:ObjectCreated:Copy` which does not re-trigger the notification (loop prevention).
|
||||
3. **Daily sweep Lambda** runs via EventBridge and scans the last 2 days of ALB log prefixes. If any SSE-S3 objects are found (missed by the event-driven Lambda), it generates a CSV manifest and submits an S3 Batch Operations `S3PutObjectCopy` job to re-encrypt them.
|
||||
|
||||
Optionally creates Athena resources for querying the logs.
|
||||
|
||||
# Example Configuration
|
||||
|
||||
This assumes your fleet module is `main` and is configured with it's default documentation.
|
||||
This assumes your fleet module is `main` and is configured with its default documentation.
|
||||
|
||||
See https://github.com/fleetdm/fleet/blob/main/terraform/example/main.tf for details.
|
||||
|
||||
@@ -44,6 +52,29 @@ For this implementation, the S3 pattern for the `CREATE TABLE` query should look
|
||||
s3://your-alb-logs-bucket/<PREFIX>/AWSLogs/<ACCOUNT-ID>/elasticloadbalancing/<REGION>/
|
||||
```
|
||||
|
||||
## Migration from previous versions
|
||||
|
||||
If upgrading from a previous version that used a separate archive bucket, use the provided script to re-encrypt existing SSE-S3 objects in-place. The script uses S3 Batch Operations with `S3PutObjectCopy` to re-encrypt objects at scale.
|
||||
|
||||
1. Apply Terraform so the new Lambda functions and Batch Operations IAM role are in place.
|
||||
2. Run the migration script to re-encrypt existing objects:
|
||||
|
||||
```
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--source-bucket fleet-alb-logs
|
||||
```
|
||||
|
||||
The script auto-detects the KMS key by deriving a prefix from the bucket name (stripping the `-alb-logs` suffix) and looking up a KMS alias matching `alias/<prefix>-logs`. Use `--kms-key-arn` to specify the key explicitly. Use `--batch-role-arn` to pass the Terraform-managed Batch Operations role ARN.
|
||||
|
||||
3. Wait for the batch job to finish and validate that objects are now SSE-KMS encrypted.
|
||||
4. Optionally clean up the script-created IAM role:
|
||||
|
||||
```
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--cleanup-role \
|
||||
--source-bucket fleet-alb-logs
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
No requirements.
|
||||
@@ -52,7 +83,8 @@ No requirements.
|
||||
|
||||
| Name | Version |
|
||||
|------|---------|
|
||||
| <a name="provider_aws"></a> [aws](#provider\_aws) | 6.9.0 |
|
||||
| <a name="provider_archive"></a> [archive](#provider\_archive) | 2.7.1 |
|
||||
| <a name="provider_aws"></a> [aws](#provider\_aws) | 6.34.0 |
|
||||
|
||||
## Modules
|
||||
|
||||
@@ -67,11 +99,34 @@ No requirements.
|
||||
|------|------|
|
||||
| [aws_athena_database.logs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/athena_database) | resource |
|
||||
| [aws_athena_workgroup.logs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/athena_workgroup) | resource |
|
||||
| [aws_cloudwatch_event_rule.sweep_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_rule) | resource |
|
||||
| [aws_cloudwatch_event_target.sweep_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_target) | resource |
|
||||
| [aws_cloudwatch_log_group.lambda_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource |
|
||||
| [aws_cloudwatch_log_group.lambda_sweep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource |
|
||||
| [aws_glue_catalog_table.partitioned_alb_logs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/glue_catalog_table) | resource |
|
||||
| [aws_iam_role.batch_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource |
|
||||
| [aws_iam_role.lambda_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource |
|
||||
| [aws_iam_role.lambda_sweep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource |
|
||||
| [aws_iam_role_policy.batch_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource |
|
||||
| [aws_iam_role_policy.lambda_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource |
|
||||
| [aws_iam_role_policy.lambda_sweep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource |
|
||||
| [aws_kms_alias.logs_alias](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_alias) | resource |
|
||||
| [aws_kms_key.logs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_key) | resource |
|
||||
| [aws_lambda_function.reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource |
|
||||
| [aws_lambda_function.sweep_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource |
|
||||
| [aws_lambda_permission.eventbridge_invoke_sweep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource |
|
||||
| [aws_lambda_permission.s3_invoke_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource |
|
||||
| [aws_s3_bucket_notification.reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_notification) | resource |
|
||||
| [archive_file.lambda_reencrypt](https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file) | data source |
|
||||
| [archive_file.lambda_sweep](https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file) | data source |
|
||||
| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source |
|
||||
| [aws_iam_policy_document.batch_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.batch_reencrypt_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.kms](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.lambda_reencrypt](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.lambda_reencrypt_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.lambda_sweep](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.lambda_sweep_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.s3_athena_bucket](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_iam_policy_document.s3_log_bucket](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
|
||||
| [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source |
|
||||
@@ -95,4 +150,4 @@ No requirements.
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| <a name="output_log_s3_bucket_id"></a> [log\_s3\_bucket\_id](#output\_log\_s3\_bucket\_id) | n/a |
|
||||
| <a name="output_log_s3_bucket_id"></a> [log\_s3\_bucket\_id](#output\_log\_s3\_bucket\_id) | S3 bucket used by ALB access logging (SSE-S3 on write, re-encrypted to SSE-KMS by Lambda) |
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Lambda that re-encrypts newly created S3 objects in-place from SSE-S3 to SSE-KMS."""
|
||||
|
||||
import os
|
||||
import urllib.parse
|
||||
|
||||
import boto3
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
|
||||
KMS_KEY_ARN = os.environ["KMS_KEY_ARN"]
|
||||
|
||||
|
||||
def handler(event, context):
|
||||
for record in event["Records"]:
|
||||
bucket = record["s3"]["bucket"]["name"]
|
||||
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
|
||||
|
||||
# Safety belt: skip if already encrypted with KMS
|
||||
head = s3.head_object(Bucket=bucket, Key=key)
|
||||
if head.get("ServerSideEncryption") == "aws:kms":
|
||||
print(f"Skipping {key}: already SSE-KMS")
|
||||
continue
|
||||
|
||||
s3.copy_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
CopySource={"Bucket": bucket, "Key": key},
|
||||
ServerSideEncryption="aws:kms",
|
||||
SSEKMSKeyId=KMS_KEY_ARN,
|
||||
BucketKeyEnabled=True,
|
||||
MetadataDirective="REPLACE",
|
||||
Metadata=head.get("Metadata", {}),
|
||||
)
|
||||
print(f"Re-encrypted {key} to SSE-KMS")
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Daily sweep Lambda that finds SSE-S3 objects and submits an S3 Batch Operations job to re-encrypt them."""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import boto3
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
s3control = boto3.client("s3control")
|
||||
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
KMS_KEY_ARN = os.environ["KMS_KEY_ARN"]
|
||||
LOG_PREFIX = os.environ["LOG_PREFIX"]
|
||||
ACCOUNT_ID = os.environ["ACCOUNT_ID"]
|
||||
REGION = os.environ["REGION"]
|
||||
BATCH_ROLE_ARN = os.environ["BATCH_ROLE_ARN"]
|
||||
|
||||
|
||||
def _build_prefixes():
|
||||
"""Build ALB log prefixes for the last 2 days."""
|
||||
base = f"{LOG_PREFIX}/AWSLogs/{ACCOUNT_ID}/elasticloadbalancing/{REGION}"
|
||||
prefixes = []
|
||||
now = datetime.now(timezone.utc)
|
||||
for days_ago in range(2):
|
||||
d = now - timedelta(days=days_ago)
|
||||
prefixes.append(f"{base}/{d.strftime('%Y/%m/%d')}/")
|
||||
return prefixes
|
||||
|
||||
|
||||
def _find_sse_s3_objects(prefixes):
|
||||
"""List objects under the given prefixes and return keys still using SSE-S3."""
|
||||
sse_s3_keys = []
|
||||
for prefix in prefixes:
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
key = obj["Key"]
|
||||
head = s3.head_object(Bucket=BUCKET, Key=key)
|
||||
if head.get("ServerSideEncryption") != "aws:kms":
|
||||
sse_s3_keys.append(key)
|
||||
return sse_s3_keys
|
||||
|
||||
|
||||
def handler(event, context):
|
||||
prefixes = _build_prefixes()
|
||||
print(f"Scanning prefixes: {prefixes}")
|
||||
|
||||
sse_s3_keys = _find_sse_s3_objects(prefixes)
|
||||
|
||||
if not sse_s3_keys:
|
||||
print("No SSE-S3 objects found. Nothing to do.")
|
||||
return {"status": "no-op", "objects": 0}
|
||||
|
||||
print(f"Found {len(sse_s3_keys)} SSE-S3 objects. Submitting batch job.")
|
||||
|
||||
# Build CSV manifest
|
||||
manifest_buf = io.StringIO()
|
||||
writer = csv.writer(manifest_buf)
|
||||
for key in sse_s3_keys:
|
||||
writer.writerow([BUCKET, key])
|
||||
manifest_bytes = manifest_buf.getvalue().encode("utf-8")
|
||||
|
||||
# Upload manifest
|
||||
token = str(uuid.uuid4())
|
||||
manifest_key = f"_sweep-reencrypt/manifest-{token}.csv"
|
||||
put_resp = s3.put_object(Bucket=BUCKET, Key=manifest_key, Body=manifest_bytes)
|
||||
manifest_etag = put_resp["ETag"]
|
||||
|
||||
# Submit S3 Batch Operations job
|
||||
bucket_arn = f"arn:aws:s3:::{BUCKET}"
|
||||
job = s3control.create_job(
|
||||
AccountId=ACCOUNT_ID,
|
||||
Operation={
|
||||
"S3PutObjectCopy": {
|
||||
"TargetResource": bucket_arn,
|
||||
"NewObjectMetadata": {
|
||||
"SSEAlgorithm": "KMS",
|
||||
},
|
||||
"SSEAwsKmsKeyId": KMS_KEY_ARN,
|
||||
"MetadataDirective": "COPY",
|
||||
"BucketKeyEnabled": True,
|
||||
}
|
||||
},
|
||||
Manifest={
|
||||
"Spec": {
|
||||
"Format": "S3BatchOperations_CSV_20180820",
|
||||
"Fields": ["Bucket", "Key"],
|
||||
},
|
||||
"Location": {
|
||||
"ObjectArn": f"{bucket_arn}/{manifest_key}",
|
||||
"ETag": manifest_etag,
|
||||
},
|
||||
},
|
||||
Report={
|
||||
"Bucket": bucket_arn,
|
||||
"Prefix": "_sweep-reencrypt/reports",
|
||||
"Format": "Report_CSV_20180820",
|
||||
"Enabled": True,
|
||||
"ReportScope": "FailedTasksOnly",
|
||||
},
|
||||
Priority=10,
|
||||
RoleArn=BATCH_ROLE_ARN,
|
||||
Description=f"Sweep re-encrypt {len(sse_s3_keys)} SSE-S3 objects",
|
||||
ClientRequestToken=token,
|
||||
ConfirmationRequired=False,
|
||||
)
|
||||
|
||||
job_id = job["JobId"]
|
||||
print(f"Submitted batch job {job_id} for {len(sse_s3_keys)} objects")
|
||||
|
||||
return {"status": "submitted", "jobId": job_id, "objects": len(sse_s3_keys)}
|
||||
+359
-16
@@ -3,30 +3,57 @@ data "aws_caller_identity" "current" {}
|
||||
data "aws_region" "current" {}
|
||||
|
||||
locals {
|
||||
landing_bucket_name = "${var.prefix}-alb-logs"
|
||||
|
||||
kms_policies = concat([{
|
||||
actions = ["kms:*"],
|
||||
principals = [{
|
||||
type = "AWS"
|
||||
identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
|
||||
}]
|
||||
resources = ["*"]
|
||||
|
||||
kms_policies = concat([
|
||||
{
|
||||
actions = ["kms:*"]
|
||||
principals = [{
|
||||
type = "AWS"
|
||||
identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
|
||||
}]
|
||||
resources = ["*"]
|
||||
},
|
||||
{
|
||||
actions = [
|
||||
"kms:Encrypt*",
|
||||
"kms:Decrypt*",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:Describe*",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = ["*"]
|
||||
principals = [{
|
||||
type = "Service"
|
||||
identifiers = ["logs.${data.aws_region.current.region}.amazonaws.com"]
|
||||
type = "AWS"
|
||||
identifiers = [aws_iam_role.lambda_reencrypt.arn]
|
||||
}]
|
||||
}], var.extra_kms_policies)
|
||||
},
|
||||
{
|
||||
actions = [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = ["*"]
|
||||
principals = [{
|
||||
type = "AWS"
|
||||
identifiers = [aws_iam_role.lambda_sweep.arn]
|
||||
}]
|
||||
},
|
||||
{
|
||||
actions = [
|
||||
"kms:Encrypt",
|
||||
"kms:GenerateDataKey",
|
||||
"kms:GenerateDataKeyWithoutPlaintext",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = ["*"]
|
||||
principals = [{
|
||||
type = "AWS"
|
||||
identifiers = [aws_iam_role.batch_reencrypt.arn]
|
||||
}]
|
||||
},
|
||||
], var.extra_kms_policies)
|
||||
|
||||
s3_path_prefix = coalesce(var.alt_path_prefix, var.prefix)
|
||||
}
|
||||
@@ -115,6 +142,8 @@ data "aws_iam_policy_document" "s3_athena_bucket" {
|
||||
}
|
||||
}
|
||||
|
||||
# ── KMS key ──────────────────────────────────────────────────────────────────
|
||||
|
||||
resource "aws_kms_key" "logs" {
|
||||
policy = data.aws_iam_policy_document.kms.json
|
||||
enable_key_rotation = true
|
||||
@@ -125,11 +154,13 @@ resource "aws_kms_alias" "logs_alias" {
|
||||
target_key_id = aws_kms_key.logs.id
|
||||
}
|
||||
|
||||
# ── S3 bucket (single bucket — ALB writes SSE-S3, Lambda re-encrypts to SSE-KMS) ──
|
||||
|
||||
module "s3_bucket_for_logs" {
|
||||
source = "terraform-aws-modules/s3-bucket/aws"
|
||||
version = "5.0.0"
|
||||
|
||||
bucket = "${var.prefix}-alb-logs"
|
||||
bucket = local.landing_bucket_name
|
||||
|
||||
# Allow deletion of non-empty bucket
|
||||
force_destroy = true
|
||||
@@ -179,6 +210,318 @@ module "s3_bucket_for_logs" {
|
||||
]
|
||||
}
|
||||
|
||||
# ── Event-driven re-encrypt Lambda ───────────────────────────────────────────
|
||||
|
||||
data "aws_iam_policy_document" "lambda_reencrypt_assume_role" {
|
||||
statement {
|
||||
actions = ["sts:AssumeRole"]
|
||||
|
||||
principals {
|
||||
type = "Service"
|
||||
identifiers = ["lambda.amazonaws.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data "aws_iam_policy_document" "lambda_reencrypt" {
|
||||
statement {
|
||||
sid = "ReadWriteBucket"
|
||||
actions = [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
]
|
||||
resources = [
|
||||
"${module.s3_bucket_for_logs.s3_bucket_arn}/*",
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "UseKmsKey"
|
||||
actions = [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = [
|
||||
aws_kms_key.logs.arn,
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "WriteLogs"
|
||||
actions = [
|
||||
"logs:CreateLogStream",
|
||||
"logs:PutLogEvents",
|
||||
]
|
||||
resources = [
|
||||
"${aws_cloudwatch_log_group.lambda_reencrypt.arn}:*",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
resource "aws_iam_role" "lambda_reencrypt" {
|
||||
name_prefix = "${var.prefix}-alb-log-reencrypt-"
|
||||
assume_role_policy = data.aws_iam_policy_document.lambda_reencrypt_assume_role.json
|
||||
}
|
||||
|
||||
resource "aws_iam_role_policy" "lambda_reencrypt" {
|
||||
name_prefix = "${var.prefix}-alb-log-reencrypt-"
|
||||
role = aws_iam_role.lambda_reencrypt.id
|
||||
policy = data.aws_iam_policy_document.lambda_reencrypt.json
|
||||
}
|
||||
|
||||
data "archive_file" "lambda_reencrypt" {
|
||||
type = "zip"
|
||||
source_file = "${path.module}/lambda/reencrypt.py"
|
||||
output_path = "${path.module}/lambda/.reencrypt.zip"
|
||||
}
|
||||
|
||||
resource "aws_cloudwatch_log_group" "lambda_reencrypt" {
|
||||
name = "/aws/lambda/${var.prefix}-alb-log-reencrypt"
|
||||
retention_in_days = var.lambda_log_retention_in_days
|
||||
}
|
||||
|
||||
resource "aws_lambda_function" "reencrypt" {
|
||||
function_name = "${var.prefix}-alb-log-reencrypt"
|
||||
role = aws_iam_role.lambda_reencrypt.arn
|
||||
handler = "reencrypt.handler"
|
||||
runtime = "python3.12"
|
||||
timeout = 60
|
||||
filename = data.archive_file.lambda_reencrypt.output_path
|
||||
source_code_hash = data.archive_file.lambda_reencrypt.output_base64sha256
|
||||
|
||||
environment {
|
||||
variables = {
|
||||
KMS_KEY_ARN = aws_kms_key.logs.arn
|
||||
}
|
||||
}
|
||||
|
||||
depends_on = [
|
||||
aws_cloudwatch_log_group.lambda_reencrypt,
|
||||
aws_iam_role_policy.lambda_reencrypt,
|
||||
]
|
||||
}
|
||||
|
||||
resource "aws_lambda_permission" "s3_invoke_reencrypt" {
|
||||
statement_id = "AllowS3Invoke"
|
||||
action = "lambda:InvokeFunction"
|
||||
function_name = aws_lambda_function.reencrypt.function_name
|
||||
principal = "s3.amazonaws.com"
|
||||
source_arn = module.s3_bucket_for_logs.s3_bucket_arn
|
||||
}
|
||||
|
||||
resource "aws_s3_bucket_notification" "reencrypt" {
|
||||
bucket = module.s3_bucket_for_logs.s3_bucket_id
|
||||
|
||||
lambda_function {
|
||||
lambda_function_arn = aws_lambda_function.reencrypt.arn
|
||||
events = ["s3:ObjectCreated:Put"]
|
||||
filter_prefix = "${local.s3_path_prefix}/"
|
||||
}
|
||||
|
||||
depends_on = [aws_lambda_permission.s3_invoke_reencrypt]
|
||||
}
|
||||
|
||||
# ── Sweep re-encrypt Lambda (daily) ─────────────────────────────────────────
|
||||
|
||||
data "aws_iam_policy_document" "lambda_sweep_assume_role" {
|
||||
statement {
|
||||
actions = ["sts:AssumeRole"]
|
||||
|
||||
principals {
|
||||
type = "Service"
|
||||
identifiers = ["lambda.amazonaws.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data "aws_iam_policy_document" "lambda_sweep" {
|
||||
statement {
|
||||
sid = "ListBucket"
|
||||
actions = [
|
||||
"s3:ListBucket",
|
||||
]
|
||||
resources = [
|
||||
module.s3_bucket_for_logs.s3_bucket_arn,
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "ReadWriteBucket"
|
||||
actions = [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
]
|
||||
resources = [
|
||||
"${module.s3_bucket_for_logs.s3_bucket_arn}/*",
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "UseKmsKey"
|
||||
actions = [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = [
|
||||
aws_kms_key.logs.arn,
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "CreateBatchJob"
|
||||
actions = [
|
||||
"s3:CreateJob",
|
||||
]
|
||||
resources = ["*"]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "PassBatchRole"
|
||||
actions = [
|
||||
"iam:PassRole",
|
||||
]
|
||||
resources = [
|
||||
aws_iam_role.batch_reencrypt.arn,
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "WriteLogs"
|
||||
actions = [
|
||||
"logs:CreateLogStream",
|
||||
"logs:PutLogEvents",
|
||||
]
|
||||
resources = [
|
||||
"${aws_cloudwatch_log_group.lambda_sweep.arn}:*",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
resource "aws_iam_role" "lambda_sweep" {
|
||||
name_prefix = "${var.prefix}-alb-log-sweep-"
|
||||
assume_role_policy = data.aws_iam_policy_document.lambda_sweep_assume_role.json
|
||||
}
|
||||
|
||||
resource "aws_iam_role_policy" "lambda_sweep" {
|
||||
name_prefix = "${var.prefix}-alb-log-sweep-"
|
||||
role = aws_iam_role.lambda_sweep.id
|
||||
policy = data.aws_iam_policy_document.lambda_sweep.json
|
||||
}
|
||||
|
||||
data "archive_file" "lambda_sweep" {
|
||||
type = "zip"
|
||||
source_file = "${path.module}/lambda/sweep_reencrypt.py"
|
||||
output_path = "${path.module}/lambda/.sweep_reencrypt.zip"
|
||||
}
|
||||
|
||||
resource "aws_cloudwatch_log_group" "lambda_sweep" {
|
||||
name = "/aws/lambda/${var.prefix}-alb-log-sweep"
|
||||
retention_in_days = var.lambda_log_retention_in_days
|
||||
}
|
||||
|
||||
resource "aws_lambda_function" "sweep_reencrypt" {
|
||||
function_name = "${var.prefix}-alb-log-sweep"
|
||||
role = aws_iam_role.lambda_sweep.arn
|
||||
handler = "sweep_reencrypt.handler"
|
||||
runtime = "python3.12"
|
||||
timeout = 900
|
||||
filename = data.archive_file.lambda_sweep.output_path
|
||||
source_code_hash = data.archive_file.lambda_sweep.output_base64sha256
|
||||
|
||||
environment {
|
||||
variables = {
|
||||
BUCKET = module.s3_bucket_for_logs.s3_bucket_id
|
||||
KMS_KEY_ARN = aws_kms_key.logs.arn
|
||||
LOG_PREFIX = local.s3_path_prefix
|
||||
ACCOUNT_ID = data.aws_caller_identity.current.account_id
|
||||
REGION = data.aws_region.current.region
|
||||
BATCH_ROLE_ARN = aws_iam_role.batch_reencrypt.arn
|
||||
}
|
||||
}
|
||||
|
||||
depends_on = [
|
||||
aws_cloudwatch_log_group.lambda_sweep,
|
||||
aws_iam_role_policy.lambda_sweep,
|
||||
]
|
||||
}
|
||||
|
||||
# ── EventBridge daily schedule → sweep Lambda ────────────────────────────────
|
||||
|
||||
resource "aws_cloudwatch_event_rule" "sweep_reencrypt" {
|
||||
name_prefix = "${var.prefix}-alb-log-sweep-"
|
||||
schedule_expression = "rate(1 day)"
|
||||
}
|
||||
|
||||
resource "aws_cloudwatch_event_target" "sweep_reencrypt" {
|
||||
rule = aws_cloudwatch_event_rule.sweep_reencrypt.name
|
||||
arn = aws_lambda_function.sweep_reencrypt.arn
|
||||
}
|
||||
|
||||
resource "aws_lambda_permission" "eventbridge_invoke_sweep" {
|
||||
statement_id = "AllowEventBridgeInvoke"
|
||||
action = "lambda:InvokeFunction"
|
||||
function_name = aws_lambda_function.sweep_reencrypt.function_name
|
||||
principal = "events.amazonaws.com"
|
||||
source_arn = aws_cloudwatch_event_rule.sweep_reencrypt.arn
|
||||
}
|
||||
|
||||
# ── S3 Batch Operations IAM role (used by sweep Lambda and migration script) ─
|
||||
|
||||
data "aws_iam_policy_document" "batch_reencrypt_assume_role" {
|
||||
statement {
|
||||
actions = ["sts:AssumeRole"]
|
||||
|
||||
principals {
|
||||
type = "Service"
|
||||
identifiers = ["s3.amazonaws.com", "batchoperations.s3.amazonaws.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data "aws_iam_policy_document" "batch_reencrypt" {
|
||||
statement {
|
||||
sid = "ReadWriteBucket"
|
||||
actions = [
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion",
|
||||
"s3:PutObject",
|
||||
]
|
||||
resources = [
|
||||
"${module.s3_bucket_for_logs.s3_bucket_arn}/*",
|
||||
]
|
||||
}
|
||||
|
||||
statement {
|
||||
sid = "UseKmsKey"
|
||||
actions = [
|
||||
"kms:Encrypt",
|
||||
"kms:GenerateDataKey",
|
||||
"kms:GenerateDataKeyWithoutPlaintext",
|
||||
"kms:DescribeKey",
|
||||
]
|
||||
resources = [
|
||||
aws_kms_key.logs.arn,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
resource "aws_iam_role" "batch_reencrypt" {
|
||||
name_prefix = "${var.prefix}-alb-batch-reencrypt-"
|
||||
assume_role_policy = data.aws_iam_policy_document.batch_reencrypt_assume_role.json
|
||||
}
|
||||
|
||||
resource "aws_iam_role_policy" "batch_reencrypt" {
|
||||
name_prefix = "${var.prefix}-alb-batch-reencrypt-"
|
||||
role = aws_iam_role.batch_reencrypt.id
|
||||
policy = data.aws_iam_policy_document.batch_reencrypt.json
|
||||
}
|
||||
|
||||
# ── Athena (optional) ────────────────────────────────────────────────────────
|
||||
|
||||
resource "aws_athena_database" "logs" {
|
||||
count = var.enable_athena == true ? 1 : 0
|
||||
name = replace("${var.prefix}-alb-logs", "-", "_")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
output "log_s3_bucket_id" {
|
||||
value = module.s3_bucket_for_logs.s3_bucket_id
|
||||
description = "S3 bucket used by ALB access logging (SSE-S3 on write, re-encrypted to SSE-KMS by Lambda)"
|
||||
value = module.s3_bucket_for_logs.s3_bucket_id
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage:
|
||||
start-batch-replication-migration.sh --source-bucket BUCKET [options]
|
||||
start-batch-replication-migration.sh --cleanup-role --source-bucket BUCKET [options]
|
||||
|
||||
Submits an S3 Batch Operations job that re-encrypts existing ALB log objects
|
||||
in-place from SSE-S3 to SSE-KMS using S3PutObjectCopy.
|
||||
|
||||
The KMS key is automatically detected by deriving a prefix from the bucket
|
||||
name (stripping the -alb-logs suffix) and looking up a KMS alias matching
|
||||
alias/<prefix>-logs. Use --kms-key-arn to override.
|
||||
|
||||
Required:
|
||||
--source-bucket BUCKET Bucket containing ALB logs.
|
||||
|
||||
Optional:
|
||||
--kms-key-arn ARN KMS key ARN override. By default the key is
|
||||
resolved from a KMS alias derived from the
|
||||
bucket name (see above).
|
||||
--account-id ID AWS account ID. Defaults to the current caller account.
|
||||
--region REGION Source bucket region. Defaults to the source bucket location.
|
||||
--report-bucket BUCKET Bucket for the manifest and completion report.
|
||||
Defaults to the source bucket.
|
||||
--report-prefix PREFIX Prefix for manifest and reports.
|
||||
Default: _batch-copy-migration/
|
||||
--report-kms-key-arn ARN KMS key for the report bucket if it uses SSE-KMS.
|
||||
--batch-role-arn ARN Existing IAM role ARN for S3 Batch Operations.
|
||||
--batch-role-name NAME IAM role name to create/update if --batch-role-arn is omitted.
|
||||
--prefix PREFIX Only copy objects under this key prefix.
|
||||
--priority N Batch job priority. Default: 10
|
||||
--cleanup-role Delete the inline policy and (if script-created) the IAM role.
|
||||
|
||||
Examples:
|
||||
# In-place re-encryption (auto-detect KMS key from alias)
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--source-bucket fleet-alb-logs
|
||||
|
||||
# Explicit KMS key override
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--source-bucket fleet-alb-logs \
|
||||
--kms-key-arn arn:aws:kms:us-east-1:123456789012:key/abcd-1234
|
||||
|
||||
./scripts/start-batch-replication-migration.sh \
|
||||
--cleanup-role \
|
||||
--source-bucket fleet-alb-logs
|
||||
EOF
|
||||
}
|
||||
|
||||
require_command() {
|
||||
if ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "Missing required command: $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
sanitize_role_name() {
|
||||
printf '%s' "$1" | tr -cs '[:alnum:]+=,.@_-' '-'
|
||||
}
|
||||
|
||||
source_bucket=""
|
||||
kms_key_arn=""
|
||||
account_id=""
|
||||
region=""
|
||||
report_bucket=""
|
||||
report_prefix="_batch-copy-migration/"
|
||||
report_kms_key_arn=""
|
||||
batch_role_arn=""
|
||||
batch_role_name=""
|
||||
prefix=""
|
||||
priority="10"
|
||||
cleanup_role="false"
|
||||
managed_policy_name=""
|
||||
role_provided_explicitly="false"
|
||||
|
||||
script_manager_tag_key="ManagedBy"
|
||||
script_manager_tag_value="fleet-logging-alb-batch-copy-script"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--source-bucket)
|
||||
source_bucket="${2:?missing value for --source-bucket}"
|
||||
shift 2
|
||||
;;
|
||||
--kms-key-arn)
|
||||
kms_key_arn="${2:?missing value for --kms-key-arn}"
|
||||
shift 2
|
||||
;;
|
||||
--account-id)
|
||||
account_id="${2:?missing value for --account-id}"
|
||||
shift 2
|
||||
;;
|
||||
--region)
|
||||
region="${2:?missing value for --region}"
|
||||
shift 2
|
||||
;;
|
||||
--report-bucket)
|
||||
report_bucket="${2:?missing value for --report-bucket}"
|
||||
shift 2
|
||||
;;
|
||||
--report-prefix)
|
||||
report_prefix="${2:?missing value for --report-prefix}"
|
||||
shift 2
|
||||
;;
|
||||
--report-kms-key-arn)
|
||||
report_kms_key_arn="${2:?missing value for --report-kms-key-arn}"
|
||||
shift 2
|
||||
;;
|
||||
--batch-role-arn)
|
||||
batch_role_arn="${2:?missing value for --batch-role-arn}"
|
||||
role_provided_explicitly="true"
|
||||
shift 2
|
||||
;;
|
||||
--batch-role-name)
|
||||
batch_role_name="${2:?missing value for --batch-role-name}"
|
||||
role_provided_explicitly="true"
|
||||
shift 2
|
||||
;;
|
||||
--prefix)
|
||||
prefix="${2:?missing value for --prefix}"
|
||||
shift 2
|
||||
;;
|
||||
--priority)
|
||||
priority="${2:?missing value for --priority}"
|
||||
shift 2
|
||||
;;
|
||||
--cleanup-role)
|
||||
cleanup_role="true"
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ "$cleanup_role" != "true" ]]; then
|
||||
if [[ -z "$source_bucket" ]]; then
|
||||
echo "Error: --source-bucket is required." >&2
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
elif [[ -z "$source_bucket" && -z "$batch_role_name" && -z "$batch_role_arn" ]]; then
|
||||
echo "Error: --source-bucket or --batch-role-name/--batch-role-arn is required for --cleanup-role." >&2
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
require_command aws
|
||||
require_command jq
|
||||
require_command uuidgen
|
||||
|
||||
if [[ -z "$account_id" ]]; then
|
||||
account_id="$(aws sts get-caller-identity --query 'Account' --output text)"
|
||||
fi
|
||||
|
||||
if [[ -z "$region" && -n "$source_bucket" ]]; then
|
||||
region="$(aws s3api get-bucket-location --bucket "$source_bucket" --query 'LocationConstraint' --output text)"
|
||||
if [[ "$region" == "None" ]]; then
|
||||
region="us-east-1"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "$report_bucket" ]]; then
|
||||
report_bucket="$source_bucket"
|
||||
fi
|
||||
|
||||
# Auto-detect KMS key from KMS alias derived from bucket name
|
||||
if [[ -z "$kms_key_arn" && -n "$source_bucket" ]]; then
|
||||
# Derive prefix by stripping -alb-logs suffix from the bucket name
|
||||
kms_prefix="${source_bucket%-alb-logs}"
|
||||
alias_prefix="alias/${kms_prefix}-logs"
|
||||
|
||||
echo "Detecting KMS key from alias matching ${alias_prefix} ..."
|
||||
|
||||
matching_aliases="$(aws kms list-aliases \
|
||||
--query "Aliases[?starts_with(AliasName, \`${alias_prefix}\`)].{AliasName:AliasName,TargetKeyId:TargetKeyId}" \
|
||||
--output json)"
|
||||
|
||||
alias_count="$(echo "$matching_aliases" | jq 'length')"
|
||||
|
||||
if [[ "$alias_count" -eq 1 ]]; then
|
||||
target_key_id="$(echo "$matching_aliases" | jq -r '.[0].TargetKeyId')"
|
||||
# Resolve full key ARN
|
||||
kms_key_arn="$(aws kms describe-key --key-id "$target_key_id" --query 'KeyMetadata.Arn' --output text)"
|
||||
echo " Detected KMS key: ${kms_key_arn}"
|
||||
elif [[ "$alias_count" -eq 0 ]]; then
|
||||
echo "Error: no KMS alias found matching ${alias_prefix}." >&2
|
||||
echo " Pass --kms-key-arn explicitly." >&2
|
||||
exit 1
|
||||
else
|
||||
echo "Error: found ${alias_count} KMS aliases matching ${alias_prefix}:" >&2
|
||||
echo "$matching_aliases" | jq -r '.[].AliasName' | sed 's/^/ /' >&2
|
||||
echo " Pass --kms-key-arn explicitly to disambiguate." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "$batch_role_arn" ]]; then
|
||||
if [[ -z "$batch_role_name" ]]; then
|
||||
batch_role_name="$(sanitize_role_name "${source_bucket}-s3-batch-copy")"
|
||||
fi
|
||||
batch_role_arn="arn:aws:iam::${account_id}:role/${batch_role_name}"
|
||||
elif [[ -z "$batch_role_name" ]]; then
|
||||
batch_role_name="${batch_role_arn##*/}"
|
||||
fi
|
||||
|
||||
managed_policy_name="${batch_role_name}-inline"
|
||||
role_created_by_script="$(
|
||||
aws iam list-role-tags \
|
||||
--role-name "$batch_role_name" \
|
||||
--query "Tags[?Key=='${script_manager_tag_key}' && Value=='${script_manager_tag_value}'] | length(@)" \
|
||||
--output text \
|
||||
2>/dev/null || true
|
||||
)"
|
||||
|
||||
# ── Cleanup mode ──────────────────────────────────────────────────────────────
|
||||
|
||||
if [[ "$cleanup_role" == "true" ]]; then
|
||||
aws iam delete-role-policy \
|
||||
--role-name "$batch_role_name" \
|
||||
--policy-name "$managed_policy_name" \
|
||||
>/dev/null 2>&1 || true
|
||||
|
||||
if [[ "$role_created_by_script" == "1" ]]; then
|
||||
aws iam delete-role \
|
||||
--role-name "$batch_role_name" \
|
||||
>/dev/null
|
||||
echo "Deleted IAM role ${batch_role_name} and inline policy ${managed_policy_name}."
|
||||
else
|
||||
echo "Deleted inline policy ${managed_policy_name} if present."
|
||||
echo "Skipped deleting role ${batch_role_name} because it was not tagged as created by this script."
|
||||
fi
|
||||
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ── Build manifest ────────────────────────────────────────────────────────────
|
||||
|
||||
source_bucket_arn="arn:aws:s3:::${source_bucket}"
|
||||
report_bucket_arn="arn:aws:s3:::${report_bucket}"
|
||||
client_request_token="$(uuidgen | tr '[:upper:]' '[:lower:]')"
|
||||
|
||||
tmpdir="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmpdir"' EXIT
|
||||
|
||||
echo "Listing objects in s3://${source_bucket}/${prefix} ..."
|
||||
|
||||
manifest_file="${tmpdir}/manifest.csv"
|
||||
|
||||
# Paginate through all objects and build the CSV manifest
|
||||
> "$manifest_file"
|
||||
next_token=""
|
||||
object_count=0
|
||||
while true; do
|
||||
response="$(aws s3api list-objects-v2 --bucket "$source_bucket" \
|
||||
${prefix:+--prefix "$prefix"} \
|
||||
--output json \
|
||||
${next_token:+--starting-token "$next_token"})"
|
||||
|
||||
# Extract keys from this page
|
||||
keys="$(echo "$response" | jq -r '.Contents[]?.Key // empty')"
|
||||
|
||||
while IFS= read -r key; do
|
||||
[[ -z "$key" ]] && continue
|
||||
echo "${source_bucket},${key}" >> "$manifest_file"
|
||||
object_count=$((object_count + 1))
|
||||
done <<< "$keys"
|
||||
|
||||
next_token="$(echo "$response" | jq -r '.NextContinuationToken // empty')"
|
||||
|
||||
if [[ -z "$next_token" ]]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "$object_count" -eq 0 ]]; then
|
||||
echo "No objects found. Nothing to do."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Found ${object_count} objects. Objects already encrypted with SSE-KMS will be skipped by the batch job."
|
||||
|
||||
# Upload manifest to report bucket
|
||||
manifest_key="${report_prefix}manifest-${client_request_token}.csv"
|
||||
manifest_etag="$(aws s3api put-object \
|
||||
--bucket "$report_bucket" \
|
||||
--key "$manifest_key" \
|
||||
--body "$manifest_file" \
|
||||
${report_kms_key_arn:+--server-side-encryption aws:kms --ssekms-key-id "$report_kms_key_arn"} \
|
||||
--query 'ETag' --output json)"
|
||||
|
||||
echo "Uploaded manifest to s3://${report_bucket}/${manifest_key}"
|
||||
|
||||
# Get manifest size in bytes
|
||||
manifest_size="$(wc -c < "$manifest_file" | tr -d ' ')"
|
||||
|
||||
# ── Create / update IAM role ─────────────────────────────────────────────────
|
||||
|
||||
cat > "${tmpdir}/trust-policy.json" <<'EOF'
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Service": [
|
||||
"s3.amazonaws.com",
|
||||
"batchoperations.s3.amazonaws.com"
|
||||
]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
if ! aws iam get-role --role-name "$batch_role_name" >/dev/null 2>&1; then
|
||||
aws iam create-role \
|
||||
--role-name "$batch_role_name" \
|
||||
--assume-role-policy-document "file://${tmpdir}/trust-policy.json" \
|
||||
--tags "Key=${script_manager_tag_key},Value=${script_manager_tag_value}" \
|
||||
>/dev/null
|
||||
role_created_by_script="1"
|
||||
elif [[ "$role_created_by_script" == "1" || "$role_provided_explicitly" != "true" ]]; then
|
||||
aws iam update-assume-role-policy \
|
||||
--role-name "$batch_role_name" \
|
||||
--policy-document "file://${tmpdir}/trust-policy.json" \
|
||||
>/dev/null
|
||||
fi
|
||||
|
||||
# Build the role policy — needs read + write on the bucket, KMS, and
|
||||
# read on the manifest + write on reports.
|
||||
kms_statements=""
|
||||
if [[ -n "$kms_key_arn" ]]; then
|
||||
kms_statements=',
|
||||
{
|
||||
"Sid": "UseKmsKey",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:GenerateDataKey",
|
||||
"kms:GenerateDataKeyWithoutPlaintext",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "'"${kms_key_arn}"'"
|
||||
}'
|
||||
fi
|
||||
|
||||
report_kms_statements=""
|
||||
if [[ -n "$report_kms_key_arn" ]]; then
|
||||
report_kms_statements=',
|
||||
{
|
||||
"Sid": "UseReportBucketKmsKey",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:GenerateDataKey",
|
||||
"kms:GenerateDataKeyWithoutPlaintext",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "'"${report_kms_key_arn}"'"
|
||||
}'
|
||||
fi
|
||||
|
||||
cat > "${tmpdir}/role-policy.json" <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "ReadSourceBucket",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion"
|
||||
],
|
||||
"Resource": "${source_bucket_arn}/*"
|
||||
},
|
||||
{
|
||||
"Sid": "WriteBucket",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject"
|
||||
],
|
||||
"Resource": "${source_bucket_arn}/*"
|
||||
},
|
||||
{
|
||||
"Sid": "ReadManifest",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion"
|
||||
],
|
||||
"Resource": "${report_bucket_arn}/${report_prefix}*"
|
||||
},
|
||||
{
|
||||
"Sid": "WriteCompletionReports",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject"
|
||||
],
|
||||
"Resource": "${report_bucket_arn}/${report_prefix}*"
|
||||
}${kms_statements}${report_kms_statements}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
aws iam put-role-policy \
|
||||
--role-name "$batch_role_name" \
|
||||
--policy-name "$managed_policy_name" \
|
||||
--policy-document "file://${tmpdir}/role-policy.json" \
|
||||
>/dev/null
|
||||
|
||||
aws iam wait role-exists --role-name "$batch_role_name"
|
||||
echo "Waiting for IAM role propagation..."
|
||||
sleep 10
|
||||
|
||||
# ── Submit batch job ──────────────────────────────────────────────────────────
|
||||
|
||||
cat > "${tmpdir}/operation.json" <<EOF
|
||||
{
|
||||
"S3PutObjectCopy": {
|
||||
"TargetResource": "${source_bucket_arn}",
|
||||
"NewObjectMetadata": {
|
||||
"SSEAlgorithm": "KMS"
|
||||
},
|
||||
"SSEAwsKmsKeyId": "${kms_key_arn}",
|
||||
"MetadataDirective": "COPY",
|
||||
"BucketKeyEnabled": true
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
cat > "${tmpdir}/manifest.json" <<EOF
|
||||
{
|
||||
"Spec": {
|
||||
"Format": "S3BatchOperations_CSV_20180820",
|
||||
"Fields": ["Bucket", "Key"]
|
||||
},
|
||||
"Location": {
|
||||
"ObjectArn": "${report_bucket_arn}/${manifest_key}",
|
||||
"ETag": ${manifest_etag}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
cat > "${tmpdir}/report.json" <<EOF
|
||||
{
|
||||
"Bucket": "${report_bucket_arn}",
|
||||
"Prefix": "${report_prefix}reports",
|
||||
"Format": "Report_CSV_20180820",
|
||||
"Enabled": true,
|
||||
"ReportScope": "FailedTasksOnly"
|
||||
}
|
||||
EOF
|
||||
|
||||
job_id="$(
|
||||
aws --region "$region" s3control create-job \
|
||||
--account-id "$account_id" \
|
||||
--operation "file://${tmpdir}/operation.json" \
|
||||
--manifest "file://${tmpdir}/manifest.json" \
|
||||
--report "file://${tmpdir}/report.json" \
|
||||
--priority "$priority" \
|
||||
--role-arn "$batch_role_arn" \
|
||||
--description "Re-encrypt objects in ${source_bucket} in-place with SSE-KMS" \
|
||||
--client-request-token "$client_request_token" \
|
||||
--no-confirmation-required \
|
||||
--query 'JobId' \
|
||||
--output text
|
||||
)"
|
||||
|
||||
cat <<EOF
|
||||
Created S3 Batch Operations re-encryption job.
|
||||
Job ID: ${job_id}
|
||||
Region: ${region}
|
||||
Bucket: ${source_bucket}
|
||||
KMS key: ${kms_key_arn}
|
||||
Objects in manifest: ${object_count}
|
||||
Report bucket: ${report_bucket}
|
||||
Batch role: ${batch_role_arn}
|
||||
|
||||
Check status with:
|
||||
aws --region ${region} s3control describe-job --account-id ${account_id} --job-id ${job_id}
|
||||
EOF
|
||||
@@ -34,6 +34,12 @@ variable "s3_noncurrent_version_expiration_days" {
|
||||
default = 30
|
||||
}
|
||||
|
||||
variable "lambda_log_retention_in_days" {
|
||||
description = "CloudWatch log retention in days for the re-encrypt and sweep Lambda functions"
|
||||
type = number
|
||||
default = 365
|
||||
}
|
||||
|
||||
variable "extra_kms_policies" {
|
||||
type = list(any)
|
||||
default = []
|
||||
|
||||
Reference in new issue
Block a user