How to get the value of an api key in CDK (AWS)

Viewed 1535

I have this problem. I want to create an API Gateway that can only be accessed with an API key - that part is done. Now I want to store the value of the API key in secrets manager. I am able to store hardcoded values in the secrets manager but not the actual value of the API keys. The code for creating the api keys is:

const key = api.addApiKey('ApiKey');

and I am able to store a hardcoded value in secrets manager with:

const secret = new secretsmanager.Secret(this, 'Secret', {
      description: "Secret ",
      secretName: "secret",
      generateSecretString: {
        secretStringTemplate: JSON.stringify({"api_key" : "some_value"}),
        generateStringKey: "string_key",
      }
    });

How can i store the api key instead of the hardcoded value?

1 Answers

I don't think there is a way we can extract the api key value without a custom resource.

But this can easily be done the other way round. we first need to generate the secret and use that value to create api key.

    const secret = new secretsmanager.Secret(this, 'Secret', {
        generateSecretString: {
            generateStringKey: 'api_key',
            secretStringTemplate: JSON.stringify({ username: 'web_user' }),
            excludeCharacters: ' %+~`#$&*()|[]{}:;<>?!\'/@"\\',
        },
    });
    this.restApi.addApiKey('ApiKey', {
        apiKeyName: `web-app-key`,
        value: secret.secretValueFromJson('api_key').toString(),
    });
Related