From 0512d6da1179726ccae1c26ddde4f4b8b78b671e Mon Sep 17 00:00:00 2001 From: Robert Fairburn <8029478+rfairburn@users.noreply.github.com> Date: Wed, 18 Feb 2026 07:30:11 -0600 Subject: [PATCH] Initial cross-account log sharing module (#176) --- .github/scripts/get-pr-reviews.sh | 23 ++ .github/workflows/tfvalidate.yml | 26 ++ .../cloudwatch/.header.md | 40 ++ .../cloudwatch/.terraform-docs.yml | 1 + .../cloudwatch/README.md | 75 ++++ .../cloudwatch/main.tf | 7 + .../cloudwatch/outputs.tf | 8 + .../cloudwatch/variables.tf | 21 + .../cloudwatch/version.tf | 10 + .../pubsub-bridge/.header.md | 105 +++++ .../pubsub-bridge/.terraform-docs.yml | 1 + .../pubsub-bridge/README.md | 184 +++++++++ .../pubsub-bridge/alerts.tf | 81 ++++ .../pubsub-bridge/dlq.tf | 30 ++ .../pubsub-bridge/iam.tf | 201 ++++++++++ .../pubsub-bridge/lambda.tf | 76 ++++ .../pubsub-bridge/lambda/go.mod | 63 +++ .../pubsub-bridge/lambda/go.sum | 227 +++++++++++ .../pubsub-bridge/lambda/main.go | 374 ++++++++++++++++++ .../pubsub-bridge/lambda/main_test.go | 224 +++++++++++ .../pubsub-bridge/lambda/replayer/main.go | 122 ++++++ .../lambda/replayer/main_test.go | 130 ++++++ .../pubsub-bridge/outputs.tf | 67 ++++ .../pubsub-bridge/replayer.tf | 90 +++++ .../pubsub-bridge/subscription.tf | 8 + .../pubsub-bridge/variables.tf | 314 +++++++++++++++ .../pubsub-bridge/version.tf | 20 + .../target-account-firehose/.header.md | 61 +++ .../.terraform-docs.yml | 1 + .../target-account-firehose/README.md | 126 ++++++ .../target-account-firehose/destination.tf | 79 ++++ .../target-account-firehose/firehose.tf | 77 ++++ .../target-account-firehose/iam.tf | 69 ++++ .../target-account-firehose/outputs.tf | 27 ++ .../target-account-firehose/s3.tf | 28 ++ .../target-account-firehose/variables.tf | 90 +++++ .../target-account-firehose/version.tf | 14 + .../target-account-gcp/.header.md | 110 ++++++ .../target-account-gcp/.terraform-docs.yml | 1 + .../target-account-gcp/README.md | 165 ++++++++ .../target-account-gcp/main.tf | 82 ++++ .../target-account-gcp/outputs.tf | 43 ++ .../scripts/publish_pubsub_test.sh | 164 ++++++++ .../target-account-gcp/variables.tf | 102 +++++ .../target-account-gcp/version.tf | 10 + .../target-account-kinesis/.header.md | 51 +++ .../.terraform-docs.yml | 1 + .../target-account-kinesis/README.md | 106 +++++ .../target-account-kinesis/destination.tf | 79 ++++ .../target-account-kinesis/iam.tf | 62 +++ .../target-account-kinesis/kinesis.tf | 19 + .../target-account-kinesis/outputs.tf | 19 + .../target-account-kinesis/variables.tf | 64 +++ .../target-account-kinesis/version.tf | 14 + addons/monitoring/lambda/go.mod | 2 +- 55 files changed, 4193 insertions(+), 1 deletion(-) create mode 100755 .github/scripts/get-pr-reviews.sh create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/.header.md create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/.terraform-docs.yml create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/README.md create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/main.tf create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/outputs.tf create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/variables.tf create mode 100644 addons/byo-cloudwatch-log-sharing/cloudwatch/version.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/.header.md create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/.terraform-docs.yml create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/README.md create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/alerts.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/dlq.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/iam.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.mod create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.sum create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main.go create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main_test.go create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main.go create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main_test.go create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/outputs.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/replayer.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/subscription.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/variables.tf create mode 100644 addons/byo-cloudwatch-log-sharing/pubsub-bridge/version.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/.header.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/.terraform-docs.yml create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/README.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/destination.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/firehose.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/iam.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/outputs.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/s3.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/variables.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-firehose/version.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/.header.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/.terraform-docs.yml create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/README.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/main.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/outputs.tf create mode 100755 addons/byo-cloudwatch-log-sharing/target-account-gcp/scripts/publish_pubsub_test.sh create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/variables.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-gcp/version.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/.header.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/.terraform-docs.yml create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/README.md create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/destination.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/iam.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/kinesis.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/outputs.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/variables.tf create mode 100644 addons/byo-cloudwatch-log-sharing/target-account-kinesis/version.tf diff --git a/.github/scripts/get-pr-reviews.sh b/.github/scripts/get-pr-reviews.sh new file mode 100755 index 0000000..6b1d63a --- /dev/null +++ b/.github/scripts/get-pr-reviews.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +set -euo pipefail + +if ! command -v gh >/dev/null 2>&1; then + echo "error: GitHub CLI (gh) is required but not installed." >&2 + exit 1 +fi + +if ! command -v jq >/dev/null 2>&1; then + echo "error: jq is required but not installed." >&2 + exit 1 +fi + +if ! gh extension list | awk '{print $1}' | grep -qx "agynio/gh-pr-review"; then + echo "Installing gh extension agynio/gh-pr-review..." >&2 + gh extension install agynio/gh-pr-review +fi + +GH_REPO="$(git config --get remote.origin.url | sed 's/.*[:\/]\(.*\)\/\(.*\)\.git/\1\/\2/')" +GIT_PR="$(gh pr list --head "$(git branch --show-current)" --json number | jq '.[0].number')" + +gh pr-review review view "${GIT_PR}" --repo "${GH_REPO}" diff --git a/.github/workflows/tfvalidate.yml b/.github/workflows/tfvalidate.yml index 76d1762..7a75869 100644 --- a/.github/workflows/tfvalidate.yml +++ b/.github/workflows/tfvalidate.yml @@ -76,5 +76,31 @@ jobs: - name: Validate ${{ matrix.terraform_dir }} module (covers all submodules) working-directory: ${{ matrix.terraform_dir }} run: | + # Some modules use aliased AWS providers (for example aws.destination/aws.target) + # and fail direct `terraform validate` unless alias configs are present. + # Generate a temporary provider file for any discovered aws. references. + AWS_ALIASES="$(grep -RhoE 'provider[[:space:]]*=[[:space:]]*aws\.[A-Za-z0-9_]+' -- *.tf 2>/dev/null | sed -E 's/.*aws\.([A-Za-z0-9_]+)/\1/' | sort -u || true)" + if [[ -n "${AWS_ALIASES}" ]]; then + # Terraform ignores dot-prefixed files, so this must not start with "." + AUTO_PROVIDER_FILE="tfvalidate.providers.auto.tf" + { + echo "// Generated by CI for terraform validate." + echo "// Do not commit." + echo + } > "${AUTO_PROVIDER_FILE}" + + for alias in ${AWS_ALIASES}; do + { + echo 'provider "aws" {' + echo " alias = \"${alias}\"" + echo ' region = "us-east-2"' + echo '}' + echo + } >> "${AUTO_PROVIDER_FILE}" + done + + echo "Generated ${AUTO_PROVIDER_FILE} for aliases: ${AWS_ALIASES}" + fi + terraform init -backend=false terraform validate diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/.header.md b/addons/byo-cloudwatch-log-sharing/cloudwatch/.header.md new file mode 100644 index 0000000..d975728 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/.header.md @@ -0,0 +1,40 @@ +# Fleet CloudWatch Log Group Sharing (Source Account) + +## Usage + +Use this module in the source Fleet account (and in the same region as the Fleet CloudWatch log group). + +### Firehose destination (default) + +```hcl +module "fleet_log_sharing" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/cloudwatch?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + destination_arn = "arn:aws:logs:us-east-2:222222222222:destination:fleet-app-logs-firehose" + # destination_type defaults to "firehose" + filter_pattern = "" + } +} +``` + +### Kinesis destination + +```hcl +module "fleet_log_sharing" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/cloudwatch?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + destination_arn = "arn:aws:logs:us-east-2:222222222222:destination:fleet-app-logs-kinesis" + destination_type = "kinesis" + kinesis_distribution = "ByLogStream" + filter_pattern = "" + } +} +``` + +`subscription.destination_arn` is usually provided out-of-band by the organization that runs the target-account module in their environment. + +No Fleet environment variable changes are required. This module configures the CloudWatch Logs subscription directly on the Fleet log group. diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/.terraform-docs.yml b/addons/byo-cloudwatch-log-sharing/cloudwatch/.terraform-docs.yml new file mode 100644 index 0000000..1d139dd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/README.md b/addons/byo-cloudwatch-log-sharing/cloudwatch/README.md new file mode 100644 index 0000000..9d4cc95 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/README.md @@ -0,0 +1,75 @@ +# Fleet CloudWatch Log Group Sharing (Source Account) + +## Usage + +Use this module in the source Fleet account (and in the same region as the Fleet CloudWatch log group). + +### Firehose destination (default) + +```hcl +module "fleet_log_sharing" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/cloudwatch?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + destination_arn = "arn:aws:logs:us-east-2:222222222222:destination:fleet-app-logs-firehose" + # destination_type defaults to "firehose" + filter_pattern = "" + } +} +``` + +### Kinesis destination + +```hcl +module "fleet_log_sharing" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/cloudwatch?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + destination_arn = "arn:aws:logs:us-east-2:222222222222:destination:fleet-app-logs-kinesis" + destination_type = "kinesis" + kinesis_distribution = "ByLogStream" + filter_pattern = "" + } +} +``` + +`subscription.destination_arn` is usually provided out-of-band by the organization that runs the target-account module in their environment. + +No Fleet environment variable changes are required. This module configures the CloudWatch Logs subscription directly on the Fleet log group. + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.7 | +| [aws](#requirement\_aws) | >= 5.29.0 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 5.29.0 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_subscription_filter.fleet_log_group](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_subscription_filter) | resource | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [subscription](#input\_subscription) | CloudWatch Logs subscription configuration for sharing a source log group to a cross-account destination. |
object({
log_group_name = string
destination_arn = string
filter_name = optional(string, "fleet-log-sharing")
filter_pattern = optional(string, "")
destination_type = optional(string, "firehose")
kinesis_distribution = optional(string, "ByLogStream")
})
| n/a | yes | + +## Outputs + +| Name | Description | +|------|-------------| +| [subscription\_filter](#output\_subscription\_filter) | CloudWatch Logs subscription filter details. | diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/main.tf b/addons/byo-cloudwatch-log-sharing/cloudwatch/main.tf new file mode 100644 index 0000000..a2c5f3a --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/main.tf @@ -0,0 +1,7 @@ +resource "aws_cloudwatch_log_subscription_filter" "fleet_log_group" { + name = var.subscription.filter_name + log_group_name = var.subscription.log_group_name + filter_pattern = var.subscription.filter_pattern + destination_arn = var.subscription.destination_arn + distribution = var.subscription.destination_type == "kinesis" ? var.subscription.kinesis_distribution : null +} diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/outputs.tf b/addons/byo-cloudwatch-log-sharing/cloudwatch/outputs.tf new file mode 100644 index 0000000..44fada3 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/outputs.tf @@ -0,0 +1,8 @@ +output "subscription_filter" { + description = "CloudWatch Logs subscription filter details." + value = { + name = aws_cloudwatch_log_subscription_filter.fleet_log_group.name + log_group_name = aws_cloudwatch_log_subscription_filter.fleet_log_group.log_group_name + destination_arn = aws_cloudwatch_log_subscription_filter.fleet_log_group.destination_arn + } +} diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/variables.tf b/addons/byo-cloudwatch-log-sharing/cloudwatch/variables.tf new file mode 100644 index 0000000..0cb5e7c --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/variables.tf @@ -0,0 +1,21 @@ +variable "subscription" { + description = "CloudWatch Logs subscription configuration for sharing a source log group to a cross-account destination." + type = object({ + log_group_name = string + destination_arn = string + filter_name = optional(string, "fleet-log-sharing") + filter_pattern = optional(string, "") + destination_type = optional(string, "firehose") + kinesis_distribution = optional(string, "ByLogStream") + }) + + validation { + condition = contains(["firehose", "kinesis"], var.subscription.destination_type) + error_message = "subscription.destination_type must be one of: firehose, kinesis." + } + + validation { + condition = contains(["ByLogStream", "Random"], var.subscription.kinesis_distribution) + error_message = "subscription.kinesis_distribution must be one of: ByLogStream, Random." + } +} diff --git a/addons/byo-cloudwatch-log-sharing/cloudwatch/version.tf b/addons/byo-cloudwatch-log-sharing/cloudwatch/version.tf new file mode 100644 index 0000000..472cd2d --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/cloudwatch/version.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.7" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.29.0" + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.header.md b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.header.md new file mode 100644 index 0000000..1462fa2 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.header.md @@ -0,0 +1,105 @@ +# Fleet CloudWatch Logs to GCP Pub/Sub Bridge + +This module creates an AWS Lambda subscription target for a Fleet CloudWatch log group and forwards log events to a GCP Pub/Sub topic. + +The Lambda function reads Google service account credentials from an existing AWS Secrets Manager secret. +Deploy this module in the same AWS region as the Fleet CloudWatch log group. +The bridge Lambda is implemented in Go and compiled during Terraform apply. +Publishing uses the official `cloud.google.com/go/pubsub/v2` client library. +The Terraform execution environment must include a working `go` toolchain. + +## Usage + +```hcl +provider "aws" { + region = "us-east-2" +} + +variable "gcp_pubsub_service_account_credentials_json" { + description = "Google service-account credentials JSON shared by the customer (for example from target-account-gcp publisher_credentials_json)." + type = string + sensitive = true +} + +resource "aws_secretsmanager_secret" "gcp_pubsub_credentials" { + name = "fleet/gcp/pubsub/service-account" +} + +resource "aws_secretsmanager_secret_version" "gcp_pubsub_credentials" { + secret_id = aws_secretsmanager_secret.gcp_pubsub_credentials.id + secret_string = jsonencode({ + service_account_json = var.gcp_pubsub_service_account_credentials_json + }) +} + +module "fleet_pubsub_bridge" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/pubsub-bridge?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + filter_pattern = "" + } + + gcp_pubsub = { + project_id = "customer-observability-prod" + topic_id = "fleet-logs" + credentials_secret_arn = aws_secretsmanager_secret.gcp_pubsub_credentials.arn + } + + lambda = { + function_name = "fleet-cloudwatch-pubsub-bridge" + role_name = "fleet-cloudwatch-pubsub-bridge-role" + policy_name = "fleet-cloudwatch-pubsub-bridge-policy" + timeout = 60 + memory_size = 256 + batch_size = 1000 + } + + dlq = { + enabled = true + queue_name = "fleet-cloudwatch-pubsub-bridge-dlq" + maximum_retry_attempts = 2 + maximum_event_age_in_seconds = 3600 + } + + alerting = { + enabled = true + sns_topic_arns = ["arn:aws:sns:us-east-2:111111111111:fleet-ops-alerts"] + period_seconds = 300 + evaluation_periods = 1 + datapoints_to_alarm = 1 + lambda_errors_threshold = 1 + dlq_visible_messages_threshold = 1 + enable_ok_notifications = true + } + + replayer = { + enabled = true + function_name = "fleet-cloudwatch-pubsub-bridge-replayer" + batch_size = 10 + maximum_batching_window_in_seconds = 5 + maximum_concurrency = 2 + } +} + +output "fleet_pubsub_bridge" { + value = module.fleet_pubsub_bridge +} +``` + +The referenced secret should contain either: +- A Google service-account key JSON document directly. +- A JSON object with a `service_account_json` field that contains the service-account key JSON. + +This module uses CloudWatch alarms for notifications so alerts fire on state transitions instead of per-failed event, which avoids high-volume SNS spam during sustained failures. + +A built-in SQS replayer Lambda is enabled by default and re-drives failed async events from the DLQ back to the main bridge Lambda with partial-batch failure handling. + +## Reprocessing Options + +1. Built-in automatic replay: +Use the module's default `replayer` settings to continuously re-drive failed events from DLQ. +2. Manual/batched replay: +Drain DLQ messages to S3 for analysis, then replay selected batches during controlled windows. +3. Scheduled replay workflow: +Use EventBridge Scheduler or Step Functions to periodically replay aged DLQ messages with rate limits and stop conditions. diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.terraform-docs.yml b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.terraform-docs.yml new file mode 100644 index 0000000..1d139dd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/README.md b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/README.md new file mode 100644 index 0000000..f130d42 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/README.md @@ -0,0 +1,184 @@ +# Fleet CloudWatch Logs to GCP Pub/Sub Bridge + +This module creates an AWS Lambda subscription target for a Fleet CloudWatch log group and forwards log events to a GCP Pub/Sub topic. + +The Lambda function reads Google service account credentials from an existing AWS Secrets Manager secret. +Deploy this module in the same AWS region as the Fleet CloudWatch log group. +The bridge Lambda is implemented in Go and compiled during Terraform apply. +Publishing uses the official `cloud.google.com/go/pubsub/v2` client library. +The Terraform execution environment must include a working `go` toolchain. + +## Usage + +```hcl +provider "aws" { + region = "us-east-2" +} + +variable "gcp_pubsub_service_account_credentials_json" { + description = "Google service-account credentials JSON shared by the customer (for example from target-account-gcp publisher_credentials_json)." + type = string + sensitive = true +} + +resource "aws_secretsmanager_secret" "gcp_pubsub_credentials" { + name = "fleet/gcp/pubsub/service-account" +} + +resource "aws_secretsmanager_secret_version" "gcp_pubsub_credentials" { + secret_id = aws_secretsmanager_secret.gcp_pubsub_credentials.id + secret_string = jsonencode({ + service_account_json = var.gcp_pubsub_service_account_credentials_json + }) +} + +module "fleet_pubsub_bridge" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/pubsub-bridge?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + subscription = { + log_group_name = module.fleet.byo-vpc.byo-db.byo-ecs.logging_config["awslogs-group"] + filter_pattern = "" + } + + gcp_pubsub = { + project_id = "customer-observability-prod" + topic_id = "fleet-logs" + credentials_secret_arn = aws_secretsmanager_secret.gcp_pubsub_credentials.arn + } + + lambda = { + function_name = "fleet-cloudwatch-pubsub-bridge" + role_name = "fleet-cloudwatch-pubsub-bridge-role" + policy_name = "fleet-cloudwatch-pubsub-bridge-policy" + timeout = 60 + memory_size = 256 + batch_size = 1000 + } + + dlq = { + enabled = true + queue_name = "fleet-cloudwatch-pubsub-bridge-dlq" + maximum_retry_attempts = 2 + maximum_event_age_in_seconds = 3600 + } + + alerting = { + enabled = true + sns_topic_arns = ["arn:aws:sns:us-east-2:111111111111:fleet-ops-alerts"] + period_seconds = 300 + evaluation_periods = 1 + datapoints_to_alarm = 1 + lambda_errors_threshold = 1 + dlq_visible_messages_threshold = 1 + enable_ok_notifications = true + } + + replayer = { + enabled = true + function_name = "fleet-cloudwatch-pubsub-bridge-replayer" + batch_size = 10 + maximum_batching_window_in_seconds = 5 + maximum_concurrency = 2 + } +} + +output "fleet_pubsub_bridge" { + value = module.fleet_pubsub_bridge +} +``` + +The referenced secret should contain either: +- A Google service-account key JSON document directly. +- A JSON object with a `service_account_json` field that contains the service-account key JSON. + +This module uses CloudWatch alarms for notifications so alerts fire on state transitions instead of per-failed event, which avoids high-volume SNS spam during sustained failures. + +A built-in SQS replayer Lambda is enabled by default and re-drives failed async events from the DLQ back to the main bridge Lambda with partial-batch failure handling. + +## Reprocessing Options + +1. Built-in automatic replay: +Use the module's default `replayer` settings to continuously re-drive failed events from DLQ. +2. Manual/batched replay: +Drain DLQ messages to S3 for analysis, then replay selected batches during controlled windows. +3. Scheduled replay workflow: +Use EventBridge Scheduler or Step Functions to periodically replay aged DLQ messages with rate limits and stop conditions. + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.7 | +| [archive](#requirement\_archive) | >= 2.4.0 | +| [aws](#requirement\_aws) | >= 5.29.0 | +| [null](#requirement\_null) | >= 3.2.1 | + +## Providers + +| Name | Version | +|------|---------| +| [archive](#provider\_archive) | >= 2.4.0 | +| [aws](#provider\_aws) | >= 5.29.0 | +| [null](#provider\_null) | >= 3.2.1 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_group.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_cloudwatch_log_group.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_cloudwatch_log_subscription_filter.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_subscription_filter) | resource | +| [aws_cloudwatch_metric_alarm.dlq_visible_messages](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource | +| [aws_cloudwatch_metric_alarm.lambda_errors](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource | +| [aws_cloudwatch_metric_alarm.replayer_errors](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource | +| [aws_iam_policy.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_iam_policy.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_iam_role.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy_attachment.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.lambda_basic_execution](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.replayer_lambda_basic_execution](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_lambda_event_source_mapping.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_event_source_mapping) | resource | +| [aws_lambda_function.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_function.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_function_event_invoke_config.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function_event_invoke_config) | resource | +| [aws_lambda_permission.allow_cloudwatch_logs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | +| [aws_sqs_queue.dlq](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sqs_queue) | resource | +| [null_resource.bridge_build](https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource) | resource | +| [null_resource.replayer_build](https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource) | resource | +| [archive_file.bridge](https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file) | data source | +| [archive_file.replayer](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.bridge](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.replayer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_partition.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/partition) | data source | +| [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [alerting](#input\_alerting) | CloudWatch alarm and SNS notification settings for bridge failures. |
object({
enabled = optional(bool, true)
sns_topic_arns = optional(list(string), [])
enable_ok_notifications = optional(bool, true)
period_seconds = optional(number, 300)
evaluation_periods = optional(number, 1)
datapoints_to_alarm = optional(number, 1)
lambda_errors_threshold = optional(number, 1)
dlq_visible_messages_threshold = optional(number, 1)
})
| `{}` | no | +| [dlq](#input\_dlq) | Asynchronous Lambda failure handling via SQS dead-letter queue. |
object({
enabled = optional(bool, true)
queue_name = optional(string)
maximum_retry_attempts = optional(number, 2)
maximum_event_age_in_seconds = optional(number, 3600)
message_retention_seconds = optional(number, 1209600)
visibility_timeout_seconds = optional(number, 60)
sqs_managed_sse_enabled = optional(bool, true)
kms_master_key_id = optional(string, "")
})
| `{}` | no | +| [gcp\_pubsub](#input\_gcp\_pubsub) | GCP Pub/Sub settings and credentials secret reference for cloud.google.com/go/pubsub/v2. The secret must contain a Google service-account key JSON, or a JSON object with a service\_account\_json field containing that key JSON. |
object({
project_id = string
topic_id = string
credentials_secret_arn = string
secret_kms_key_arn = optional(string, "")
})
| n/a | yes | +| [lambda](#input\_lambda) | Go-based Lambda bridge configuration. |
object({
function_name = optional(string, "fleet-cloudwatch-pubsub-bridge")
role_name = optional(string, "fleet-cloudwatch-pubsub-bridge-role")
policy_name = optional(string)
runtime = optional(string, "provided.al2")
architecture = optional(string, "x86_64")
memory_size = optional(number, 256)
timeout = optional(number, 60)
log_retention_in_days = optional(number, 30)
reserved_concurrent_executions = optional(number, -1)
batch_size = optional(number, 1000)
})
| `{}` | no | +| [replayer](#input\_replayer) | SQS DLQ replayer settings. Replays failed bridge events back to the main bridge Lambda. |
object({
enabled = optional(bool, true)
function_name = optional(string)
role_name = optional(string)
policy_name = optional(string)
runtime = optional(string)
architecture = optional(string)
memory_size = optional(number, 256)
timeout = optional(number, 60)
log_retention_in_days = optional(number, 30)
reserved_concurrent_executions = optional(number, -1)
batch_size = optional(number, 10)
maximum_batching_window_in_seconds = optional(number, 5)
maximum_concurrency = optional(number, 2)
})
| `{}` | no | +| [subscription](#input\_subscription) | CloudWatch Logs subscription settings for sending Fleet log events to the Pub/Sub bridge Lambda. |
object({
log_group_name = string
log_group_arn = optional(string)
filter_name = optional(string, "fleet-log-pubsub-bridge")
filter_pattern = optional(string, "")
})
| n/a | yes | +| [tags](#input\_tags) | Tags to apply to created resources that support tags. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [alerting](#output\_alerting) | CloudWatch alarm and notification resources for bridge health. | +| [dlq](#output\_dlq) | Dead-letter queue configuration and resource details. | +| [lambda](#output\_lambda) | Lambda bridge details. | +| [pubsub](#output\_pubsub) | Configured GCP Pub/Sub destination details. | +| [replayer](#output\_replayer) | DLQ replayer Lambda and event source mapping details. | +| [subscription\_filter](#output\_subscription\_filter) | CloudWatch Logs subscription filter details. | diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/alerts.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/alerts.tf new file mode 100644 index 0000000..b0d3e5e --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/alerts.tf @@ -0,0 +1,81 @@ +locals { + alerting_ok_actions = var.alerting.enable_ok_notifications ? var.alerting.sns_topic_arns : [] +} + +resource "aws_cloudwatch_metric_alarm" "lambda_errors" { + count = var.alerting.enabled ? 1 : 0 + + alarm_name = "${var.lambda.function_name}-errors" + alarm_description = "Fleet CloudWatch Pub/Sub bridge Lambda has invocation errors. Notifications fire on alarm-state transitions to avoid alert spam." + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = var.alerting.evaluation_periods + datapoints_to_alarm = var.alerting.datapoints_to_alarm + threshold = var.alerting.lambda_errors_threshold + namespace = "AWS/Lambda" + metric_name = "Errors" + period = var.alerting.period_seconds + statistic = "Sum" + treat_missing_data = "notBreaching" + + dimensions = { + FunctionName = aws_lambda_function.bridge.function_name + } + + alarm_actions = var.alerting.sns_topic_arns + ok_actions = local.alerting_ok_actions + insufficient_data_actions = [] + + tags = var.tags +} + +resource "aws_cloudwatch_metric_alarm" "dlq_visible_messages" { + count = var.alerting.enabled && var.dlq.enabled ? 1 : 0 + + alarm_name = "${local.dlq_queue_name}-visible-messages" + alarm_description = "Fleet CloudWatch Pub/Sub bridge DLQ has visible messages pending reprocessing. Notifications fire on alarm-state transitions to avoid alert spam." + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = var.alerting.evaluation_periods + datapoints_to_alarm = var.alerting.datapoints_to_alarm + threshold = var.alerting.dlq_visible_messages_threshold + namespace = "AWS/SQS" + metric_name = "ApproximateNumberOfMessagesVisible" + period = var.alerting.period_seconds + statistic = "Maximum" + treat_missing_data = "notBreaching" + + dimensions = { + QueueName = aws_sqs_queue.dlq[0].name + } + + alarm_actions = var.alerting.sns_topic_arns + ok_actions = local.alerting_ok_actions + insufficient_data_actions = [] + + tags = var.tags +} + +resource "aws_cloudwatch_metric_alarm" "replayer_errors" { + count = var.alerting.enabled && local.replayer_enabled ? 1 : 0 + + alarm_name = "${local.replayer_function_name}-errors" + alarm_description = "Fleet CloudWatch Pub/Sub bridge replayer Lambda has invocation errors. Notifications fire on alarm-state transitions to avoid alert spam." + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = var.alerting.evaluation_periods + datapoints_to_alarm = var.alerting.datapoints_to_alarm + threshold = var.alerting.lambda_errors_threshold + namespace = "AWS/Lambda" + metric_name = "Errors" + period = var.alerting.period_seconds + statistic = "Sum" + treat_missing_data = "notBreaching" + + dimensions = { + FunctionName = aws_lambda_function.replayer[0].function_name + } + + alarm_actions = var.alerting.sns_topic_arns + ok_actions = local.alerting_ok_actions + insufficient_data_actions = [] + + tags = var.tags +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/dlq.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/dlq.tf new file mode 100644 index 0000000..9b4cb73 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/dlq.tf @@ -0,0 +1,30 @@ +locals { + dlq_queue_name = coalesce(var.dlq.queue_name, "${var.lambda.function_name}-dlq") +} + +resource "aws_sqs_queue" "dlq" { + count = var.dlq.enabled ? 1 : 0 + + name = local.dlq_queue_name + message_retention_seconds = var.dlq.message_retention_seconds + visibility_timeout_seconds = var.dlq.visibility_timeout_seconds + + kms_master_key_id = var.dlq.kms_master_key_id != "" ? var.dlq.kms_master_key_id : null + sqs_managed_sse_enabled = var.dlq.kms_master_key_id == "" ? var.dlq.sqs_managed_sse_enabled : null + + tags = var.tags +} + +resource "aws_lambda_function_event_invoke_config" "bridge" { + count = var.dlq.enabled ? 1 : 0 + + function_name = aws_lambda_function.bridge.function_name + maximum_retry_attempts = var.dlq.maximum_retry_attempts + maximum_event_age_in_seconds = var.dlq.maximum_event_age_in_seconds + + destination_config { + on_failure { + destination = aws_sqs_queue.dlq[0].arn + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/iam.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/iam.tf new file mode 100644 index 0000000..0c981a0 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/iam.tf @@ -0,0 +1,201 @@ +data "aws_partition" "current" {} + +data "aws_region" "current" {} + +data "aws_caller_identity" "current" {} + +locals { + lambda_log_group_name = "/aws/lambda/${var.lambda.function_name}" + + source_log_group_arn = coalesce( + var.subscription.log_group_arn, + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:log-group:${var.subscription.log_group_name}" + ) + + source_log_group_subscription_arn = endswith(local.source_log_group_arn, ":*") ? local.source_log_group_arn : "${local.source_log_group_arn}:*" + + lambda_policy_name = coalesce( + var.lambda.policy_name, + "${var.lambda.role_name}-policy" + ) + + dlq_kms_key_arn = startswith(var.dlq.kms_master_key_id, "alias/") ? "arn:${data.aws_partition.current.partition}:kms:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:${var.dlq.kms_master_key_id}" : var.dlq.kms_master_key_id + + replayer_function_name = coalesce(var.replayer.function_name, "${var.lambda.function_name}-replayer") + replayer_role_name = coalesce(var.replayer.role_name, "${local.replayer_function_name}-role") + replayer_policy_name = coalesce(var.replayer.policy_name, "${local.replayer_role_name}-policy") + replayer_runtime = coalesce(var.replayer.runtime, var.lambda.runtime) + replayer_architecture = coalesce(var.replayer.architecture, var.lambda.architecture) + replayer_log_group_name = "/aws/lambda/${local.replayer_function_name}" + replayer_enabled = var.replayer.enabled && var.dlq.enabled + replayer_go_arch = local.replayer_architecture == "arm64" ? "arm64" : "amd64" + replayer_maximum_concurrency = var.replayer.maximum_concurrency +} + +data "aws_iam_policy_document" "lambda_assume_role" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + } +} + +resource "aws_iam_role" "bridge" { + name = var.lambda.role_name + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "lambda_basic_execution" { + role = aws_iam_role.bridge.name + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +data "aws_iam_policy_document" "bridge" { + statement { + sid = "GetPubSubCredentialsSecret" + effect = "Allow" + + actions = [ + "secretsmanager:DescribeSecret", + "secretsmanager:GetSecretValue", + ] + + resources = [var.gcp_pubsub.credentials_secret_arn] + } + + dynamic "statement" { + for_each = var.dlq.enabled ? [1] : [] + + content { + sid = "SendToAsyncFailureDLQ" + effect = "Allow" + + actions = [ + "sqs:SendMessage", + ] + + resources = [aws_sqs_queue.dlq[0].arn] + } + } + + dynamic "statement" { + for_each = var.gcp_pubsub.secret_kms_key_arn != "" ? [1] : [] + + content { + sid = "DecryptPubSubCredentialsSecretKey" + effect = "Allow" + + actions = [ + "kms:Decrypt", + ] + + resources = [var.gcp_pubsub.secret_kms_key_arn] + } + } + + dynamic "statement" { + for_each = var.dlq.enabled && var.dlq.kms_master_key_id != "" ? [1] : [] + + content { + sid = "EncryptDLQMessages" + effect = "Allow" + + actions = [ + "kms:Decrypt", + "kms:GenerateDataKey", + ] + + resources = [local.dlq_kms_key_arn] + } + } +} + +resource "aws_iam_policy" "bridge" { + name = local.lambda_policy_name + policy = data.aws_iam_policy_document.bridge.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "bridge" { + role = aws_iam_role.bridge.name + policy_arn = aws_iam_policy.bridge.arn +} + +resource "aws_iam_role" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + name = local.replayer_role_name + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "replayer_lambda_basic_execution" { + count = local.replayer_enabled ? 1 : 0 + + role = aws_iam_role.replayer[0].name + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +data "aws_iam_policy_document" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + statement { + sid = "InvokeBridgeLambda" + effect = "Allow" + + actions = [ + "lambda:InvokeFunction", + ] + + resources = [aws_lambda_function.bridge.arn] + } + + statement { + sid = "ReadFromDLQ" + effect = "Allow" + + actions = [ + "sqs:ChangeMessageVisibility", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes", + "sqs:ReceiveMessage", + ] + + resources = [aws_sqs_queue.dlq[0].arn] + } + + dynamic "statement" { + for_each = var.dlq.kms_master_key_id != "" ? [1] : [] + + content { + sid = "DecryptDLQMessages" + effect = "Allow" + + actions = [ + "kms:Decrypt", + ] + + resources = [local.dlq_kms_key_arn] + } + } +} + +resource "aws_iam_policy" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + name = local.replayer_policy_name + policy = data.aws_iam_policy_document.replayer[0].json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + role = aws_iam_role.replayer[0].name + policy_arn = aws_iam_policy.replayer[0].arn +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda.tf new file mode 100644 index 0000000..7769474 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda.tf @@ -0,0 +1,76 @@ +locals { + bridge_lambda_binary_path = "${path.module}/lambda/bootstrap" + bridge_lambda_go_arch = var.lambda.architecture == "arm64" ? "arm64" : "amd64" +} + +resource "null_resource" "bridge_build" { + triggers = { + main_go_changes = filesha256("${path.module}/lambda/main.go") + go_mod_changes = filesha256("${path.module}/lambda/go.mod") + go_sum_changes = fileexists("${path.module}/lambda/go.sum") ? filesha256("${path.module}/lambda/go.sum") : "" + go_arch = local.bridge_lambda_go_arch + binary_exists = fileexists(local.bridge_lambda_binary_path) ? true : timestamp() + } + + provisioner "local-exec" { + working_dir = "${path.module}/lambda" + command = <<-EOT + go mod download + CGO_ENABLED=0 GOOS=linux GOARCH=${local.bridge_lambda_go_arch} go build -tags lambda.norpc -o bootstrap main.go + EOT + } +} + +data "archive_file" "bridge" { + depends_on = [null_resource.bridge_build] + type = "zip" + output_path = "${path.module}/lambda/.pubsub-bridge.zip" + source_file = local.bridge_lambda_binary_path +} + +resource "aws_cloudwatch_log_group" "bridge" { + name = local.lambda_log_group_name + retention_in_days = var.lambda.log_retention_in_days + tags = var.tags +} + +resource "aws_lambda_function" "bridge" { + function_name = var.lambda.function_name + role = aws_iam_role.bridge.arn + runtime = var.lambda.runtime + handler = "bootstrap" + architectures = [var.lambda.architecture] + timeout = var.lambda.timeout + memory_size = var.lambda.memory_size + + reserved_concurrent_executions = var.lambda.reserved_concurrent_executions == -1 ? null : var.lambda.reserved_concurrent_executions + + filename = data.archive_file.bridge.output_path + source_code_hash = data.archive_file.bridge.output_base64sha256 + + environment { + variables = { + GCP_PUBSUB_PROJECT_ID = var.gcp_pubsub.project_id + GCP_PUBSUB_TOPIC_ID = var.gcp_pubsub.topic_id + GCP_CREDENTIALS_SECRET_ARN = var.gcp_pubsub.credentials_secret_arn + PUBSUB_BATCH_SIZE = tostring(var.lambda.batch_size) + } + } + + tags = var.tags + + depends_on = [ + aws_cloudwatch_log_group.bridge, + aws_iam_role_policy_attachment.lambda_basic_execution, + aws_iam_role_policy_attachment.bridge, + ] +} + +resource "aws_lambda_permission" "allow_cloudwatch_logs" { + statement_id = "AllowExecutionFromCloudWatchLogs" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.bridge.function_name + principal = "logs.${data.aws_region.current.region}.amazonaws.com" + source_account = data.aws_caller_identity.current.account_id + source_arn = local.source_log_group_subscription_arn +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.mod b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.mod new file mode 100644 index 0000000..6a8d8b7 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.mod @@ -0,0 +1,63 @@ +module github.com/fleetdm/fleet/terraform/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda + +go 1.25.7 + +require ( + cloud.google.com/go/pubsub/v2 v2.3.0 + github.com/aws/aws-lambda-go v1.41.0 + github.com/aws/aws-sdk-go-v2 v1.41.1 + github.com/aws/aws-sdk-go-v2/config v1.31.13 + github.com/aws/aws-sdk-go-v2/service/lambda v1.88.0 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.7 + github.com/stretchr/testify v1.11.1 + google.golang.org/api v0.258.0 +) + +require ( + cloud.google.com/go v0.121.6 // indirect + cloud.google.com/go/auth v0.17.0 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/compute/metadata v0.9.0 // indirect + cloud.google.com/go/iam v1.5.2 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.18.17 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.10 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.10 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.29.7 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.2 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.38.7 // indirect + github.com/aws/smithy-go v1.24.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect + github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + go.opencensus.io v0.24.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel/metric v1.38.0 // indirect + go.opentelemetry.io/otel/trace v1.38.0 // indirect + golang.org/x/crypto v0.46.0 // indirect + golang.org/x/net v0.48.0 // indirect + golang.org/x/oauth2 v0.34.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.39.0 // indirect + golang.org/x/text v0.32.0 // indirect + golang.org/x/time v0.14.0 // indirect + google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 // indirect + google.golang.org/grpc v1.77.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.sum b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.sum new file mode 100644 index 0000000..185ad9c --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/go.sum @@ -0,0 +1,227 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.121.6 h1:waZiuajrI28iAf40cWgycWNgaXPO06dupuS+sgibK6c= +cloud.google.com/go v0.121.6/go.mod h1:coChdst4Ea5vUpiALcYKXEpR1S9ZgXbhEzzMcMR66vI= +cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= +cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= +cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= +cloud.google.com/go/pubsub/v2 v2.3.0 h1:DgAN907x+sP0nScYfBzneRiIhWoXcpCD8ZAut8WX9vs= +cloud.google.com/go/pubsub/v2 v2.3.0/go.mod h1:O5f0KHG9zDheZAd3z5rlCRhxt2JQtB+t/IYLKK3Bpvw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/aws/aws-lambda-go v1.41.0 h1:l/5fyVb6Ud9uYd411xdHZzSf2n86TakxzpvIoz7l+3Y= +github.com/aws/aws-lambda-go v1.41.0/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= +github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= +github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4= +github.com/aws/aws-sdk-go-v2/config v1.31.13 h1:wcqQB3B0PgRPUF5ZE/QL1JVOyB0mbPevHFoAMpemR9k= +github.com/aws/aws-sdk-go-v2/config v1.31.13/go.mod h1:ySB5D5ybwqGbT6c3GszZ+u+3KvrlYCUQNo62+hkKOFk= +github.com/aws/aws-sdk-go-v2/credentials v1.18.17 h1:skpEwzN/+H8cdrrtT8y+rvWJGiWWv0DeNAe+4VTf+Vs= +github.com/aws/aws-sdk-go-v2/credentials v1.18.17/go.mod h1:Ed+nXsaYa5uBINovJhcAWkALvXw2ZLk36opcuiSZfJM= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.10 h1:UuGVOX48oP4vgQ36oiKmW9RuSeT8jlgQgBFQD+HUiHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.10/go.mod h1:vM/Ini41PzvudT4YkQyE/+WiQJiQ6jzeDyU8pQKwCac= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2 h1:xtuxji5CS0JknaXoACOunXOYOQzgfTvGAc9s2QdCJA4= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2/go.mod h1:zxwi0DIR0rcRcgdbl7E2MSOvxDyyXGBlScvBkARFaLQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.10 h1:DRND0dkCKtJzCj4Xl4OpVbXZgfttY5q712H9Zj7qc/0= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.10/go.mod h1:tGGNmJKOTernmR2+VJ0fCzQRurcPZj9ut60Zu5Fi6us= +github.com/aws/aws-sdk-go-v2/service/lambda v1.88.0 h1:u66DMbJWDFXs9458RAHNtq2d0gyqcZFV4mzRwfjM358= +github.com/aws/aws-sdk-go-v2/service/lambda v1.88.0/go.mod h1:ogjbkxFgFOjG3dYFQ8irC92gQfpfMDcy1RDKNSZWXNU= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.7 h1:ac9qk31MWmUlUci1tthz0iREvkjFktEeGaDF1fAgeCU= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.7/go.mod h1:A3WcpfEY2lhQvpnS6SJbMfljJuskxIKIVDcuYbIbXeE= +github.com/aws/aws-sdk-go-v2/service/sso v1.29.7 h1:fspVFg6qMx0svs40YgRmE7LZXh9VRZvTT35PfdQR6FM= +github.com/aws/aws-sdk-go-v2/service/sso v1.29.7/go.mod h1:BQTKL3uMECaLaUV3Zc2L4Qybv8C6BIXjuu1dOPyxTQs= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.2 h1:scVnW+NLXasGOhy7HhkdT9AGb6kjgW7fJ5xYkUaqHs0= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.2/go.mod h1:FRNCY3zTEWZXBKm2h5UBUPvCVDOecTad9KhynDyGBc0= +github.com/aws/aws-sdk-go-v2/service/sts v1.38.7 h1:VEO5dqFkMsl8QZ2yHsFDJAIZLAkEbaYDB+xdKi0Feic= +github.com/aws/aws-sdk-go-v2/service/sts v1.38.7/go.mod h1:L1xxV3zAdB+qVrVW/pBIrIAnHFWHo6FBbFe4xOGsG/o= +github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= +github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f h1:Y8xYupdHxryycyPlc9Y+bSQAYZnetRJ70VMVKm5CKI0= +github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329 h1:K+fnvUM0VZ7ZFJf0n4L/BRlnsb9pL/GuDG6FqaH+PwM= +github.com/envoyproxy/go-control-plane/envoy v1.35.0 h1:ixjkELDE+ru6idPxcHLj8LBVc2bFP7iBytj353BoHUo= +github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= +github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= +github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.einride.tech/aip v0.73.0 h1:bPo4oqBo2ZQeBKo4ZzLb1kxYXTY1ysJhpvQyfuGzvps= +go.einride.tech/aip v0.73.0/go.mod h1:Mj7rFbmXEgw0dq1dqJ7JGMvYCZZVxmGOR3S4ZcV5LvQ= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc= +google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= +google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 h1:mepRgnBZa07I4TRuomDE4sTIYieg/osKmzIf4USdWS4= +google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 h1:2I6GHUeJ/4shcDpoUlLs/2WPnhg7yJwvXtqcMJt9liA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= +google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main.go b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main.go new file mode 100644 index 0000000..86f899c --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main.go @@ -0,0 +1,374 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + "sync" + "time" + + pubsub "cloud.google.com/go/pubsub/v2" + "github.com/aws/aws-lambda-go/lambda" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + "google.golang.org/api/option" +) + +const defaultPubSubBatchMax = 1000 + +const defaultCredentialsCacheTTL = 5 * time.Minute + +type cloudWatchLogsEvent struct { + AWSLogs struct { + Data string `json:"data"` + } `json:"awslogs"` +} + +type cloudWatchPayload struct { + Owner string `json:"owner"` + LogGroup string `json:"logGroup"` + LogStream string `json:"logStream"` + SubscriptionFilters []string `json:"subscriptionFilters"` + MessageType string `json:"messageType"` + LogEvents []struct { + ID string `json:"id"` + Timestamp int64 `json:"timestamp"` + Message string `json:"message"` + } `json:"logEvents"` +} + +type outboundMessage struct { + Data []byte + Attributes map[string]string +} + +type serviceAccountCredentials struct { + ClientEmail string `json:"client_email"` + PrivateKey string `json:"private_key"` +} + +type cacheState struct { + secretARN string + credentialsJSON []byte + credentialsFetched time.Time + + projectID string + topicReference string + pubsubClient *pubsub.Client + publisher *pubsub.Publisher +} + +var ( + cacheMu sync.Mutex + cache cacheState + + credentialsCacheTTL = defaultCredentialsCacheTTL + + getPublisherFunc = getPublisher + publishBatchFunc = publishBatch +) + +func mustGetEnv(name string) (string, error) { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return "", fmt.Errorf("missing required environment variable: %s", name) + } + return value, nil +} + +func parseServiceAccountSecret(secretText string) ([]byte, error) { + candidatePayload := []byte(secretText) + + var raw map[string]json.RawMessage + if err := json.Unmarshal([]byte(secretText), &raw); err == nil { + if nested, ok := raw["service_account_json"]; ok && len(nested) > 0 { + var nestedString string + if err := json.Unmarshal(nested, &nestedString); err == nil { + candidatePayload = []byte(nestedString) + } else { + candidatePayload = nested + } + } + } + + var creds serviceAccountCredentials + if err := json.Unmarshal(candidatePayload, &creds); err != nil { + return nil, fmt.Errorf("parse service account json: %w", err) + } + + if strings.TrimSpace(creds.ClientEmail) == "" || strings.TrimSpace(creds.PrivateKey) == "" { + return nil, errors.New("service account json must include client_email and private_key") + } + + return candidatePayload, nil +} + +func getServiceAccountJSON(ctx context.Context, secretARN string) ([]byte, error) { + cacheMu.Lock() + if cache.secretARN == secretARN && len(cache.credentialsJSON) > 0 && time.Since(cache.credentialsFetched) < credentialsCacheTTL { + cached := make([]byte, len(cache.credentialsJSON)) + copy(cached, cache.credentialsJSON) + cacheMu.Unlock() + return cached, nil + } + cacheMu.Unlock() + + cfg, err := config.LoadDefaultConfig(ctx) + if err != nil { + return nil, fmt.Errorf("load aws sdk config: %w", err) + } + + smClient := secretsmanager.NewFromConfig(cfg) + secretValue, err := smClient.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{SecretId: aws.String(secretARN)}) + if err != nil { + return nil, fmt.Errorf("get secret value: %w", err) + } + + var secretText string + switch { + case secretValue.SecretString != nil: + secretText = *secretValue.SecretString + case len(secretValue.SecretBinary) > 0: + secretText = string(secretValue.SecretBinary) + default: + return nil, errors.New("secret has no SecretString or SecretBinary payload") + } + + credentialsJSON, err := parseServiceAccountSecret(secretText) + if err != nil { + return nil, err + } + + cacheMu.Lock() + cache.secretARN = secretARN + cache.credentialsJSON = make([]byte, len(credentialsJSON)) + copy(cache.credentialsJSON, credentialsJSON) + cache.credentialsFetched = time.Now() + cacheMu.Unlock() + + return credentialsJSON, nil +} + +func getPublisher(ctx context.Context, projectID, topicID, secretARN string) (*pubsub.Publisher, error) { + topicReference := topicID + + cacheMu.Lock() + if cache.publisher != nil && + cache.projectID == projectID && + cache.topicReference == topicReference && + cache.secretARN == secretARN && + time.Since(cache.credentialsFetched) < credentialsCacheTTL { + publisher := cache.publisher + cacheMu.Unlock() + return publisher, nil + } + cacheMu.Unlock() + + credentialsJSON, err := getServiceAccountJSON(ctx, secretARN) + if err != nil { + return nil, err + } + + client, err := pubsub.NewClient(ctx, projectID, option.WithAuthCredentialsJSON(option.ServiceAccount, credentialsJSON)) + if err != nil { + return nil, fmt.Errorf("create pubsub client: %w", err) + } + + publisher := client.Publisher(topicReference) + + cacheMu.Lock() + if cache.publisher != nil { + cache.publisher.Stop() + } + if cache.pubsubClient != nil { + _ = cache.pubsubClient.Close() + } + + cache.projectID = projectID + cache.topicReference = topicReference + cache.secretARN = secretARN + cache.pubsubClient = client + cache.publisher = publisher + cacheMu.Unlock() + + return publisher, nil +} + +func decodeCloudWatchPayload(event cloudWatchLogsEvent) (*cloudWatchPayload, error) { + if strings.TrimSpace(event.AWSLogs.Data) == "" { + return nil, errors.New("event missing awslogs.data") + } + + compressed, err := base64.StdEncoding.DecodeString(event.AWSLogs.Data) + if err != nil { + return nil, fmt.Errorf("decode awslogs.data: %w", err) + } + + reader, err := gzip.NewReader(bytes.NewReader(compressed)) + if err != nil { + return nil, fmt.Errorf("open gzip payload: %w", err) + } + defer reader.Close() + + decoded, err := io.ReadAll(reader) + if err != nil { + return nil, fmt.Errorf("read gzip payload: %w", err) + } + + var payload cloudWatchPayload + if err := json.Unmarshal(decoded, &payload); err != nil { + return nil, fmt.Errorf("parse cloudwatch payload: %w", err) + } + + return &payload, nil +} + +func buildOutboundMessages(payload *cloudWatchPayload) ([]outboundMessage, error) { + if payload.MessageType == "CONTROL_MESSAGE" { + return nil, nil + } + + messages := make([]outboundMessage, 0, len(payload.LogEvents)) + for _, event := range payload.LogEvents { + envelope := map[string]interface{}{ + "owner": payload.Owner, + "logGroup": payload.LogGroup, + "logStream": payload.LogStream, + "subscriptionFilters": payload.SubscriptionFilters, + "id": event.ID, + "timestamp": event.Timestamp, + "message": event.Message, + } + + serialized, err := json.Marshal(envelope) + if err != nil { + return nil, fmt.Errorf("marshal message payload: %w", err) + } + + messages = append(messages, outboundMessage{ + Data: serialized, + Attributes: map[string]string{ + "owner": payload.Owner, + "log_group": payload.LogGroup, + "log_stream": payload.LogStream, + }, + }) + } + + return messages, nil +} + +func resolveBatchSize() int { + batchSize := defaultPubSubBatchMax + raw := strings.TrimSpace(os.Getenv("PUBSUB_BATCH_SIZE")) + if raw == "" { + return batchSize + } + + parsed, err := strconv.Atoi(raw) + if err != nil || parsed < 1 || parsed > defaultPubSubBatchMax { + return batchSize + } + + return parsed +} + +func splitBatches(messages []outboundMessage, batchSize int) [][]outboundMessage { + batches := make([][]outboundMessage, 0, (len(messages)+batchSize-1)/batchSize) + for i := 0; i < len(messages); i += batchSize { + end := i + batchSize + if end > len(messages) { + end = len(messages) + } + batches = append(batches, messages[i:end]) + } + return batches +} + +func publishBatch(ctx context.Context, publisher *pubsub.Publisher, messages []outboundMessage) error { + results := make([]*pubsub.PublishResult, 0, len(messages)) + for _, message := range messages { + result := publisher.Publish(ctx, &pubsub.Message{ + Data: message.Data, + Attributes: message.Attributes, + }) + results = append(results, result) + } + + for _, result := range results { + if _, err := result.Get(ctx); err != nil { + return err + } + } + + return nil +} + +func handler(ctx context.Context, event cloudWatchLogsEvent) (map[string]interface{}, error) { + projectID, err := mustGetEnv("GCP_PUBSUB_PROJECT_ID") + if err != nil { + return nil, err + } + + topicID, err := mustGetEnv("GCP_PUBSUB_TOPIC_ID") + if err != nil { + return nil, err + } + + secretARN, err := mustGetEnv("GCP_CREDENTIALS_SECRET_ARN") + if err != nil { + return nil, err + } + + payload, err := decodeCloudWatchPayload(event) + if err != nil { + return nil, err + } + + messages, err := buildOutboundMessages(payload) + if err != nil { + return nil, err + } + + messageType := payload.MessageType + if messageType == "" { + messageType = "UNKNOWN" + } + + if len(messages) == 0 { + return map[string]interface{}{ + "published_message_count": 0, + "message_type": messageType, + }, nil + } + + publisher, err := getPublisherFunc(ctx, projectID, topicID, secretARN) + if err != nil { + return nil, err + } + + batchSize := resolveBatchSize() + for _, batch := range splitBatches(messages, batchSize) { + if err := publishBatchFunc(ctx, publisher, batch); err != nil { + return nil, err + } + } + + return map[string]interface{}{ + "published_message_count": len(messages), + "message_type": messageType, + }, nil +} + +func main() { + lambda.Start(handler) +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main_test.go b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main_test.go new file mode 100644 index 0000000..8a636c1 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/main_test.go @@ -0,0 +1,224 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "errors" + "testing" + + pubsub "cloud.google.com/go/pubsub/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func resetMainTestState() { + cacheMu.Lock() + cache = cacheState{} + cacheMu.Unlock() + + credentialsCacheTTL = defaultCredentialsCacheTTL + getPublisherFunc = getPublisher + publishBatchFunc = publishBatch +} + +func makeCloudWatchEvent(t *testing.T, payload map[string]interface{}) cloudWatchLogsEvent { + t.Helper() + + raw, err := json.Marshal(payload) + require.NoError(t, err) + + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + _, err = gz.Write(raw) + require.NoError(t, err) + require.NoError(t, gz.Close()) + + var ev cloudWatchLogsEvent + ev.AWSLogs.Data = base64.StdEncoding.EncodeToString(buf.Bytes()) + return ev +} + +func TestParseServiceAccountSecret(t *testing.T) { + t.Run("direct service account", func(t *testing.T) { + secret := `{"client_email":"x@example.com","private_key":"key"}` + got, err := parseServiceAccountSecret(secret) + require.NoError(t, err) + + var parsed serviceAccountCredentials + require.NoError(t, json.Unmarshal(got, &parsed)) + assert.Equal(t, "x@example.com", parsed.ClientEmail) + }) + + t.Run("nested service_account_json string", func(t *testing.T) { + secret := `{"service_account_json":"{\"client_email\":\"x@example.com\",\"private_key\":\"key\"}"}` + _, err := parseServiceAccountSecret(secret) + require.NoError(t, err) + }) + + t.Run("nested service_account_json object", func(t *testing.T) { + secret := `{"service_account_json":{"client_email":"x@example.com","private_key":"key"}}` + _, err := parseServiceAccountSecret(secret) + require.NoError(t, err) + }) + + t.Run("missing required fields", func(t *testing.T) { + _, err := parseServiceAccountSecret(`{"client_email":"x@example.com"}`) + require.Error(t, err) + }) +} + +func TestDecodeCloudWatchPayload(t *testing.T) { + t.Run("success", func(t *testing.T) { + ev := makeCloudWatchEvent(t, map[string]interface{}{ + "owner": "123", + "logGroup": "group", + "logStream": "stream", + "messageType": "DATA_MESSAGE", + "logEvents": []map[string]interface{}{ + {"id": "1", "timestamp": 10, "message": "hello"}, + }, + }) + + payload, err := decodeCloudWatchPayload(ev) + require.NoError(t, err) + assert.Equal(t, "group", payload.LogGroup) + }) + + t.Run("missing data", func(t *testing.T) { + _, err := decodeCloudWatchPayload(cloudWatchLogsEvent{}) + require.Error(t, err) + }) + + t.Run("invalid base64", func(t *testing.T) { + var ev cloudWatchLogsEvent + ev.AWSLogs.Data = "%%%%" + _, err := decodeCloudWatchPayload(ev) + require.Error(t, err) + }) +} + +func TestBuildOutboundMessages(t *testing.T) { + payload := &cloudWatchPayload{ + Owner: "123", + LogGroup: "group", + LogStream: "stream", + MessageType: "DATA_MESSAGE", + LogEvents: []struct { + ID string `json:"id"` + Timestamp int64 `json:"timestamp"` + Message string `json:"message"` + }{ + {ID: "1", Timestamp: 10, Message: "hello"}, + }, + } + + msgs, err := buildOutboundMessages(payload) + require.NoError(t, err) + require.Len(t, msgs, 1) + assert.Equal(t, "group", msgs[0].Attributes["log_group"]) + + control, err := buildOutboundMessages(&cloudWatchPayload{MessageType: "CONTROL_MESSAGE"}) + require.NoError(t, err) + assert.Nil(t, control) +} + +func TestResolveBatchSize(t *testing.T) { + t.Setenv("PUBSUB_BATCH_SIZE", "5") + assert.Equal(t, 5, resolveBatchSize()) + + t.Setenv("PUBSUB_BATCH_SIZE", "2000") + assert.Equal(t, defaultPubSubBatchMax, resolveBatchSize()) + + t.Setenv("PUBSUB_BATCH_SIZE", "nope") + assert.Equal(t, defaultPubSubBatchMax, resolveBatchSize()) +} + +func TestSplitBatches(t *testing.T) { + messages := []outboundMessage{{}, {}, {}, {}, {}} + batches := splitBatches(messages, 2) + require.Len(t, batches, 3) + assert.Len(t, batches[2], 1) +} + +func TestHandler(t *testing.T) { + resetMainTestState() + t.Cleanup(resetMainTestState) + + t.Setenv("GCP_PUBSUB_PROJECT_ID", "proj") + t.Setenv("GCP_PUBSUB_TOPIC_ID", "topic") + t.Setenv("GCP_CREDENTIALS_SECRET_ARN", "arn:aws:secretsmanager:us-east-2:111111111111:secret:x") + t.Setenv("PUBSUB_BATCH_SIZE", "2") + + ev := makeCloudWatchEvent(t, map[string]interface{}{ + "owner": "123", + "logGroup": "group", + "logStream": "stream", + "messageType": "DATA_MESSAGE", + "logEvents": []map[string]interface{}{ + {"id": "1", "timestamp": 10, "message": "m1"}, + {"id": "2", "timestamp": 11, "message": "m2"}, + {"id": "3", "timestamp": 12, "message": "m3"}, + }, + }) + + var batchSizes []int + getPublisherFunc = func(ctx context.Context, projectID, topicID, secretARN string) (*pubsub.Publisher, error) { + return nil, nil + } + publishBatchFunc = func(ctx context.Context, publisher *pubsub.Publisher, messages []outboundMessage) error { + batchSizes = append(batchSizes, len(messages)) + return nil + } + + resp, err := handler(context.Background(), ev) + require.NoError(t, err) + assert.Equal(t, []int{2, 1}, batchSizes) + assert.Equal(t, 3, resp["published_message_count"]) + assert.Equal(t, "DATA_MESSAGE", resp["message_type"]) +} + +func TestHandlerPublishError(t *testing.T) { + resetMainTestState() + t.Cleanup(resetMainTestState) + + t.Setenv("GCP_PUBSUB_PROJECT_ID", "proj") + t.Setenv("GCP_PUBSUB_TOPIC_ID", "topic") + t.Setenv("GCP_CREDENTIALS_SECRET_ARN", "arn:aws:secretsmanager:us-east-2:111111111111:secret:x") + + ev := makeCloudWatchEvent(t, map[string]interface{}{ + "owner": "123", + "messageType": "DATA_MESSAGE", + "logEvents": []map[string]interface{}{ + {"id": "1", "timestamp": 10, "message": "m1"}, + }, + }) + + getPublisherFunc = func(ctx context.Context, projectID, topicID, secretARN string) (*pubsub.Publisher, error) { + return nil, nil + } + publishBatchFunc = func(ctx context.Context, publisher *pubsub.Publisher, messages []outboundMessage) error { + return errors.New("boom") + } + + _, err := handler(context.Background(), ev) + require.Error(t, err) +} + +func TestHandlerMissingEnv(t *testing.T) { + resetMainTestState() + t.Cleanup(resetMainTestState) + + t.Setenv("GCP_PUBSUB_PROJECT_ID", "") + t.Setenv("GCP_PUBSUB_TOPIC_ID", "topic") + t.Setenv("GCP_CREDENTIALS_SECRET_ARN", "arn:aws:secretsmanager:us-east-2:111111111111:secret:x") + + ev := makeCloudWatchEvent(t, map[string]interface{}{ + "messageType": "CONTROL_MESSAGE", + }) + + _, err := handler(context.Background(), ev) + require.Error(t, err) +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main.go b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main.go new file mode 100644 index 0000000..7ea655e --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main.go @@ -0,0 +1,122 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "sync" + + "github.com/aws/aws-lambda-go/events" + "github.com/aws/aws-lambda-go/lambda" + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + awslambda "github.com/aws/aws-sdk-go-v2/service/lambda" + "github.com/aws/aws-sdk-go-v2/service/lambda/types" +) + +type asyncDestinationMessage struct { + RequestPayload json.RawMessage `json:"requestPayload"` + RequestContext struct { + RequestID string `json:"requestId"` + } `json:"requestContext"` +} + +type lambdaInvoker interface { + Invoke(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) +} + +var ( + lambdaClientOnce sync.Once + lambdaClient lambdaInvoker + lambdaClientErr error + + getLambdaClientFunc = getLambdaClient + replayOneFunc = replayOne +) + +func getTargetFunctionName() (string, error) { + name := strings.TrimSpace(os.Getenv("TARGET_BRIDGE_FUNCTION_NAME")) + if name == "" { + return "", errors.New("missing required environment variable: TARGET_BRIDGE_FUNCTION_NAME") + } + return name, nil +} + +func getLambdaClient(ctx context.Context) (lambdaInvoker, error) { + lambdaClientOnce.Do(func() { + cfg, err := awsconfig.LoadDefaultConfig(ctx) + if err != nil { + lambdaClientErr = fmt.Errorf("load aws sdk config: %w", err) + return + } + lambdaClient = awslambda.NewFromConfig(cfg) + }) + + if lambdaClientErr != nil { + return nil, lambdaClientErr + } + return lambdaClient, nil +} + +func extractOriginalPayload(body string) ([]byte, error) { + var message asyncDestinationMessage + if err := json.Unmarshal([]byte(body), &message); err != nil { + return nil, fmt.Errorf("parse async destination message: %w", err) + } + + if len(message.RequestPayload) == 0 { + return nil, errors.New("async destination message does not include requestPayload") + } + + return message.RequestPayload, nil +} + +func replayOne(ctx context.Context, client lambdaInvoker, targetFunctionName string, record events.SQSMessage) error { + payload, err := extractOriginalPayload(record.Body) + if err != nil { + return err + } + + resp, err := client.Invoke(ctx, &awslambda.InvokeInput{ + FunctionName: aws.String(targetFunctionName), + InvocationType: types.InvocationTypeEvent, + Payload: payload, + }) + if err != nil { + return fmt.Errorf("invoke bridge lambda: %w", err) + } + + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return fmt.Errorf("invoke bridge lambda unexpected status code: %d", resp.StatusCode) + } + + return nil +} + +func handler(ctx context.Context, event events.SQSEvent) (events.SQSEventResponse, error) { + targetFunctionName, err := getTargetFunctionName() + if err != nil { + return events.SQSEventResponse{}, err + } + + client, err := getLambdaClientFunc(ctx) + if err != nil { + return events.SQSEventResponse{}, err + } + + failures := make([]events.SQSBatchItemFailure, 0) + for _, record := range event.Records { + if err := replayOneFunc(ctx, client, targetFunctionName, record); err != nil { + failures = append(failures, events.SQSBatchItemFailure{ItemIdentifier: record.MessageId}) + } + } + + return events.SQSEventResponse{BatchItemFailures: failures}, nil +} + +func main() { + lambda.Start(handler) +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main_test.go b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main_test.go new file mode 100644 index 0000000..f5513a3 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/lambda/replayer/main_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "sync" + "testing" + + "github.com/aws/aws-lambda-go/events" + awslambda "github.com/aws/aws-sdk-go-v2/service/lambda" + "github.com/aws/aws-sdk-go-v2/service/lambda/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type fakeLambdaInvoker struct { + invokeFn func(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) +} + +func (f *fakeLambdaInvoker) Invoke(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) { + if f.invokeFn != nil { + return f.invokeFn(ctx, params, optFns...) + } + return &awslambda.InvokeOutput{StatusCode: 202}, nil +} + +func resetReplayerTestState() { + lambdaClientOnce = sync.Once{} + lambdaClient = nil + lambdaClientErr = nil + getLambdaClientFunc = getLambdaClient + replayOneFunc = replayOne +} + +func mustJSON(t *testing.T, v interface{}) string { + t.Helper() + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) +} + +func TestExtractOriginalPayload(t *testing.T) { + body := `{"requestPayload":{"awslogs":{"data":"abc"}},"requestContext":{"requestId":"r1"}}` + payload, err := extractOriginalPayload(body) + require.NoError(t, err) + assert.Equal(t, `{"awslogs":{"data":"abc"}}`, string(payload)) + + _, err = extractOriginalPayload(`{"requestContext":{"requestId":"r1"}}`) + require.Error(t, err) +} + +func TestReplayOne(t *testing.T) { + record := events.SQSMessage{Body: `{"requestPayload":{"awslogs":{"data":"abc"}}}`} + + t.Run("success", func(t *testing.T) { + invoker := &fakeLambdaInvoker{invokeFn: func(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) { + require.NotNil(t, params.FunctionName) + assert.Equal(t, "bridge", *params.FunctionName) + assert.Equal(t, types.InvocationTypeEvent, params.InvocationType) + assert.Equal(t, `{"awslogs":{"data":"abc"}}`, string(params.Payload)) + return &awslambda.InvokeOutput{StatusCode: 202}, nil + }} + + require.NoError(t, replayOne(context.Background(), invoker, "bridge", record)) + }) + + t.Run("invoke error", func(t *testing.T) { + invoker := &fakeLambdaInvoker{invokeFn: func(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) { + return nil, errors.New("boom") + }} + + require.Error(t, replayOne(context.Background(), invoker, "bridge", record)) + }) + + t.Run("non 2xx status", func(t *testing.T) { + invoker := &fakeLambdaInvoker{invokeFn: func(ctx context.Context, params *awslambda.InvokeInput, optFns ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) { + return &awslambda.InvokeOutput{StatusCode: 500}, nil + }} + + require.Error(t, replayOne(context.Background(), invoker, "bridge", record)) + }) +} + +func TestHandler(t *testing.T) { + resetReplayerTestState() + t.Cleanup(resetReplayerTestState) + + t.Setenv("TARGET_BRIDGE_FUNCTION_NAME", "bridge") + getLambdaClientFunc = func(ctx context.Context) (lambdaInvoker, error) { + return &fakeLambdaInvoker{}, nil + } + + replayOneFunc = func(ctx context.Context, client lambdaInvoker, targetFunctionName string, record events.SQSMessage) error { + if record.MessageId == "bad" { + return errors.New("replay failed") + } + return nil + } + + event := events.SQSEvent{Records: []events.SQSMessage{ + {MessageId: "ok", Body: mustJSON(t, map[string]interface{}{"requestPayload": map[string]interface{}{"k": "v"}})}, + {MessageId: "bad", Body: mustJSON(t, map[string]interface{}{"requestPayload": map[string]interface{}{"k": "v2"}})}, + }} + + resp, err := handler(context.Background(), event) + require.NoError(t, err) + require.Len(t, resp.BatchItemFailures, 1) + assert.Equal(t, "bad", resp.BatchItemFailures[0].ItemIdentifier) +} + +func TestHandlerErrors(t *testing.T) { + resetReplayerTestState() + t.Cleanup(resetReplayerTestState) + + t.Run("missing target env", func(t *testing.T) { + t.Setenv("TARGET_BRIDGE_FUNCTION_NAME", "") + _, err := handler(context.Background(), events.SQSEvent{}) + require.Error(t, err) + }) + + t.Run("client creation error", func(t *testing.T) { + t.Setenv("TARGET_BRIDGE_FUNCTION_NAME", "bridge") + getLambdaClientFunc = func(ctx context.Context) (lambdaInvoker, error) { + return nil, errors.New("no client") + } + _, err := handler(context.Background(), events.SQSEvent{}) + require.Error(t, err) + }) +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/outputs.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/outputs.tf new file mode 100644 index 0000000..fb1f16a --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/outputs.tf @@ -0,0 +1,67 @@ +output "lambda" { + description = "Lambda bridge details." + value = { + arn = aws_lambda_function.bridge.arn + function_name = aws_lambda_function.bridge.function_name + role_arn = aws_iam_role.bridge.arn + log_group_name = aws_cloudwatch_log_group.bridge.name + } +} + +output "subscription_filter" { + description = "CloudWatch Logs subscription filter details." + value = { + name = aws_cloudwatch_log_subscription_filter.bridge.name + log_group_name = aws_cloudwatch_log_subscription_filter.bridge.log_group_name + destination_arn = aws_cloudwatch_log_subscription_filter.bridge.destination_arn + } +} + +output "pubsub" { + description = "Configured GCP Pub/Sub destination details." + value = { + project_id = var.gcp_pubsub.project_id + topic_id = var.gcp_pubsub.topic_id + credentials_secret_arn = var.gcp_pubsub.credentials_secret_arn + } +} + +output "dlq" { + description = "Dead-letter queue configuration and resource details." + value = { + enabled = var.dlq.enabled + queue_name = try(aws_sqs_queue.dlq[0].name, null) + queue_arn = try(aws_sqs_queue.dlq[0].arn, null) + queue_url = try(aws_sqs_queue.dlq[0].url, null) + maximum_retry_attempts = var.dlq.maximum_retry_attempts + maximum_event_age_in_seconds = var.dlq.maximum_event_age_in_seconds + } +} + +output "alerting" { + description = "CloudWatch alarm and notification resources for bridge health." + value = { + enabled = var.alerting.enabled + sns_topic_arns = var.alerting.sns_topic_arns + lambda_errors_alarm_name = try(aws_cloudwatch_metric_alarm.lambda_errors[0].alarm_name, null) + lambda_errors_alarm_arn = try(aws_cloudwatch_metric_alarm.lambda_errors[0].arn, null) + replayer_errors_alarm_name = try(aws_cloudwatch_metric_alarm.replayer_errors[0].alarm_name, null) + replayer_errors_alarm_arn = try(aws_cloudwatch_metric_alarm.replayer_errors[0].arn, null) + dlq_visible_messages_alarm_name = try(aws_cloudwatch_metric_alarm.dlq_visible_messages[0].alarm_name, null) + dlq_visible_messages_alarm_arn = try(aws_cloudwatch_metric_alarm.dlq_visible_messages[0].arn, null) + } +} + +output "replayer" { + description = "DLQ replayer Lambda and event source mapping details." + value = { + enabled = local.replayer_enabled + function_name = try(aws_lambda_function.replayer[0].function_name, null) + function_arn = try(aws_lambda_function.replayer[0].arn, null) + role_arn = try(aws_iam_role.replayer[0].arn, null) + event_source_mapping_uuid = try(aws_lambda_event_source_mapping.replayer[0].uuid, null) + batch_size = var.replayer.batch_size + maximum_batching_window_seconds = var.replayer.maximum_batching_window_in_seconds + maximum_concurrency = var.replayer.maximum_concurrency + } +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/replayer.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/replayer.tf new file mode 100644 index 0000000..97b41ed --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/replayer.tf @@ -0,0 +1,90 @@ +locals { + replayer_lambda_binary_path = "${path.module}/lambda/replayer/bootstrap" +} + +resource "null_resource" "replayer_build" { + count = local.replayer_enabled ? 1 : 0 + + triggers = { + main_go_changes = filesha256("${path.module}/lambda/replayer/main.go") + go_mod_changes = filesha256("${path.module}/lambda/go.mod") + go_sum_changes = fileexists("${path.module}/lambda/go.sum") ? filesha256("${path.module}/lambda/go.sum") : "" + go_arch = local.replayer_go_arch + binary_exists = fileexists(local.replayer_lambda_binary_path) ? true : timestamp() + } + + provisioner "local-exec" { + working_dir = "${path.module}/lambda" + command = <<-EOT + go mod download + CGO_ENABLED=0 GOOS=linux GOARCH=${local.replayer_go_arch} go build -tags lambda.norpc -o replayer/bootstrap ./replayer + EOT + } +} + +data "archive_file" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + depends_on = [null_resource.replayer_build[0]] + type = "zip" + output_path = "${path.module}/lambda/.pubsub-bridge-replayer.zip" + source_file = local.replayer_lambda_binary_path +} + +resource "aws_cloudwatch_log_group" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + name = local.replayer_log_group_name + retention_in_days = var.replayer.log_retention_in_days + tags = var.tags +} + +resource "aws_lambda_function" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + function_name = local.replayer_function_name + role = aws_iam_role.replayer[0].arn + runtime = local.replayer_runtime + handler = "bootstrap" + architectures = [local.replayer_architecture] + timeout = var.replayer.timeout + memory_size = var.replayer.memory_size + + reserved_concurrent_executions = var.replayer.reserved_concurrent_executions == -1 ? null : var.replayer.reserved_concurrent_executions + + filename = data.archive_file.replayer[0].output_path + source_code_hash = data.archive_file.replayer[0].output_base64sha256 + + environment { + variables = { + TARGET_BRIDGE_FUNCTION_NAME = aws_lambda_function.bridge.function_name + } + } + + tags = var.tags + + depends_on = [ + aws_cloudwatch_log_group.replayer, + aws_iam_role_policy_attachment.replayer_lambda_basic_execution, + aws_iam_role_policy_attachment.replayer, + ] +} + +resource "aws_lambda_event_source_mapping" "replayer" { + count = local.replayer_enabled ? 1 : 0 + + event_source_arn = aws_sqs_queue.dlq[0].arn + function_name = aws_lambda_function.replayer[0].arn + batch_size = var.replayer.batch_size + maximum_batching_window_in_seconds = var.replayer.maximum_batching_window_in_seconds + function_response_types = ["ReportBatchItemFailures"] + enabled = true + + dynamic "scaling_config" { + for_each = local.replayer_maximum_concurrency > 0 ? [1] : [] + + content { + maximum_concurrency = local.replayer_maximum_concurrency + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/subscription.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/subscription.tf new file mode 100644 index 0000000..c9bae8e --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/subscription.tf @@ -0,0 +1,8 @@ +resource "aws_cloudwatch_log_subscription_filter" "bridge" { + name = var.subscription.filter_name + log_group_name = var.subscription.log_group_name + filter_pattern = var.subscription.filter_pattern + destination_arn = aws_lambda_function.bridge.arn + + depends_on = [aws_lambda_permission.allow_cloudwatch_logs] +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/variables.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/variables.tf new file mode 100644 index 0000000..b641ef5 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/variables.tf @@ -0,0 +1,314 @@ +variable "subscription" { + description = "CloudWatch Logs subscription settings for sending Fleet log events to the Pub/Sub bridge Lambda." + type = object({ + log_group_name = string + log_group_arn = optional(string) + filter_name = optional(string, "fleet-log-pubsub-bridge") + filter_pattern = optional(string, "") + }) + + validation { + condition = length(trimspace(var.subscription.log_group_name)) > 0 + error_message = "subscription.log_group_name must not be empty." + } + + validation { + condition = ( + !can(var.subscription.log_group_arn) || + var.subscription.log_group_arn == null || + startswith(var.subscription.log_group_arn, "arn:") + ) + error_message = "subscription.log_group_arn must be a valid ARN when provided." + } +} + +variable "lambda" { + description = "Go-based Lambda bridge configuration." + type = object({ + function_name = optional(string, "fleet-cloudwatch-pubsub-bridge") + role_name = optional(string, "fleet-cloudwatch-pubsub-bridge-role") + policy_name = optional(string) + runtime = optional(string, "provided.al2") + architecture = optional(string, "x86_64") + memory_size = optional(number, 256) + timeout = optional(number, 60) + log_retention_in_days = optional(number, 30) + reserved_concurrent_executions = optional(number, -1) + batch_size = optional(number, 1000) + }) + default = {} + + validation { + condition = contains(["provided.al2", "provided.al2023"], var.lambda.runtime) + error_message = "lambda.runtime must be one of: provided.al2, provided.al2023." + } + + validation { + condition = contains(["x86_64", "arm64"], var.lambda.architecture) + error_message = "lambda.architecture must be one of: x86_64, arm64." + } + + validation { + condition = var.lambda.memory_size >= 128 && var.lambda.memory_size <= 10240 + error_message = "lambda.memory_size must be between 128 and 10240 MB." + } + + validation { + condition = var.lambda.timeout >= 1 && var.lambda.timeout <= 900 + error_message = "lambda.timeout must be between 1 and 900 seconds." + } + + validation { + condition = var.lambda.batch_size >= 1 && var.lambda.batch_size <= 1000 + error_message = "lambda.batch_size must be between 1 and 1000." + } + + validation { + condition = ( + var.lambda.reserved_concurrent_executions == -1 || + var.lambda.reserved_concurrent_executions >= 1 + ) + error_message = "lambda.reserved_concurrent_executions must be -1 (unreserved) or >= 1." + } +} + +variable "gcp_pubsub" { + description = "GCP Pub/Sub settings and credentials secret reference for cloud.google.com/go/pubsub/v2. The secret must contain a Google service-account key JSON, or a JSON object with a service_account_json field containing that key JSON." + type = object({ + project_id = string + topic_id = string + credentials_secret_arn = string + secret_kms_key_arn = optional(string, "") + }) + + validation { + condition = length(trimspace(var.gcp_pubsub.project_id)) > 0 + error_message = "gcp_pubsub.project_id must not be empty." + } + + validation { + condition = length(trimspace(var.gcp_pubsub.topic_id)) > 0 + error_message = "gcp_pubsub.topic_id must not be empty." + } + + validation { + condition = startswith(var.gcp_pubsub.credentials_secret_arn, "arn:") + error_message = "gcp_pubsub.credentials_secret_arn must be a Secrets Manager ARN." + } + + validation { + condition = ( + var.gcp_pubsub.secret_kms_key_arn == "" || + startswith(var.gcp_pubsub.secret_kms_key_arn, "arn:") + ) + error_message = "gcp_pubsub.secret_kms_key_arn must be empty or a valid KMS key ARN." + } +} + +variable "dlq" { + description = "Asynchronous Lambda failure handling via SQS dead-letter queue." + type = object({ + enabled = optional(bool, true) + queue_name = optional(string) + maximum_retry_attempts = optional(number, 2) + maximum_event_age_in_seconds = optional(number, 3600) + message_retention_seconds = optional(number, 1209600) + visibility_timeout_seconds = optional(number, 60) + sqs_managed_sse_enabled = optional(bool, true) + kms_master_key_id = optional(string, "") + }) + default = {} + + validation { + condition = ( + !can(var.dlq.queue_name) || + var.dlq.queue_name == null || + length(trimspace(var.dlq.queue_name)) > 0 + ) + error_message = "dlq.queue_name must not be empty when provided." + } + + validation { + condition = var.dlq.maximum_retry_attempts >= 0 && var.dlq.maximum_retry_attempts <= 2 + error_message = "dlq.maximum_retry_attempts must be between 0 and 2." + } + + validation { + condition = var.dlq.maximum_event_age_in_seconds >= 60 && var.dlq.maximum_event_age_in_seconds <= 21600 + error_message = "dlq.maximum_event_age_in_seconds must be between 60 and 21600." + } + + validation { + condition = var.dlq.message_retention_seconds >= 60 && var.dlq.message_retention_seconds <= 1209600 + error_message = "dlq.message_retention_seconds must be between 60 and 1209600." + } + + validation { + condition = var.dlq.visibility_timeout_seconds >= 0 && var.dlq.visibility_timeout_seconds <= 43200 + error_message = "dlq.visibility_timeout_seconds must be between 0 and 43200." + } + + validation { + condition = ( + var.dlq.kms_master_key_id == "" || + startswith(var.dlq.kms_master_key_id, "arn:") || + startswith(var.dlq.kms_master_key_id, "alias/") + ) + error_message = "dlq.kms_master_key_id must be empty, an ARN, or an alias/ value." + } +} + +variable "alerting" { + description = "CloudWatch alarm and SNS notification settings for bridge failures." + type = object({ + enabled = optional(bool, true) + sns_topic_arns = optional(list(string), []) + enable_ok_notifications = optional(bool, true) + period_seconds = optional(number, 300) + evaluation_periods = optional(number, 1) + datapoints_to_alarm = optional(number, 1) + lambda_errors_threshold = optional(number, 1) + dlq_visible_messages_threshold = optional(number, 1) + }) + default = {} + + validation { + condition = var.alerting.period_seconds >= 10 + error_message = "alerting.period_seconds must be at least 10." + } + + validation { + condition = var.alerting.evaluation_periods >= 1 + error_message = "alerting.evaluation_periods must be at least 1." + } + + validation { + condition = ( + var.alerting.datapoints_to_alarm >= 1 && + var.alerting.datapoints_to_alarm <= var.alerting.evaluation_periods + ) + error_message = "alerting.datapoints_to_alarm must be between 1 and alerting.evaluation_periods." + } + + validation { + condition = var.alerting.lambda_errors_threshold >= 1 + error_message = "alerting.lambda_errors_threshold must be at least 1." + } + + validation { + condition = var.alerting.dlq_visible_messages_threshold >= 1 + error_message = "alerting.dlq_visible_messages_threshold must be at least 1." + } +} + +variable "replayer" { + description = "SQS DLQ replayer settings. Replays failed bridge events back to the main bridge Lambda." + type = object({ + enabled = optional(bool, true) + function_name = optional(string) + role_name = optional(string) + policy_name = optional(string) + runtime = optional(string) + architecture = optional(string) + memory_size = optional(number, 256) + timeout = optional(number, 60) + log_retention_in_days = optional(number, 30) + reserved_concurrent_executions = optional(number, -1) + batch_size = optional(number, 10) + maximum_batching_window_in_seconds = optional(number, 5) + maximum_concurrency = optional(number, 2) + }) + default = {} + + validation { + condition = !var.replayer.enabled || var.dlq.enabled + error_message = "replayer.enabled requires dlq.enabled to be true." + } + + validation { + condition = ( + !can(var.replayer.function_name) || + var.replayer.function_name == null || + length(trimspace(var.replayer.function_name)) > 0 + ) + error_message = "replayer.function_name must not be empty when provided." + } + + validation { + condition = ( + !can(var.replayer.role_name) || + var.replayer.role_name == null || + length(trimspace(var.replayer.role_name)) > 0 + ) + error_message = "replayer.role_name must not be empty when provided." + } + + validation { + condition = ( + !can(var.replayer.policy_name) || + var.replayer.policy_name == null || + length(trimspace(var.replayer.policy_name)) > 0 + ) + error_message = "replayer.policy_name must not be empty when provided." + } + + validation { + condition = ( + !can(var.replayer.runtime) || + var.replayer.runtime == null || + contains(["provided.al2", "provided.al2023"], var.replayer.runtime) + ) + error_message = "replayer.runtime must be one of: provided.al2, provided.al2023." + } + + validation { + condition = ( + !can(var.replayer.architecture) || + var.replayer.architecture == null || + contains(["x86_64", "arm64"], var.replayer.architecture) + ) + error_message = "replayer.architecture must be one of: x86_64, arm64." + } + + validation { + condition = var.replayer.memory_size >= 128 && var.replayer.memory_size <= 10240 + error_message = "replayer.memory_size must be between 128 and 10240 MB." + } + + validation { + condition = var.replayer.timeout >= 1 && var.replayer.timeout <= 900 + error_message = "replayer.timeout must be between 1 and 900 seconds." + } + + validation { + condition = ( + var.replayer.reserved_concurrent_executions == -1 || + var.replayer.reserved_concurrent_executions >= 1 + ) + error_message = "replayer.reserved_concurrent_executions must be -1 (unreserved) or >= 1." + } + + validation { + condition = var.replayer.batch_size >= 1 && var.replayer.batch_size <= 10000 + error_message = "replayer.batch_size must be between 1 and 10000." + } + + validation { + condition = var.replayer.maximum_batching_window_in_seconds >= 0 && var.replayer.maximum_batching_window_in_seconds <= 300 + error_message = "replayer.maximum_batching_window_in_seconds must be between 0 and 300." + } + + validation { + condition = ( + var.replayer.maximum_concurrency == 0 || + (var.replayer.maximum_concurrency >= 2 && var.replayer.maximum_concurrency <= 1000) + ) + error_message = "replayer.maximum_concurrency must be 0 (disabled) or between 2 and 1000." + } +} + +variable "tags" { + type = map(string) + description = "Tags to apply to created resources that support tags." + default = {} +} diff --git a/addons/byo-cloudwatch-log-sharing/pubsub-bridge/version.tf b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/version.tf new file mode 100644 index 0000000..1afee29 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/pubsub-bridge/version.tf @@ -0,0 +1,20 @@ +terraform { + required_version = ">= 1.3.7" + + required_providers { + archive = { + source = "hashicorp/archive" + version = ">= 2.4.0" + } + + null = { + source = "hashicorp/null" + version = ">= 3.2.1" + } + + aws = { + source = "hashicorp/aws" + version = ">= 5.29.0" + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/.header.md b/addons/byo-cloudwatch-log-sharing/target-account-firehose/.header.md new file mode 100644 index 0000000..1bfa0b5 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/.header.md @@ -0,0 +1,61 @@ +# Fleet CloudWatch Log Group Sharing via Firehose (Target Account) + +This module creates the cross-account CloudWatch Logs destination and a Firehose delivery stream target. + +CloudWatch Logs subscription payloads are already gzip-compressed. This module defaults Firehose `compression_format` to `UNCOMPRESSED` to avoid double-compression. + +Because CloudWatch Logs destinations must be created in the same region as the source log group, this module uses two provider aliases: + +- `aws.destination`: Region of the Fleet CloudWatch log group (source region). +- `aws.target`: Region for the Firehose stream and S3 bucket (same region or different region). + +Both provider aliases must use the same AWS account credentials. Cross-account is achieved between source and target subscriptions, not between `aws.destination` and `aws.target` within this module. + +## Usage + +```hcl +provider "aws" { + alias = "source_region" + region = "us-east-2" +} + +provider "aws" { + alias = "target_region" + region = "us-west-2" +} + +module "fleet_log_sharing_target" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-firehose?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + providers = { + aws.destination = aws.source_region + aws.target = aws.target_region + } + + source_account_ids = ["111111111111"] + + cloudwatch_destination = { + name = "fleet-app-logs-firehose" + role_name = "fleet-app-logs-destination-role" + policy_name = "fleet-app-logs-destination-policy" + } + + firehose = { + delivery_stream_name = "fleet-app-logs-firehose" + role_name = "fleet-app-logs-firehose-role" + policy_name = "fleet-app-logs-firehose-policy" + # Optional override; default is UNCOMPRESSED. + compression_format = "UNCOMPRESSED" + } + + s3 = { + bucket_name = "fleet-app-logs-firehose-example" + } +} + +output "fleet_log_sharing_target" { + value = module.fleet_log_sharing_target +} +``` + +Then apply the source account module (`../cloudwatch`) using `module.fleet_log_sharing_target.log_destination.arn` (default `destination_type` is `firehose`). diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/.terraform-docs.yml b/addons/byo-cloudwatch-log-sharing/target-account-firehose/.terraform-docs.yml new file mode 100644 index 0000000..1d139dd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/README.md b/addons/byo-cloudwatch-log-sharing/target-account-firehose/README.md new file mode 100644 index 0000000..b6982d4 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/README.md @@ -0,0 +1,126 @@ +# Fleet CloudWatch Log Group Sharing via Firehose (Target Account) + +This module creates the cross-account CloudWatch Logs destination and a Firehose delivery stream target. + +CloudWatch Logs subscription payloads are already gzip-compressed. This module defaults Firehose `compression_format` to `UNCOMPRESSED` to avoid double-compression. + +Because CloudWatch Logs destinations must be created in the same region as the source log group, this module uses two provider aliases: + +- `aws.destination`: Region of the Fleet CloudWatch log group (source region). +- `aws.target`: Region for the Firehose stream and S3 bucket (same region or different region). + +Both provider aliases must use the same AWS account credentials. Cross-account is achieved between source and target subscriptions, not between `aws.destination` and `aws.target` within this module. + +## Usage + +```hcl +provider "aws" { + alias = "source_region" + region = "us-east-2" +} + +provider "aws" { + alias = "target_region" + region = "us-west-2" +} + +module "fleet_log_sharing_target" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-firehose?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + providers = { + aws.destination = aws.source_region + aws.target = aws.target_region + } + + source_account_ids = ["111111111111"] + + cloudwatch_destination = { + name = "fleet-app-logs-firehose" + role_name = "fleet-app-logs-destination-role" + policy_name = "fleet-app-logs-destination-policy" + } + + firehose = { + delivery_stream_name = "fleet-app-logs-firehose" + role_name = "fleet-app-logs-firehose-role" + policy_name = "fleet-app-logs-firehose-policy" + # Optional override; default is UNCOMPRESSED. + compression_format = "UNCOMPRESSED" + } + + s3 = { + bucket_name = "fleet-app-logs-firehose-example" + } +} + +output "fleet_log_sharing_target" { + value = module.fleet_log_sharing_target +} +``` + +Then apply the source account module (`../cloudwatch`) using `module.fleet_log_sharing_target.log_destination.arn` (default `destination_type` is `firehose`). + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.7 | +| [aws](#requirement\_aws) | >= 5.29.0 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 5.29.0 | +| [aws.destination](#provider\_aws.destination) | >= 5.29.0 | +| [aws.target](#provider\_aws.target) | >= 5.29.0 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_destination.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_destination) | resource | +| [aws_cloudwatch_log_destination_policy.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_destination_policy) | resource | +| [aws_iam_policy.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_iam_policy.firehose](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_iam_role.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role.firehose](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy_attachment.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.firehose](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_kinesis_firehose_delivery_stream.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kinesis_firehose_delivery_stream) | resource | +| [aws_s3_bucket.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket) | resource | +| [aws_s3_bucket_public_access_block.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_public_access_block) | resource | +| [aws_s3_bucket_server_side_encryption_configuration.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_server_side_encryption_configuration) | resource | +| [aws_caller_identity.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_caller_identity.target](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_iam_policy_document.assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.destination_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.firehose](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.firehose_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_partition.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/partition) | data source | +| [aws_region.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | +| [aws_region.target](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [cloudwatch\_destination](#input\_cloudwatch\_destination) | CloudWatch Logs destination settings in the source log-group region. |
object({
name = optional(string, "fleet-log-sharing-firehose-destination")
role_name = optional(string, "fleet-log-sharing-firehose-destination-role")
policy_name = optional(string)
})
| `{}` | no | +| [destination\_policy\_source\_organization\_id](#input\_destination\_policy\_source\_organization\_id) | Optional AWS Organization ID allowed to subscribe to this destination. | `string` | `""` | no | +| [firehose](#input\_firehose) | Firehose delivery stream settings used as the CloudWatch Logs destination target. CloudWatch Logs subscription payloads are already gzip-compressed, so UNCOMPRESSED is the default to avoid double compression. |
object({
delivery_stream_name = string
role_name = optional(string, "fleet-log-sharing-firehose-delivery-role")
policy_name = optional(string)
buffering_size = optional(number, 5)
buffering_interval = optional(number, 300)
compression_format = optional(string, "UNCOMPRESSED")
s3_prefix = optional(string, "fleet-logs/year=!{timestamp:yyyy}/month=!{timestamp:MM}/day=!{timestamp:dd}/")
s3_error_prefix = optional(string, "fleet-logs-errors/!{firehose:error-output-type}/year=!{timestamp:yyyy}/month=!{timestamp:MM}/day=!{timestamp:dd}/")
})
| n/a | yes | +| [s3](#input\_s3) | S3 configuration for Firehose delivered logs. |
object({
bucket_name = string
force_destroy = optional(bool, false)
})
| n/a | yes | +| [source\_account\_ids](#input\_source\_account\_ids) | AWS account IDs allowed to create subscription filters to this destination. | `list(string)` | n/a | yes | +| [tags](#input\_tags) | Tags to apply to created resources that support tags. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [firehose](#output\_firehose) | Firehose destination details. | +| [log\_destination](#output\_log\_destination) | CloudWatch Logs destination details to share with the source-account team. | +| [s3\_bucket](#output\_s3\_bucket) | S3 bucket details used as the Firehose destination. | diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/destination.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/destination.tf new file mode 100644 index 0000000..b3ff387 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/destination.tf @@ -0,0 +1,79 @@ +data "aws_region" "destination" { + provider = aws.destination +} + +data "aws_region" "target" { + provider = aws.target +} + +data "aws_caller_identity" "destination" { + provider = aws.destination +} + +data "aws_caller_identity" "target" { + provider = aws.target +} + +data "aws_partition" "destination" { + provider = aws.destination +} + +locals { + allowed_source_accounts = distinct(concat(var.source_account_ids, [data.aws_caller_identity.destination.account_id])) + + allowed_source_arns = [ + for account_id in local.allowed_source_accounts : + "arn:${data.aws_partition.destination.partition}:logs:${data.aws_region.destination.region}:${account_id}:*" + ] +} + +resource "aws_cloudwatch_log_destination" "destination" { + provider = aws.destination + name = var.cloudwatch_destination.name + role_arn = aws_iam_role.destination.arn + target_arn = aws_kinesis_firehose_delivery_stream.destination.arn +} + +data "aws_iam_policy_document" "destination_policy" { + statement { + sid = "AllowSourceAccountsToSubscribe" + effect = "Allow" + actions = ["logs:PutSubscriptionFilter"] + + principals { + type = "AWS" + identifiers = var.source_account_ids + } + + resources = [aws_cloudwatch_log_destination.destination.arn] + } + + dynamic "statement" { + for_each = length(var.destination_policy_source_organization_id) > 0 ? [1] : [] + + content { + sid = "AllowOrganizationToSubscribe" + effect = "Allow" + actions = ["logs:PutSubscriptionFilter"] + + principals { + type = "AWS" + identifiers = ["*"] + } + + condition { + test = "StringEquals" + variable = "aws:PrincipalOrgID" + values = [var.destination_policy_source_organization_id] + } + + resources = [aws_cloudwatch_log_destination.destination.arn] + } + } +} + +resource "aws_cloudwatch_log_destination_policy" "destination" { + provider = aws.destination + destination_name = aws_cloudwatch_log_destination.destination.name + access_policy = data.aws_iam_policy_document.destination_policy.json +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/firehose.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/firehose.tf new file mode 100644 index 0000000..09a9a3b --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/firehose.tf @@ -0,0 +1,77 @@ +data "aws_iam_policy_document" "firehose_assume_role" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["firehose.amazonaws.com"] + } + } +} + +resource "aws_iam_role" "firehose" { + provider = aws.target + name = local.firehose_role_name + assume_role_policy = data.aws_iam_policy_document.firehose_assume_role.json + tags = var.tags +} + +data "aws_iam_policy_document" "firehose" { + statement { + effect = "Allow" + actions = [ + "s3:AbortMultipartUpload", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:ListBucket", + "s3:ListBucketMultipartUploads", + "s3:PutObject", + "s3:PutObjectAcl", + ] + resources = [ + aws_s3_bucket.destination.arn, + "${aws_s3_bucket.destination.arn}/*", + ] + } +} + +resource "aws_iam_policy" "firehose" { + provider = aws.target + name = local.firehose_policy_name + policy = data.aws_iam_policy_document.firehose.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "firehose" { + provider = aws.target + role = aws_iam_role.firehose.name + policy_arn = aws_iam_policy.firehose.arn +} + +resource "aws_kinesis_firehose_delivery_stream" "destination" { + provider = aws.target + name = var.firehose.delivery_stream_name + destination = "extended_s3" + + extended_s3_configuration { + bucket_arn = aws_s3_bucket.destination.arn + role_arn = aws_iam_role.firehose.arn + prefix = var.firehose.s3_prefix + error_output_prefix = var.firehose.s3_error_prefix + buffering_size = var.firehose.buffering_size + buffering_interval = var.firehose.buffering_interval + # CloudWatch Logs subscription payloads are gzip-compressed already. + # Keep this UNCOMPRESSED by default to avoid double-compression. + compression_format = var.firehose.compression_format + } + + tags = var.tags + + lifecycle { + precondition { + condition = data.aws_caller_identity.destination.account_id == data.aws_caller_identity.target.account_id + error_message = "aws.destination and aws.target providers must use the same AWS account." + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/iam.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/iam.tf new file mode 100644 index 0000000..17f51c2 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/iam.tf @@ -0,0 +1,69 @@ +locals { + cloudwatch_destination_role_name = coalesce( + var.cloudwatch_destination.role_name, + "fleet-log-sharing-firehose-destination-role" + ) + firehose_role_name = coalesce( + var.firehose.role_name, + "fleet-log-sharing-firehose-delivery-role" + ) + + cloudwatch_destination_policy_name = coalesce( + var.cloudwatch_destination.policy_name, + "${local.cloudwatch_destination_role_name}-policy" + ) + firehose_policy_name = coalesce( + var.firehose.policy_name, + "${local.firehose_role_name}-policy" + ) +} + +data "aws_iam_policy_document" "assume_role" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["logs.${data.aws_region.destination.region}.amazonaws.com"] + } + + condition { + test = "StringLike" + variable = "aws:SourceArn" + values = local.allowed_source_arns + } + } +} + +resource "aws_iam_role" "destination" { + provider = aws.destination + name = local.cloudwatch_destination_role_name + assume_role_policy = data.aws_iam_policy_document.assume_role.json + tags = var.tags +} + +data "aws_iam_policy_document" "destination" { + statement { + effect = "Allow" + actions = [ + "firehose:DescribeDeliveryStream", + "firehose:PutRecord", + "firehose:PutRecordBatch", + ] + resources = [aws_kinesis_firehose_delivery_stream.destination.arn] + } +} + +resource "aws_iam_policy" "destination" { + provider = aws.destination + name = local.cloudwatch_destination_policy_name + policy = data.aws_iam_policy_document.destination.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "destination" { + provider = aws.destination + role = aws_iam_role.destination.name + policy_arn = aws_iam_policy.destination.arn +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/outputs.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/outputs.tf new file mode 100644 index 0000000..464ac88 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/outputs.tf @@ -0,0 +1,27 @@ +output "log_destination" { + description = "CloudWatch Logs destination details to share with the source-account team." + value = { + arn = aws_cloudwatch_log_destination.destination.arn + name = aws_cloudwatch_log_destination.destination.name + region = data.aws_region.destination.region + account_id = data.aws_caller_identity.destination.account_id + role_arn = aws_iam_role.destination.arn + } +} + +output "firehose" { + description = "Firehose destination details." + value = { + delivery_stream_name = aws_kinesis_firehose_delivery_stream.destination.name + delivery_stream_arn = aws_kinesis_firehose_delivery_stream.destination.arn + region = data.aws_region.target.region + } +} + +output "s3_bucket" { + description = "S3 bucket details used as the Firehose destination." + value = { + name = aws_s3_bucket.destination.bucket + arn = aws_s3_bucket.destination.arn + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/s3.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/s3.tf new file mode 100644 index 0000000..c43275d --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/s3.tf @@ -0,0 +1,28 @@ +resource "aws_s3_bucket" "destination" { + provider = aws.target + bucket = var.s3.bucket_name + force_destroy = var.s3.force_destroy + tags = var.tags +} + +resource "aws_s3_bucket_public_access_block" "destination" { + provider = aws.target + bucket = aws_s3_bucket.destination.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "destination" { + provider = aws.target + bucket = aws_s3_bucket.destination.id + + rule { + bucket_key_enabled = true + + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/variables.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/variables.tf new file mode 100644 index 0000000..6e27055 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/variables.tf @@ -0,0 +1,90 @@ +variable "source_account_ids" { + type = list(string) + description = "AWS account IDs allowed to create subscription filters to this destination." + + validation { + condition = length(var.source_account_ids) > 0 + error_message = "source_account_ids must include at least one AWS account ID." + } +} + +variable "destination_policy_source_organization_id" { + type = string + description = "Optional AWS Organization ID allowed to subscribe to this destination." + default = "" +} + +variable "cloudwatch_destination" { + description = "CloudWatch Logs destination settings in the source log-group region." + type = object({ + name = optional(string, "fleet-log-sharing-firehose-destination") + role_name = optional(string, "fleet-log-sharing-firehose-destination-role") + policy_name = optional(string) + }) + default = {} + + validation { + condition = ( + var.cloudwatch_destination.role_name == null || + length(trimspace(var.cloudwatch_destination.role_name)) > 0 + ) + error_message = "cloudwatch_destination.role_name must be null or a non-empty string." + } +} + +variable "firehose" { + description = "Firehose delivery stream settings used as the CloudWatch Logs destination target. CloudWatch Logs subscription payloads are already gzip-compressed, so UNCOMPRESSED is the default to avoid double compression." + type = object({ + delivery_stream_name = string + role_name = optional(string, "fleet-log-sharing-firehose-delivery-role") + policy_name = optional(string) + buffering_size = optional(number, 5) + buffering_interval = optional(number, 300) + compression_format = optional(string, "UNCOMPRESSED") + s3_prefix = optional(string, "fleet-logs/year=!{timestamp:yyyy}/month=!{timestamp:MM}/day=!{timestamp:dd}/") + s3_error_prefix = optional(string, "fleet-logs-errors/!{firehose:error-output-type}/year=!{timestamp:yyyy}/month=!{timestamp:MM}/day=!{timestamp:dd}/") + }) + + validation { + condition = var.firehose.buffering_size >= 1 && var.firehose.buffering_size <= 128 + error_message = "firehose.buffering_size must be between 1 and 128 MB." + } + + validation { + condition = var.firehose.buffering_interval >= 0 && var.firehose.buffering_interval <= 900 + error_message = "firehose.buffering_interval must be between 0 and 900 seconds." + } + + validation { + condition = contains([ + "UNCOMPRESSED", + "GZIP", + "ZIP", + "Snappy", + "HADOOP_SNAPPY", + ], var.firehose.compression_format) + error_message = "firehose.compression_format must be one of: UNCOMPRESSED, GZIP, ZIP, Snappy, HADOOP_SNAPPY." + } + + validation { + condition = ( + var.firehose.role_name == null || + length(trimspace(var.firehose.role_name)) > 0 + ) + error_message = "firehose.role_name must be null or a non-empty string." + } +} + +variable "s3" { + description = "S3 configuration for Firehose delivered logs." + type = object({ + bucket_name = string + force_destroy = optional(bool, false) + }) +} + +variable "tags" { + type = map(string) + description = "Tags to apply to created resources that support tags." + default = {} +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-firehose/version.tf b/addons/byo-cloudwatch-log-sharing/target-account-firehose/version.tf new file mode 100644 index 0000000..6f8a9cd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-firehose/version.tf @@ -0,0 +1,14 @@ +terraform { + required_version = ">= 1.3.7" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.29.0" + configuration_aliases = [ + aws.destination, + aws.target, + ] + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/.header.md b/addons/byo-cloudwatch-log-sharing/target-account-gcp/.header.md new file mode 100644 index 0000000..e9df228 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/.header.md @@ -0,0 +1,110 @@ +# Fleet CloudWatch Log Sharing GCP Target + +This module creates the Google Cloud destination side for Fleet CloudWatch log sharing: + +- Pub/Sub topic for log ingestion from the AWS bridge Lambda. +- Service account (and optional key) used by the AWS bridge Lambda to publish. +- Cloud Storage bucket destination. +- Pub/Sub subscription that streams topic data into Cloud Storage. + +This is the Google Cloud equivalent of an AWS target account module that ends in `S3`. + +## Usage + +```hcl +provider "google" { + project = "customer-observability-prod" + region = "us-central1" +} + +module "fleet_log_sharing_target_gcp" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-gcp?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + # Optional. If omitted, module uses provider "google" project. + # project_id = "customer-observability-prod" + + service_account = { + # Optional. If omitted, defaults to "fleet-cwl-pubsub-publisher". + account_id = "fleet-cwl-pubsub-publisher" + } + + pubsub = { + topic_name = "fleet-cloudwatch-logs" + subscription_name = "fleet-cloudwatch-logs-to-gcs" + } + + gcs = { + bucket_name = "customer-fleet-cloudwatch-logs" + location = "US" + } + + delivery = { + filename_prefix = "fleet/logs/" + filename_suffix = ".jsonl" + max_duration = "300s" + max_bytes = 10485760 + } +} + +output "fleet_log_sharing_target_gcp" { + value = module.fleet_log_sharing_target_gcp + sensitive = true +} +``` + +### Cross-Organization Hand-off to AWS Bridge Team + +Share these values out-of-band with the team that manages the AWS `pubsub-bridge` module: + +- `module.fleet_log_sharing_target_gcp.bridge.project_id` +- `module.fleet_log_sharing_target_gcp.bridge.topic_id` +- `module.fleet_log_sharing_target_gcp.publisher_credentials_json` + +The bridge team stores `publisher_credentials_json` in AWS Secrets Manager and passes the secret ARN into: + +- `addons/byo-cloudwatch-log-sharing/pubsub-bridge` + +## Test Publisher Script + +A helper script is included to publish validation messages directly to the Pub/Sub topic: + +- `scripts/publish_pubsub_test.sh` + +Example using built-in default messages: + +```bash +./scripts/publish_pubsub_test.sh \ + --project-id customer-observability-prod \ + --topic-id fleet-cloudwatch-logs \ + --service-account-key-file ./service-account.json \ + --debug +``` + +Example using custom data: + +```bash +./scripts/publish_pubsub_test.sh \ + --project-id customer-observability-prod \ + --topic-id fleet-cloudwatch-logs \ + --service-account-key-file ./service-account.json \ + --data-file ./messages.ndjson +``` + +`messages.ndjson` should contain one message per line. + +Example using values directly from Terraform outputs (`jq` required): + +```bash +terraform output -json > ./tf-output.json + +jq -r '.fleet_log_sharing_target_gcp.value.publisher_credentials_json' ./tf-output.json > ./service-account.json + +PROJECT_ID="$(jq -r '.fleet_log_sharing_target_gcp.value.bridge.project_id' ./tf-output.json)" +TOPIC_ID="$(jq -r '.fleet_log_sharing_target_gcp.value.bridge.topic_id' ./tf-output.json)" + +./scripts/publish_pubsub_test.sh \ + --project-id "${PROJECT_ID}" \ + --topic-id "${TOPIC_ID}" \ + --service-account-key-file ./service-account.json \ + --debug +``` diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/.terraform-docs.yml b/addons/byo-cloudwatch-log-sharing/target-account-gcp/.terraform-docs.yml new file mode 100644 index 0000000..1d139dd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/README.md b/addons/byo-cloudwatch-log-sharing/target-account-gcp/README.md new file mode 100644 index 0000000..09ba70b --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/README.md @@ -0,0 +1,165 @@ + +# Fleet CloudWatch Log Sharing GCP Target + +This module creates the Google Cloud destination side for Fleet CloudWatch log sharing: + +- Pub/Sub topic for log ingestion from the AWS bridge Lambda. +- Service account (and optional key) used by the AWS bridge Lambda to publish. +- Cloud Storage bucket destination. +- Pub/Sub subscription that streams topic data into Cloud Storage. + +This is the Google Cloud equivalent of an AWS target account module that ends in `S3`. + +## Usage + +```hcl +provider "google" { + project = "customer-observability-prod" + region = "us-central1" +} + +module "fleet_log_sharing_target_gcp" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-gcp?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + # Optional. If omitted, module uses provider "google" project. + # project_id = "customer-observability-prod" + + service_account = { + # Optional. If omitted, defaults to "fleet-cwl-pubsub-publisher". + account_id = "fleet-cwl-pubsub-publisher" + } + + pubsub = { + topic_name = "fleet-cloudwatch-logs" + subscription_name = "fleet-cloudwatch-logs-to-gcs" + } + + gcs = { + bucket_name = "customer-fleet-cloudwatch-logs" + location = "US" + } + + delivery = { + filename_prefix = "fleet/logs/" + filename_suffix = ".jsonl" + max_duration = "300s" + max_bytes = 10485760 + } +} + +output "fleet_log_sharing_target_gcp" { + value = module.fleet_log_sharing_target_gcp + sensitive = true +} +``` + +### Cross-Organization Hand-off to AWS Bridge Team + +Share these values out-of-band with the team that manages the AWS `pubsub-bridge` module: + +- `module.fleet_log_sharing_target_gcp.bridge.project_id` +- `module.fleet_log_sharing_target_gcp.bridge.topic_id` +- `module.fleet_log_sharing_target_gcp.publisher_credentials_json` + +The bridge team stores `publisher_credentials_json` in AWS Secrets Manager and passes the secret ARN into: + +- `addons/byo-cloudwatch-log-sharing/pubsub-bridge` + +## Test Publisher Script + +A helper script is included to publish validation messages directly to the Pub/Sub topic: + +- `scripts/publish_pubsub_test.sh` + +Example using built-in default messages: + +```bash +./scripts/publish_pubsub_test.sh \ + --project-id customer-observability-prod \ + --topic-id fleet-cloudwatch-logs \ + --service-account-key-file ./service-account.json \ + --debug +``` + +Example using custom data: + +```bash +./scripts/publish_pubsub_test.sh \ + --project-id customer-observability-prod \ + --topic-id fleet-cloudwatch-logs \ + --service-account-key-file ./service-account.json \ + --data-file ./messages.ndjson +``` + +`messages.ndjson` should contain one message per line. + +Example using values directly from Terraform outputs (`jq` required): + +```bash +terraform output -json > ./tf-output.json + +jq -r '.fleet_log_sharing_target_gcp.value.publisher_credentials_json' ./tf-output.json > ./service-account.json + +PROJECT_ID="$(jq -r '.fleet_log_sharing_target_gcp.value.bridge.project_id' ./tf-output.json)" +TOPIC_ID="$(jq -r '.fleet_log_sharing_target_gcp.value.bridge.topic_id' ./tf-output.json)" + +./scripts/publish_pubsub_test.sh \ + --project-id "${PROJECT_ID}" \ + --topic-id "${TOPIC_ID}" \ + --service-account-key-file ./service-account.json \ + --debug +``` + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.7 | +| [google](#requirement\_google) | >= 6.35.0 | + +## Providers + +| Name | Version | +|------|---------| +| [google](#provider\_google) | >= 6.35.0 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [google_pubsub_subscription.gcs_sink](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_subscription) | resource | +| [google_pubsub_topic.fleet_logs](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_topic) | resource | +| [google_pubsub_topic_iam_member.publisher](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_topic_iam_member) | resource | +| [google_service_account.publisher](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/service_account) | resource | +| [google_service_account_key.publisher](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/service_account_key) | resource | +| [google_storage_bucket.fleet_logs](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket) | resource | +| [google_storage_bucket_iam_member.pubsub_bucket_reader](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket_iam_member) | resource | +| [google_storage_bucket_iam_member.pubsub_writer](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket_iam_member) | resource | +| [google_client_config.current](https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/client_config) | data source | +| [google_project.target](https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/project) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [delivery](#input\_delivery) | Pub/Sub Cloud Storage subscription delivery settings. |
object({
filename_prefix = optional(string, "fleet-cloudwatch-logs/")
filename_suffix = optional(string, ".jsonl")
max_duration = optional(string, "300s")
max_bytes = optional(number, 10485760)
})
| `{}` | no | +| [gcs](#input\_gcs) | Google Cloud Storage destination for delivered Pub/Sub log files. |
object({
bucket_name = string
location = optional(string, "US")
storage_class = optional(string, "STANDARD")
force_destroy = optional(bool, false)
})
| n/a | yes | +| [labels](#input\_labels) | Labels to apply to resources that support labels. | `map(string)` | `{}` | no | +| [project\_id](#input\_project\_id) | Optional GCP project ID where resources will be created. If omitted, the module uses the active Google provider project. | `string` | `""` | no | +| [pubsub](#input\_pubsub) | Pub/Sub topic and subscription settings for incoming Fleet log events. |
object({
topic_name = optional(string, "fleet-cloudwatch-logs")
subscription_name = optional(string, "fleet-cloudwatch-logs-to-gcs")
ack_deadline_seconds = optional(number, 20)
message_retention_duration = optional(string, "604800s")
})
| `{}` | no | +| [service\_account](#input\_service\_account) | Service account used by the AWS bridge Lambda to publish to Pub/Sub. If account\_id is omitted, defaults to fleet-cwl-pubsub-publisher. |
object({
account_id = optional(string, "")
display_name = optional(string, "Fleet CloudWatch Pub/Sub Publisher")
description = optional(string, "Publishes Fleet CloudWatch log events to a customer-managed Pub/Sub topic")
create_key = optional(bool, true)
})
| `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [bridge](#output\_bridge) | Values to share with the AWS bridge module configuration. | +| [publisher\_credentials\_json](#output\_publisher\_credentials\_json) | Sensitive Google service-account credentials JSON to store in AWS Secrets Manager for the bridge Lambda. | +| [publisher\_service\_account](#output\_publisher\_service\_account) | Publisher service-account details used by the AWS Lambda bridge. | +| [pubsub](#output\_pubsub) | Pub/Sub resource details for the log intake topic and GCS sink subscription. | +| [storage](#output\_storage) | Google Cloud Storage destination details. | + \ No newline at end of file diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/main.tf b/addons/byo-cloudwatch-log-sharing/target-account-gcp/main.tf new file mode 100644 index 0000000..a1f364e --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/main.tf @@ -0,0 +1,82 @@ +data "google_client_config" "current" {} + +data "google_project" "target" { + project_id = local.effective_project_id +} + +locals { + effective_project_id = trimspace(var.project_id) != "" ? var.project_id : data.google_client_config.current.project + effective_sa_account_id = trimspace(var.service_account.account_id) != "" ? var.service_account.account_id : "fleet-cwl-pubsub-publisher" + pubsub_service_agent_email = "service-${data.google_project.target.number}@gcp-sa-pubsub.iam.gserviceaccount.com" +} + +resource "google_pubsub_topic" "fleet_logs" { + project = local.effective_project_id + name = var.pubsub.topic_name + labels = var.labels +} + +resource "google_service_account" "publisher" { + project = local.effective_project_id + account_id = local.effective_sa_account_id + display_name = var.service_account.display_name + description = var.service_account.description +} + +resource "google_service_account_key" "publisher" { + count = var.service_account.create_key ? 1 : 0 + service_account_id = google_service_account.publisher.name + private_key_type = "TYPE_GOOGLE_CREDENTIALS_FILE" +} + +resource "google_pubsub_topic_iam_member" "publisher" { + project = local.effective_project_id + topic = google_pubsub_topic.fleet_logs.name + role = "roles/pubsub.publisher" + member = "serviceAccount:${google_service_account.publisher.email}" +} + +resource "google_storage_bucket" "fleet_logs" { + project = local.effective_project_id + name = var.gcs.bucket_name + location = var.gcs.location + storage_class = var.gcs.storage_class + force_destroy = var.gcs.force_destroy + labels = var.labels + + uniform_bucket_level_access = true +} + +resource "google_storage_bucket_iam_member" "pubsub_writer" { + bucket = google_storage_bucket.fleet_logs.name + role = "roles/storage.objectCreator" + member = "serviceAccount:${local.pubsub_service_agent_email}" +} + +resource "google_storage_bucket_iam_member" "pubsub_bucket_reader" { + bucket = google_storage_bucket.fleet_logs.name + role = "roles/storage.legacyBucketReader" + member = "serviceAccount:${local.pubsub_service_agent_email}" +} + +resource "google_pubsub_subscription" "gcs_sink" { + project = local.effective_project_id + name = var.pubsub.subscription_name + topic = google_pubsub_topic.fleet_logs.id + + ack_deadline_seconds = var.pubsub.ack_deadline_seconds + message_retention_duration = var.pubsub.message_retention_duration + + cloud_storage_config { + bucket = google_storage_bucket.fleet_logs.name + filename_prefix = var.delivery.filename_prefix + filename_suffix = var.delivery.filename_suffix + max_duration = var.delivery.max_duration + max_bytes = var.delivery.max_bytes + } + + depends_on = [ + google_storage_bucket_iam_member.pubsub_writer, + google_storage_bucket_iam_member.pubsub_bucket_reader, + ] +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/outputs.tf b/addons/byo-cloudwatch-log-sharing/target-account-gcp/outputs.tf new file mode 100644 index 0000000..382f3cb --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/outputs.tf @@ -0,0 +1,43 @@ +output "bridge" { + description = "Values to share with the AWS bridge module configuration." + value = { + project_id = local.effective_project_id + topic_id = google_pubsub_topic.fleet_logs.name + } +} + +output "pubsub" { + description = "Pub/Sub resource details for the log intake topic and GCS sink subscription." + value = { + topic_name = google_pubsub_topic.fleet_logs.name + topic_id = google_pubsub_topic.fleet_logs.id + topic_qualified_id = google_pubsub_topic.fleet_logs.id + + subscription_name = google_pubsub_subscription.gcs_sink.name + subscription_id = google_pubsub_subscription.gcs_sink.id + subscription_qualified_id = google_pubsub_subscription.gcs_sink.id + } +} + +output "storage" { + description = "Google Cloud Storage destination details." + value = { + bucket_name = google_storage_bucket.fleet_logs.name + bucket_url = google_storage_bucket.fleet_logs.url + } +} + +output "publisher_service_account" { + description = "Publisher service-account details used by the AWS Lambda bridge." + value = { + email = google_service_account.publisher.email + account_id = google_service_account.publisher.account_id + member = "serviceAccount:${google_service_account.publisher.email}" + } +} + +output "publisher_credentials_json" { + description = "Sensitive Google service-account credentials JSON to store in AWS Secrets Manager for the bridge Lambda." + value = var.service_account.create_key ? base64decode(google_service_account_key.publisher[0].private_key) : null + sensitive = true +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/scripts/publish_pubsub_test.sh b/addons/byo-cloudwatch-log-sharing/target-account-gcp/scripts/publish_pubsub_test.sh new file mode 100755 index 0000000..2ff25c3 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/scripts/publish_pubsub_test.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROJECT_ID="" +TOPIC_ID="" +SERVICE_ACCOUNT_KEY_FILE="" +DATA_FILE="" +DEBUG=false + +declare -a USER_MESSAGES=() + +debug() { + if [[ "${DEBUG}" == "true" ]]; then + printf '[DEBUG] %s\n' "$1" + fi +} + +log() { + printf '%s\n' "$1" +} + +usage() { + cat < --topic-id --service-account-key-file [options] + +Required: + --project-id GCP project ID. + --topic-id Pub/Sub topic ID. + --service-account-key-file Path to service account JSON key file. + +Optional: + --message Add a message payload (repeatable). + --data-file NDJSON/plain-text file with one message per line. + --debug Enable verbose diagnostics. + --help Show this help. + +Behavior: + - If no --message or --data-file is provided, a built-in default dataset is published. + - This script uses an isolated gcloud config directory and does not modify your active gcloud profile. +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --project-id) + PROJECT_ID="${2:-}" + shift 2 + ;; + --topic-id) + TOPIC_ID="${2:-}" + shift 2 + ;; + --service-account-key-file) + SERVICE_ACCOUNT_KEY_FILE="${2:-}" + shift 2 + ;; + --message) + USER_MESSAGES+=("${2:-}") + shift 2 + ;; + --data-file) + DATA_FILE="${2:-}" + shift 2 + ;; + --debug) + DEBUG=true + shift + ;; + --help|-h) + usage + exit 0 + ;; + *) + printf 'Unknown argument: %s\n\n' "$1" >&2 + usage >&2 + exit 1 + ;; + esac +done + +if [[ -z "${PROJECT_ID}" || -z "${TOPIC_ID}" || -z "${SERVICE_ACCOUNT_KEY_FILE}" ]]; then + printf 'Missing required arguments.\n\n' >&2 + usage >&2 + exit 1 +fi + +if [[ ! -f "${SERVICE_ACCOUNT_KEY_FILE}" ]]; then + printf 'Service account key file not found: %s\n' "${SERVICE_ACCOUNT_KEY_FILE}" >&2 + exit 1 +fi + +if [[ -n "${DATA_FILE}" && ! -f "${DATA_FILE}" ]]; then + printf 'Data file not found: %s\n' "${DATA_FILE}" >&2 + exit 1 +fi + +if ! command -v gcloud >/dev/null 2>&1; then + printf 'gcloud is required but not installed or not in PATH.\n' >&2 + exit 1 +fi + +declare -a MESSAGES=() + +if [[ -n "${DATA_FILE}" ]]; then + debug "Loading messages from ${DATA_FILE}" + while IFS= read -r line || [[ -n "${line}" ]]; do + trimmed="${line#"${line%%[![:space:]]*}"}" + if [[ -z "${trimmed}" ]]; then + continue + fi + MESSAGES+=("${line}") + done < "${DATA_FILE}" +fi + +if [[ ${#USER_MESSAGES[@]} -gt 0 ]]; then + debug "Appending ${#USER_MESSAGES[@]} CLI-provided message(s)" + MESSAGES+=("${USER_MESSAGES[@]}") +fi + +if [[ ${#MESSAGES[@]} -eq 0 ]]; then + debug "Using built-in default test dataset" + MESSAGES=( + '{"test_case":"default-1","source":"fleet-terraform","message":"hello from fleet cloudwatch log sharing","severity":"INFO"}' + '{"test_case":"default-2","source":"fleet-terraform","message":"simulated warning log","severity":"WARN","component":"pubsub-bridge"}' + '{"test_case":"default-3","source":"fleet-terraform","message":"simulated error log","severity":"ERROR","component":"pubsub-bridge"}' + ) +fi + +TMP_GCLOUD_CONFIG_DIR="$(mktemp -d)" +cleanup() { + rm -rf "${TMP_GCLOUD_CONFIG_DIR}" +} +trap cleanup EXIT + +export CLOUDSDK_CONFIG="${TMP_GCLOUD_CONFIG_DIR}" + +declare -a GCLOUD_VERBOSE_FLAG=() +if [[ "${DEBUG}" == "true" ]]; then + GCLOUD_VERBOSE_FLAG=(--verbosity=debug) + set -x +fi + +log "Authenticating service account for project ${PROJECT_ID}" +gcloud "${GCLOUD_VERBOSE_FLAG[@]}" --quiet auth activate-service-account --key-file "${SERVICE_ACCOUNT_KEY_FILE}" --project "${PROJECT_ID}" >/dev/null + +ACTIVE_ACCOUNT="$(gcloud "${GCLOUD_VERBOSE_FLAG[@]}" auth list --filter=status:ACTIVE --format='value(account)')" +log "Active gcloud account: ${ACTIVE_ACCOUNT}" +log "Publishing ${#MESSAGES[@]} message(s) to topic ${TOPIC_ID}" + +PUBLISHED_COUNT=0 +for idx in "${!MESSAGES[@]}"; do + message="${MESSAGES[$idx]}" + sequence="$((idx + 1))" + debug "Publishing message ${sequence}: ${message}" + + gcloud "${GCLOUD_VERBOSE_FLAG[@]}" --project "${PROJECT_ID}" pubsub topics publish "${TOPIC_ID}" \ + --message "${message}" \ + --attribute "source=fleet-terraform-pubsub-test,sequence=${sequence}" >/dev/null + + PUBLISHED_COUNT="$((PUBLISHED_COUNT + 1))" +done + +log "Published ${PUBLISHED_COUNT} message(s) successfully." diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/variables.tf b/addons/byo-cloudwatch-log-sharing/target-account-gcp/variables.tf new file mode 100644 index 0000000..054190d --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/variables.tf @@ -0,0 +1,102 @@ +variable "project_id" { + type = string + description = "Optional GCP project ID where resources will be created. If omitted, the module uses the active Google provider project." + default = "" +} + +variable "pubsub" { + description = "Pub/Sub topic and subscription settings for incoming Fleet log events." + type = object({ + topic_name = optional(string, "fleet-cloudwatch-logs") + subscription_name = optional(string, "fleet-cloudwatch-logs-to-gcs") + ack_deadline_seconds = optional(number, 20) + message_retention_duration = optional(string, "604800s") + }) + default = {} + + validation { + condition = length(trimspace(var.pubsub.topic_name)) > 0 + error_message = "pubsub.topic_name must not be empty." + } + + validation { + condition = length(trimspace(var.pubsub.subscription_name)) > 0 + error_message = "pubsub.subscription_name must not be empty." + } + + validation { + condition = var.pubsub.ack_deadline_seconds >= 10 && var.pubsub.ack_deadline_seconds <= 600 + error_message = "pubsub.ack_deadline_seconds must be between 10 and 600 seconds." + } + + validation { + condition = can(regex("^[1-9][0-9]*s$", var.pubsub.message_retention_duration)) + error_message = "pubsub.message_retention_duration must be a duration string ending in 's', for example '604800s'." + } +} + +variable "service_account" { + description = "Service account used by the AWS bridge Lambda to publish to Pub/Sub. If account_id is omitted, defaults to fleet-cwl-pubsub-publisher." + type = object({ + account_id = optional(string, "") + display_name = optional(string, "Fleet CloudWatch Pub/Sub Publisher") + description = optional(string, "Publishes Fleet CloudWatch log events to a customer-managed Pub/Sub topic") + create_key = optional(bool, true) + }) + default = {} + + validation { + condition = ( + trimspace(var.service_account.account_id) == "" || + can(regex("^[a-z]([-a-z0-9]{4,28}[a-z0-9])$", var.service_account.account_id)) + ) + error_message = "service_account.account_id must be empty or 6-30 chars starting with a letter, using lowercase letters, numbers, or hyphens." + } + + validation { + condition = length(trimspace(var.service_account.display_name)) > 0 + error_message = "service_account.display_name must not be empty." + } +} + +variable "gcs" { + description = "Google Cloud Storage destination for delivered Pub/Sub log files." + type = object({ + bucket_name = string + location = optional(string, "US") + storage_class = optional(string, "STANDARD") + force_destroy = optional(bool, false) + }) + + validation { + condition = length(trimspace(var.gcs.bucket_name)) > 0 + error_message = "gcs.bucket_name must not be empty." + } +} + +variable "delivery" { + description = "Pub/Sub Cloud Storage subscription delivery settings." + type = object({ + filename_prefix = optional(string, "fleet-cloudwatch-logs/") + filename_suffix = optional(string, ".jsonl") + max_duration = optional(string, "300s") + max_bytes = optional(number, 10485760) + }) + default = {} + + validation { + condition = can(regex("^[1-9][0-9]*s$", var.delivery.max_duration)) + error_message = "delivery.max_duration must be a duration string ending in 's', for example '300s'." + } + + validation { + condition = var.delivery.max_bytes >= 1024 && var.delivery.max_bytes <= 1073741824 + error_message = "delivery.max_bytes must be between 1024 and 1073741824 bytes." + } +} + +variable "labels" { + type = map(string) + description = "Labels to apply to resources that support labels." + default = {} +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-gcp/version.tf b/addons/byo-cloudwatch-log-sharing/target-account-gcp/version.tf new file mode 100644 index 0000000..92bc380 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-gcp/version.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.7" + + required_providers { + google = { + source = "hashicorp/google" + version = ">= 6.35.0" + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.header.md b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.header.md new file mode 100644 index 0000000..906fd43 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.header.md @@ -0,0 +1,51 @@ +# Fleet CloudWatch Log Group Sharing via Kinesis (Target Account) + +This module creates the cross-account CloudWatch Logs destination and a Kinesis Data Stream target. + +Because CloudWatch Logs destinations must be created in the same region as the source log group, this module uses two provider aliases: + +- `aws.destination`: Region of the Fleet CloudWatch log group (source region). +- `aws.target`: Region for the Kinesis stream (same region or different region). + +Both provider aliases must use the same AWS account credentials. Cross-account is achieved between source and target subscriptions, not between `aws.destination` and `aws.target` within this module. + +## Usage + +```hcl +provider "aws" { + alias = "source_region" + region = "us-east-2" +} + +provider "aws" { + alias = "target_region" + region = "us-west-2" +} + +module "fleet_log_sharing_target" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-kinesis?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + providers = { + aws.destination = aws.source_region + aws.target = aws.target_region + } + + source_account_ids = ["111111111111"] + + cloudwatch_destination = { + name = "fleet-app-logs" + role_name = "fleet-app-logs-role" + policy_name = "fleet-app-logs-policy" + } + + kinesis = { + stream_name = "fleet-app-logs" + } +} + +output "fleet_log_sharing_target" { + value = module.fleet_log_sharing_target +} +``` + +Then apply the source account module (`../cloudwatch`) using `module.fleet_log_sharing_target.log_destination.arn` and set `destination_type = "kinesis"`. diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.terraform-docs.yml b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.terraform-docs.yml new file mode 100644 index 0000000..1d139dd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/README.md b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/README.md new file mode 100644 index 0000000..4b12726 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/README.md @@ -0,0 +1,106 @@ +# Fleet CloudWatch Log Group Sharing via Kinesis (Target Account) + +This module creates the cross-account CloudWatch Logs destination and a Kinesis Data Stream target. + +Because CloudWatch Logs destinations must be created in the same region as the source log group, this module uses two provider aliases: + +- `aws.destination`: Region of the Fleet CloudWatch log group (source region). +- `aws.target`: Region for the Kinesis stream (same region or different region). + +Both provider aliases must use the same AWS account credentials. Cross-account is achieved between source and target subscriptions, not between `aws.destination` and `aws.target` within this module. + +## Usage + +```hcl +provider "aws" { + alias = "source_region" + region = "us-east-2" +} + +provider "aws" { + alias = "target_region" + region = "us-west-2" +} + +module "fleet_log_sharing_target" { + source = "github.com/fleetdm/fleet-terraform//addons/byo-cloudwatch-log-sharing/target-account-kinesis?depth=1&ref=tf-mod-addon-byo-cloudwatch-log-sharing-v1.0.0" + + providers = { + aws.destination = aws.source_region + aws.target = aws.target_region + } + + source_account_ids = ["111111111111"] + + cloudwatch_destination = { + name = "fleet-app-logs" + role_name = "fleet-app-logs-role" + policy_name = "fleet-app-logs-policy" + } + + kinesis = { + stream_name = "fleet-app-logs" + } +} + +output "fleet_log_sharing_target" { + value = module.fleet_log_sharing_target +} +``` + +Then apply the source account module (`../cloudwatch`) using `module.fleet_log_sharing_target.log_destination.arn` and set `destination_type = "kinesis"`. + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.7 | +| [aws](#requirement\_aws) | >= 5.29.0 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 5.29.0 | +| [aws.destination](#provider\_aws.destination) | >= 5.29.0 | +| [aws.target](#provider\_aws.target) | >= 5.29.0 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_destination.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_destination) | resource | +| [aws_cloudwatch_log_destination_policy.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_destination_policy) | resource | +| [aws_iam_policy.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_iam_role.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy_attachment.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_kinesis_stream.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kinesis_stream) | resource | +| [aws_caller_identity.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_caller_identity.target](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_iam_policy_document.assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.destination_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_partition.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/partition) | data source | +| [aws_region.destination](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | +| [aws_region.target](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [cloudwatch\_destination](#input\_cloudwatch\_destination) | CloudWatch Logs destination settings in the source log-group region. |
object({
name = optional(string, "fleet-log-sharing-destination")
role_name = optional(string, "fleet-log-sharing-destination-role")
policy_name = optional(string)
})
| `{}` | no | +| [destination\_policy\_source\_organization\_id](#input\_destination\_policy\_source\_organization\_id) | Optional AWS Organization ID allowed to subscribe to this destination. | `string` | `""` | no | +| [kinesis](#input\_kinesis) | Kinesis stream settings used as the CloudWatch Logs destination target. |
object({
stream_name = string
stream_mode = optional(string, "ON_DEMAND")
shard_count = optional(number, 1)
retention_period = optional(number, 24)
})
| n/a | yes | +| [source\_account\_ids](#input\_source\_account\_ids) | AWS account IDs allowed to create subscription filters to this destination. | `list(string)` | n/a | yes | +| [tags](#input\_tags) | Tags to apply to created resources that support tags. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [kinesis](#output\_kinesis) | Kinesis destination details. | +| [log\_destination](#output\_log\_destination) | CloudWatch Logs destination details to share with the source-account team. | diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/destination.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/destination.tf new file mode 100644 index 0000000..86d49d3 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/destination.tf @@ -0,0 +1,79 @@ +data "aws_region" "destination" { + provider = aws.destination +} + +data "aws_region" "target" { + provider = aws.target +} + +data "aws_caller_identity" "destination" { + provider = aws.destination +} + +data "aws_caller_identity" "target" { + provider = aws.target +} + +data "aws_partition" "destination" { + provider = aws.destination +} + +locals { + allowed_source_accounts = distinct(concat(var.source_account_ids, [data.aws_caller_identity.destination.account_id])) + + allowed_source_arns = [ + for account_id in local.allowed_source_accounts : + "arn:${data.aws_partition.destination.partition}:logs:${data.aws_region.destination.region}:${account_id}:*" + ] +} + +resource "aws_cloudwatch_log_destination" "destination" { + provider = aws.destination + name = var.cloudwatch_destination.name + role_arn = aws_iam_role.destination.arn + target_arn = aws_kinesis_stream.destination.arn +} + +data "aws_iam_policy_document" "destination_policy" { + statement { + sid = "AllowSourceAccountsToSubscribe" + effect = "Allow" + actions = ["logs:PutSubscriptionFilter"] + + principals { + type = "AWS" + identifiers = var.source_account_ids + } + + resources = [aws_cloudwatch_log_destination.destination.arn] + } + + dynamic "statement" { + for_each = length(var.destination_policy_source_organization_id) > 0 ? [1] : [] + + content { + sid = "AllowOrganizationToSubscribe" + effect = "Allow" + actions = ["logs:PutSubscriptionFilter"] + + principals { + type = "AWS" + identifiers = ["*"] + } + + condition { + test = "StringEquals" + variable = "aws:PrincipalOrgID" + values = [var.destination_policy_source_organization_id] + } + + resources = [aws_cloudwatch_log_destination.destination.arn] + } + } +} + +resource "aws_cloudwatch_log_destination_policy" "destination" { + provider = aws.destination + destination_name = aws_cloudwatch_log_destination.destination.name + access_policy = data.aws_iam_policy_document.destination_policy.json +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/iam.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/iam.tf new file mode 100644 index 0000000..b73a6a7 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/iam.tf @@ -0,0 +1,62 @@ +locals { + cloudwatch_destination_role_name = coalesce( + var.cloudwatch_destination.role_name, + "fleet-log-sharing-destination-role" + ) + + cloudwatch_destination_policy_name = coalesce( + var.cloudwatch_destination.policy_name, + "${local.cloudwatch_destination_role_name}-policy" + ) +} + +data "aws_iam_policy_document" "assume_role" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["logs.${data.aws_region.destination.region}.amazonaws.com"] + } + + condition { + test = "StringLike" + variable = "aws:SourceArn" + values = local.allowed_source_arns + } + } +} + +resource "aws_iam_role" "destination" { + provider = aws.destination + name = local.cloudwatch_destination_role_name + assume_role_policy = data.aws_iam_policy_document.assume_role.json + tags = var.tags +} + +data "aws_iam_policy_document" "destination" { + statement { + effect = "Allow" + actions = [ + "kinesis:DescribeStream", + "kinesis:DescribeStreamSummary", + "kinesis:PutRecord", + "kinesis:PutRecords", + ] + resources = [aws_kinesis_stream.destination.arn] + } +} + +resource "aws_iam_policy" "destination" { + provider = aws.destination + name = local.cloudwatch_destination_policy_name + policy = data.aws_iam_policy_document.destination.json + tags = var.tags +} + +resource "aws_iam_role_policy_attachment" "destination" { + provider = aws.destination + role = aws_iam_role.destination.name + policy_arn = aws_iam_policy.destination.arn +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/kinesis.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/kinesis.tf new file mode 100644 index 0000000..d430e02 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/kinesis.tf @@ -0,0 +1,19 @@ +resource "aws_kinesis_stream" "destination" { + provider = aws.target + name = var.kinesis.stream_name + retention_period = var.kinesis.retention_period + shard_count = var.kinesis.stream_mode == "PROVISIONED" ? var.kinesis.shard_count : null + + stream_mode_details { + stream_mode = var.kinesis.stream_mode + } + + tags = var.tags + + lifecycle { + precondition { + condition = data.aws_caller_identity.destination.account_id == data.aws_caller_identity.target.account_id + error_message = "aws.destination and aws.target providers must use the same AWS account." + } + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/outputs.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/outputs.tf new file mode 100644 index 0000000..a825fc0 --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/outputs.tf @@ -0,0 +1,19 @@ +output "log_destination" { + description = "CloudWatch Logs destination details to share with the source-account team." + value = { + arn = aws_cloudwatch_log_destination.destination.arn + name = aws_cloudwatch_log_destination.destination.name + region = data.aws_region.destination.region + account_id = data.aws_caller_identity.destination.account_id + role_arn = aws_iam_role.destination.arn + } +} + +output "kinesis" { + description = "Kinesis destination details." + value = { + stream_name = aws_kinesis_stream.destination.name + stream_arn = aws_kinesis_stream.destination.arn + region = data.aws_region.target.region + } +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/variables.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/variables.tf new file mode 100644 index 0000000..5f4f42f --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/variables.tf @@ -0,0 +1,64 @@ +variable "source_account_ids" { + type = list(string) + description = "AWS account IDs allowed to create subscription filters to this destination." + + validation { + condition = length(var.source_account_ids) > 0 + error_message = "source_account_ids must include at least one AWS account ID." + } +} + +variable "destination_policy_source_organization_id" { + type = string + description = "Optional AWS Organization ID allowed to subscribe to this destination." + default = "" +} + +variable "cloudwatch_destination" { + description = "CloudWatch Logs destination settings in the source log-group region." + type = object({ + name = optional(string, "fleet-log-sharing-destination") + role_name = optional(string, "fleet-log-sharing-destination-role") + policy_name = optional(string) + }) + default = {} + + validation { + condition = ( + var.cloudwatch_destination.role_name == null || + length(trimspace(var.cloudwatch_destination.role_name)) > 0 + ) + error_message = "cloudwatch_destination.role_name must be null or a non-empty string." + } +} + +variable "kinesis" { + description = "Kinesis stream settings used as the CloudWatch Logs destination target." + type = object({ + stream_name = string + stream_mode = optional(string, "ON_DEMAND") + shard_count = optional(number, 1) + retention_period = optional(number, 24) + }) + + validation { + condition = contains(["ON_DEMAND", "PROVISIONED"], var.kinesis.stream_mode) + error_message = "kinesis.stream_mode must be one of: ON_DEMAND, PROVISIONED." + } + + validation { + condition = var.kinesis.shard_count >= 1 + error_message = "kinesis.shard_count must be greater than or equal to 1." + } + + validation { + condition = var.kinesis.retention_period >= 24 && var.kinesis.retention_period <= 8760 + error_message = "kinesis.retention_period must be between 24 and 8760 hours." + } +} + +variable "tags" { + type = map(string) + description = "Tags to apply to created resources that support tags." + default = {} +} diff --git a/addons/byo-cloudwatch-log-sharing/target-account-kinesis/version.tf b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/version.tf new file mode 100644 index 0000000..6f8a9cd --- /dev/null +++ b/addons/byo-cloudwatch-log-sharing/target-account-kinesis/version.tf @@ -0,0 +1,14 @@ +terraform { + required_version = ">= 1.3.7" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.29.0" + configuration_aliases = [ + aws.destination, + aws.target, + ] + } + } +} diff --git a/addons/monitoring/lambda/go.mod b/addons/monitoring/lambda/go.mod index 5406129..ef4b9a8 100644 --- a/addons/monitoring/lambda/go.mod +++ b/addons/monitoring/lambda/go.mod @@ -1,6 +1,6 @@ module github.com/fleetdm/fleet/terraform/addons/monitoring/lambda -go 1.24.4 +go 1.25.7 require ( github.com/aws/aws-lambda-go v1.41.0