Syncing AWS Secrets Manager across accounts
Tags: aws, security, devops, python
Published: 2024-05-14 16:53:35

## Introduction

In this guide, we'll explore how to synchronize AWS Secrets Manager values across two different AWS accounts using Lambda and EventBridge.

## Setup

We have two AWS accounts, A and B, each running separate e-commerce sites. Account A stores database information in Secrets Manager, and Account B needs to use this data. The goal is to sync secrets from Account A to Account B whenever they change.

## Solution Overview

We'll use AWS EventBridge to detect changes in Secrets Manager in Account A and trigger a Lambda function that updates Secrets Manager in Account B.

![Architecture: Syncing AWS Secrets Manager across accounts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7szzuehkirnjcto55on.jpg)

### Steps

1. **Account B Preparation**
    - **Create Secrets Manager Secret**: Name it `super-top-secretB`.
    - **Create IAM Role**: Allow switching from Account A to operate Secrets Manager in Account B.

        ```json
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "AWS": "arn:aws:iam::<AccountA-ID>:role/service-role/AccountB-SecretsManager-change-Lambda-role"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
```

    - **Attach Policy**: Attach `SecretsManagerReadWrite` policy to the role.

2. **Account A Preparation**
    - **Create Lambda Function**: This function will read secrets from Account A and write them to Account B.

        ```json
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": "sts:AssumeRole",
                    "Resource": "arn:aws:iam::<AccountB-ID>:role/secretsmanager-change-role"
                }
            ]
        }
```

    - **Attach Policies**: Attach `AWSLambdaBasicExecutionRole`, `SecretsManagerReadWrite`, and `AccountB-assumerole-policy`.

3. **Lambda Function Code**

    ```python
    import boto3
    import json

    def lambda_handler(event, context):
        source_secret_name = "super-top-secretA"
        destination_secret_name = "super-top-secretB"

        client_source = boto3.client('secretsmanager', region_name='eu-west-2')

        sts_client = boto3.client('sts')
        assumed_role = sts_client.assume_role(
            RoleArn="arn:aws:iam::<AccountB-ID>:role/secretsmanager-change-role",
            RoleSessionName="ReplicateSecretSession"
        )
        credentials = assumed_role['Credentials']

        client_destination = boto3.client(
            'secretsmanager',
            region_name='eu-west-2',
            aws_access_key_id=credentials['AccessKeyId'],
            aws_secret_access_key=credentials['SecretAccessKey'],
            aws_session_token=credentials['SessionToken'],
        )

        secret_value = client_source.get_secret_value(SecretId=source_secret_name)['SecretString']

        response = client_destination.put_secret_value(
            SecretId=destination_secret_name,
            SecretString=secret_value
        )

        return {
            'statusCode': 200,
            'body': json.dumps('Secret replicated successfully.')
        }
    ```

4. **Create EventBridge Rule**

    Create an EventBridge rule to detect changes in Secrets Manager in Account A and set the Lambda function as the target.

    ```json
    {
      "source": ["aws.secretsmanager"],
      "detail-type": ["AWS API Call via CloudTrail"],
      "detail": {
        "eventSource": ["secretsmanager.amazonaws.com"],
        "eventName": ["PutSecretValue"],
        "responseElements": {
          "arn": ["arn:aws:secretsmanager:eu-west-2:<AccountA-ID>:secret:super-top-secretA"]
        }
      }
    }
    ```

## Conclusion

By following these steps, you can automate the synchronization of secrets across AWS accounts using EventBridge and Lambda. This approach ensures that secrets in Account B are always up to date with changes in Account A.


---

### Stay Connected and Get More Insights
If you found this guide helpful and are dealing with similar challenges, don't hesitate to reach out for personalized consulting at [Superpeer](https://superpeer.com/siddhantkhare/). For more tech insights and updates, consider following me on [GitHub](https://github.com/Siddhant-K-code). Let's innovate together!