Home > Net >  AWS CDK: Iterate over Secret keys
AWS CDK: Iterate over Secret keys

Time:11-17

I'm using a Secret to store environment secret key for a Fargate service. I'd like to filter this secret keys, removing some of them (those starting with "CDK_") and send all remaining keys/values to the container.

I was thinking of something like this:

secrets = aws_secretsmanager.Secret.from_secret_complete_arn(self, "Env",
    secret_complete_arn = …)

task_definition = aws_ecs.FargateTaskDefinition(stack, "MyTaskDef")
task_definition.add_container("MyContainer",
    image = …,
    environment = { 
        key: value 
        for key, value in secrets.secret_value.to_json().items() 
        if key[0:4] != "CDK_"})

But it's not working because of SecretValue resolution:

AttributeError: 'str' object has no attribute 'items'

print(secrets.secret_value.to_json())
# <unresolved-token>

Is there a way to iterate over a Secret keys in CDK?

CodePudding user response:

No, there is not. CDK doesn't access the secret itself, so it never has access to the actual value, and you can't do anything based on it, including iteration.

When you get a secret's value in CDK, you're just looking at a reference to it, or a token, not the actual value.

My suggestion would be to rethink the architecture - create a separate secret with your CDK_ keys, since Secrets should be used on a need-to-know basis. A task role shouldn't get access to the fields it doesn't need.

https://docs.aws.amazon.com/cdk/latest/guide/tokens.html

  • Related