AwsCLI icon
If icon
SlackIncomingWebhook icon
Log icon
Fail icon
Schedule icon

AWS Cross-Region KMS DR Key Policy Synchronization

Detect and sync AWS KMS multi-region key policy drift across DR replica regions with pre-write backups, error tracking, and a per-run sync cap.

Categories
CloudInfrastructure

AWS KMS multi-region keys share key material across regions, but key policies remain region-scoped. When administrators update the primary key policy, replica keys in disaster recovery regions do not inherit the changes automatically. Over time, replica policies drift, potentially blocking failover workloads or exposing keys to unauthorized principals during a disaster. This workflow audits one multi-region key per execution, compares replica policies against the primary policy, stores previous replica policies in the working directory before writing, updates out-of-sync replicas up to a safety cap, notifies Slack, and fails when unreachable regions or permissions errors occur.

How it works

  1. sync_kms_dr_policies (io.kestra.plugin.aws.cli.AwsCLI) validates the target key and coordinates policy synchronization:
    • Extracts the bare key ID from primary_key_id using ${primary_key_id##*/} so both bare IDs (mrk-...) and full ARNs are accepted. Replicas share the identical key ID across regions.
    • Runs aws kms describe-key against primary_region using --query to verify four mandatory conditions: MultiRegion is True, MultiRegionKeyType is PRIMARY, KeyManager is CUSTOMER, and KeyState is Enabled. If any condition is not met, the task exits immediately with an error.
    • Extracts the primary default policy document using aws kms get-key-policy --policy-name default --query Policy --output text and saves it to primary_policy.json in the task working directory.
    • Iterates over comma-separated replica_regions. Each region is validated against the format pattern ^[a-z]{2}(-[a-z]+)+-[0-9]$ before any AWS call.
    • For each valid replica region, it invokes aws kms describe-key in that region. If the key is not found or access is denied, it records the failure under error_regions distinguishing ResourceNotFound from AccessDenied and other errors.
    • Calls aws kms get-key-policy for the replica and saves the existing policy to replica_<region>_previous_policy.json in the working directory. Because outputFiles tracks *.json, Kestra captures each previous policy as an execution artifact.
    • Compares whitespace-collapsed policy documents. Replicas with identical text are marked skipped(in-sync). Note that statement order differences or JSON serialization differences count as drift because policy equivalence requires exact structural parity.
    • When drift is detected and dry_run is false, it verifies that syncs_done has not exceeded max_policy_syncs_per_run. If under the cap, it runs aws kms put-key-policy --policy-name default --policy file://primary_policy.json --region <region>. The command never uses BypassPolicyLockoutSafetyCheck. If the cap is reached, remaining drifted regions are flagged skipped(cap-reached).
    • Emits structured execution metrics (drift_regions, synced_regions, skipped_regions, error_regions, syncs_done, cap_hit) using the JSON output convention.
  2. evaluate_result (io.kestra.plugin.core.flow.If) checks whether drift_regions or error_regions contains entries:
    • If drift or errors exist, alert_slack_summary posts an itemized breakdown including affected regions, sync counts, error categories, and artifact backup filenames.
    • If neither drift nor errors exist, log_all_in_sync logs a clean verification message.
  3. log_audit_summary (io.kestra.plugin.core.log.Log) logs a structured audit trail of all counters regardless of branch.
  4. fail_on_errors (io.kestra.plugin.core.flow.If) evaluates error_regions. If any replica region failed inspection or write, it triggers io.kestra.plugin.core.execution.Fail to ensure executions with partial failures are never marked successful.
  5. The errors block triggers alert_flow_failure to post a failure notification to Slack if an unhandled error occurs before the evaluation tasks execute.

What you get

  • Automated detection of cross-region KMS key policy drift across secondary DR regions.
  • Pre-write policy backups (replica_<region>_previous_policy.json) stored as Kestra artifacts, ensuring rollback recovery if an applied policy requires reversal.
  • Strict blast-radius controls: dry-run default, single-key execution scope, and a per-run maximum policy write cap.
  • Granular error categorization distinguishing ResourceNotFound from AccessDenied or invalid region strings, with workflow failure enforcement on error.
  • Direct Slack alerts displaying exact drift and remediation details.

Who it's for

  • Cloud Security Engineers enforcing consistent cryptographic authorization across AWS regions.
  • Site Reliability Engineers maintaining multi-region disaster recovery readiness.
  • Platform Architects managing infrastructure-as-code and preventing configuration drift.

Why orchestrate this with Kestra

Synchronizing KMS policies across regions with raw scripts often leads to unchecked mass updates, unrecorded prior states, and silent failures when individual regional endpoints fail. Kestra provides declarative workflow control with pre-flight key validation, automatic artifact storage of previous policies via outputFiles, bounded remediation caps, team notifications, and guaranteed failure signaling when regional endpoints reject updates.

Prerequisites

  • AWS IAM credentials configured with permissions for KMS multi-region key administration:
    • kms:DescribeKey on primary and replica key ARNs.
    • kms:GetKeyPolicy on primary and replica key ARNs for the default policy.
    • kms:PutKeyPolicy on replica key ARNs (required only when applying updates with dry_run: false).
    • Note: The policy applied to replicas must maintain kms:PutKeyPolicy permissions for the executing IAM principal, otherwise subsequent syncs will be locked out.
  • An active multi-region primary key and corresponding replica keys created in target regions. Replicas must be provisioned before running this synchronization workflow.
  • A Slack incoming webhook URL for operational notifications.

Secrets

  • AWS_ACCESS_KEY_ID: AWS access key ID for the KMS administrative principal.

  • AWS_SECRET_ACCESS_KEY: AWS secret access key for the KMS administrative principal.

  • SLACK_WEBHOOK_URL: Slack incoming webhook URL used for alerts and error notifications.

    In Kestra OSS, configure secrets as base64-encoded environment variables prefixed with SECRET_, such as SECRET_AWS_ACCESS_KEY_ID and SECRET_SLACK_WEBHOOK_URL.

Inputs

Input Type Default Notes
primary_key_id STRING <your-primary-key-id> Multi-region key ID (mrk-...) or ARN. Scope is one key per run.
primary_region STRING us-east-1 AWS region where the primary multi-region key resides.
replica_regions STRING us-west-2,eu-west-1 Comma-separated list of replica regions to check and synchronize.
max_policy_syncs_per_run INT 5 Maximum number of replica policy writes permitted in a single run.
dry_run BOOL true When true, audits drift without modifying replica policies.

Quick start

  1. Identify your primary multi-region key ID and confirmed replica regions:
    aws kms describe-key --key-id <your-primary-key-id> --region us-east-1
    
  2. Add AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and SLACK_WEBHOOK_URL in your Kestra namespace secrets.
  3. Run the workflow with dry_run: true to perform an initial non-destructive audit.
  4. Review execution outputs and download replica_<region>_previous_policy.json artifacts from the UI.
  5. Set dry_run: false to reconcile detected drift up to max_policy_syncs_per_run.
  6. Enable the weekly schedule trigger to maintain continuous compliance.

How to extend

  • Orchestrate bulk audits across multiple multi-region keys by creating a parent flow that iterates key IDs using io.kestra.plugin.core.flow.Loop and triggers this flow.
  • Publish drift metrics to Amazon CloudWatch or Datadog to track policy drift frequency over time.
  • Add an approval gate using io.kestra.plugin.core.flow.Pause before executing put-key-policy when drift is detected in critical production regions.
  • Export execution backup files (*.json) to an encrypted Amazon S3 compliance bucket for long-term audit retention.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.