3

I'm trying to fetch the Secret as integer Value (port number) per CDK in order to create another resource. Basically when I need a String value for String parameters everything is working fine, but when I try to parse the String to int in order to provide the number parameter it does not work anymore. The problem is that CDK generates a reference for these values and it cannot be casted to a number value. The question is: is there any way to retrive the Secret Value as number?

Here some code snippets:

SecretManager Object:

const secret = secretsmanager.Secret.fromSecretAttributes(this, "SecretId", {
      secretCompleteArn: someValidSecretArn
    });

Working fine:

host: secret.secretValueFromJson('host').toString()

Not working because the parameter needs to be a number value:

port: secret.secretValueFromJson('port').toString()

Not working because port is null (it is not!), basically the reference cannot be parsed:

port: parseInt(secret.secretValueFromJson('port').toString())

Not working, same as above:

port: +secret.secretValueFromJson('port').toString()

1 Answers1

5

You can use the CDK's Token class to cast the token to a number:

https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-aswbrnumbervalue

port: cdk.Token.asNumber(secret.secretValueFromJson('port'));

It will be resolved to the proper value at deploy time.

gshpychka
  • 8,523
  • 1
  • 11
  • 31
  • is it correct to assume that the secret value will be shown during build time (in codebuild log) or only shown after the actual stack deployment? – Jack Rogers Apr 25 '23 at 14:35
  • It will not be shown at all, it will be displayed as a token throughout the deployment and in the stack template. – gshpychka Apr 25 '23 at 14:40
  • got it, we have similar problem with OP, where we are trying to make our frontend build to consume a secret value that exists in a secret manager, when i do ```cdk ls``` and the codebuild log it shows ```${Token[TOKEN.1532]}``` and i updated the code to ```cdk.Token.as_string(my_variables.secret_value_from_json('my_variable'))``` but its still not consumed by the frontend, and stuck where do we debug from here, do you have any pointers where to go from here? – Jack Rogers Apr 25 '23 at 15:17
  • How are you using the token? Where are you passing it? – gshpychka Apr 25 '23 at 15:37
  • i made a post about it so you can see the codes https://stackoverflow.com/questions/76103340/consuming-secret-values-when-building-react-using-cdk – Jack Rogers Apr 25 '23 at 16:13