如何在 CDK (AWS) 中获取 api 键的值

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

我有这个问题。我想创建一个只能使用 API 密钥访问的 API 网关 - 该部分已完成。现在我想将 API 密钥的值存储在 secrets manager 中。我能够在机密管理器中存储硬编码值,但不能存储 API 键的实际值。创建 api 键的代码是:

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

并且我能够通过以下方式在机密管理器中存储硬编码值:

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

如何存储 api 键而不是硬编码值?

我不认为我们可以在没有自定义资源的情况下提取 api 键值。

但这可以很容易地反过来完成。我们首先需要生成密钥并使用该值创建 api 密钥。

    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(),
    });