Skip to main content

AWS Secret Cdk

A library to create and provision secrets by AWS SecretsManager. This library makes it easy to create secrets with secret rotation.

Remarks

The project is written by Laimonas Sutkus and is owned by iDenfy. This is an open source library intended to be used by anyone. iDenfy aims to share its knowledge and educate market for better and more secure IT infrastructure.

Related technology

This project utilizes the following technology:

  • AWS (Amazon Web Services).
  • AWS CDK (Amazon Web Services Cloud Development Kit).
  • AWS CloudFormation.
  • AWS SecretsManager.

Assumptions

This library project assumes the following:

  • You have knowledge in AWS (Amazon Web Services).
  • You have knowledge in AWS CloudFormation and AWS SecretsManager.
  • You are managing your infrastructure with AWS CDK.
  • You are writing AWS CDK templates with a python language.

Install

The project is built and uploaded to PyPi. Install it by using pip.

pip install aws-secret-cdk

Or directly install it through source.

./build.sh -ic

Description

SecretsManager is a great AWS service to manage your secrets e.g. database password. It is really easy to create and configure a secret through AWS console (UI). However it is notoriously difficult to create and manage secrets through CloudFormation. You need to create a lambda function, which executes secret rotation, ensure correct lambda function permissions and security groups, correctly configure secrets themselves with correct templates, etc. This library tackles this problem. In a nutshell, you just provide a database, for which the secret should be applied, and some other params. And that's it! You're good to go.

One big note - this library can be used on existing databases.

Examples

Here are the examples on how to use this library with various scenarios.

RDS (MySql and Aurora MySql compatible) Single user rotation

To create a SecretsManager Secret for an RDS database with 30 days rotation, create a Secret instance.

from aws_cdk.core import Stack
from aws_cdk.aws_ec2 import Vpc
from aws_cdk import aws_rds
from aws_secret_cdk.vpc_parameters import VPCParameters
from aws_secret_cdk.aurora_mysql_single_user.secret import Secret

class MyStack(Stack):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Suppose you have defined a VPC.
        self.vpc = Vpc(**kwargs)

        # Suppose you have a database (or a cluster).
        self.database = aws_rds.CfnDBCluster(**kwargs)

        # Now simply create a secret with 30 day rotation.
        self.rds_secret = Secret(
            stack=self,
            prefix='MyResourcesPrefix',
            vpc_parameters=VPCParameters(
                rotation_lambda_vpc=self.vpc,
                rotation_lambda_security_groups=[
                    # Your SG's.
                ],
                # NOTE! Ensure that your private subnets have a NAT gateway
                # or have a VPC endpoint in order to reach SecretsManager
                # API which is outside your own VPC.
                rotation_lambda_subnets=self.vpc.private_subnets
            ),
            database=self.database
        )

And that's pretty much it. From now own your database password will be stored in a SecretsManager and will be roted every 30 days.

Using the new secret

In order to retrieve the secret, use this sample code below.

# Use this code snippet in your app.
# If you need more information about configurations or implementing the sample code, visit the AWS docs:   
# https://aws.amazon.com/developers/getting-started/python/

import boto3
import base64
from botocore.exceptions import ClientError


def get_secret():

    secret_name = "test"
    region_name = "eu-west-1"

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        # Some error happened here. Log it / handle it / raise it.
        raise e
    else:
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            secret = base64.b64decode(get_secret_value_response['SecretBinary'])

        return secret

Release history

5.3.0

Include MD files.

5.2.0

Update to 1.60.0 and add upper dependency bound of 2.0.0.

5.1.0

Force update to CDK 1.44.0.

5.0.0

Restructure project having in mind that different types of rotations are possible e.g. DynamoDB secret rotation, or RDS multi user secret rotation. Narrowed down the permissions required for rotation. With this version an aws-secret-cdk package is fully functional and available to be used.

4.0.0

Do not enforce KMS CMKs. Use assets to deploy lambda function source code instead of S3 buckets. Use better prefixes. Refactor lambda function source code to support initial passwords on existing databases. Warning: loosened permissions. Next commit should fix them.

3.0.1

Update README.

3.0.0

Shorten lambda bucket name.

2.0.3

Consistent naming.

2.0.2

Add docstrings.

2.0.1

Fix target types and target arns.

2.0.0

General bug fixes. Add permission for KMS key resource. Add secret template.

1.0.9

Add secrets manager as a valid principal to invoke rotation lambda.

1.0.8

Add S3 removal policy.

1.0.7

Don't use managed policies.

1.0.6

Aws Lambda dependency update.

1.0.5

Aws Lambda dependency update.

1.0.4

Dont create Code class instance.

1.0.3

Move packages into main package.

1.0.2

Fix manifest file.

1.0.1

Ensure bucket and bucket deployment has different names.

1.0.0

Initial commit. Add ability to create RDS secret and rotate it every 30 days.

Metadata

Release files for aws-secret-cdk 5.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aws-secret-cdk 5.3.0
File Size Uploaded Provenance
aws_secret_cdk-5.3.0.tar.gz 65.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for aws-secret-cdk 5.3.0
File Interpreter ABI Platform
aws_secret_cdk-5.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 138.5 kB

Release files / aws_secret_cdk-5.3.0.tar.gz

Download URL aws_secret_cdk-5.3.0.tar.gz
Size 65.4 kB
Tags Source
SHA-256 checksum
How to use checksums
1afc519c8d2d0b88a58816b75b70c7d25717a30330951e706eeeda32939f7b84
BLAKE2b-256 checksum
How to use checksums
8250b63efb38b8d9f3450ae6aaed7431c1cc50efc7cb717e251fc82ad2568842
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.15.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.37.0 CPython/2.7.17

Release files / aws_secret_cdk-5.3.0-py3-none-any.whl

Download URL aws_secret_cdk-5.3.0-py3-none-any.whl
Size 73.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a93f960987a522022e9cf5d5445f6cfc8b5f29e627d77afdb74c143c1b936cdd
BLAKE2b-256 checksum
How to use checksums
977b44f0302d34f0780ffbef2782c14aa87205bf4d4e6ece7b217304eea29f30
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.15.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.37.0 CPython/2.7.17

Security for aws-secret-cdk 5.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page