Resolve secret created with CDK in a Cfn L1 Construct

Viewed 995

How can I use an L2 Secret created with Secrets Manager to resolve as an L1 Cfn Property value?

from aws_cdk import (
    core,
    aws_secretsmanager as secretsmanager,
    aws_elasticache as elasticache
)
class MyStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        redis_password = secretsmanager.Secret(
            self, "RedisPassword",
            description="Redis auth",
            generate_secret_string=secretsmanager.SecretStringGenerator(
                exclude_characters='/"@'
            )
        )
        self.redis = elasticache.CfnReplicationGroup(self, 'RedisCluster',
            auth_token=redis_password.secret_value,
            # other properties
        )

This gives the error

jsii.errors.JSIIError: Object of type @aws-cdk/aws-secretsmanager.Secret is not convertible to @aws-cdk/core.CfnElement

In Cloudformation to resolve a secret I'd use something like

AuthToken: !Sub '{{resolve:secretsmanager:${MySecret}::password}}'

But a L2 Secret doesn't output the Cfn Ref like L1 constructs do (that I know of)

What am I missing?

1 Answers

I was only missing the to_string() method

from aws_cdk import (
    core,
    aws_secretsmanager as secretsmanager,
    aws_elasticache as elasticache
)
class MyStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        redis_password = secretsmanager.Secret(
            self, "RedisPassword",
            description="Redis auth",
            generate_secret_string=secretsmanager.SecretStringGenerator(
                exclude_characters='/"@'
            )
        )
        self.redis = elasticache.CfnReplicationGroup(self, 'RedisCluster',
            auth_token=redis_password.secret_value.to_string(),
            # other properties
        )

This synthesizes to

{
  "RedisPasswordED621C10": {
    "Type": "AWS::SecretsManager::Secret",
    "Properties": {
      "Description": "Redis auth",
      "GenerateSecretString": {
        "ExcludeCharacters": "/\"@"
      }
    },
    "Metadata": {
      "aws:cdk:path": "my-cdk-stack/RedisPassword/Resource"
    }
  },
  "RedisCluster": {
    "Type": "AWS::ElastiCache::ReplicationGroup",
    "Properties": {
      "ReplicationGroupDescription": "RedisGroup",
      "AtRestEncryptionEnabled": true,
      "AuthToken": {
        "Fn::Join": [
          "",
          [
            "{{resolve:secretsmanager:",
            {
              "Ref": "RedisPasswordED621C10"
            },
            ":SecretString:::}}"
          ]
        ]
      },
      "OtherProps": "..."
    }
  }
}
Related