首页 > 解决方案 > 在云形成中输出 apikey 值

问题描述

我有一个输出变量的 cloudformation 模板。输出变量之一是

 ApiGKeyId:
    Description: "Api Key Id"
    Value: !Ref ApplicationApiGatewayApiKey

这将返回 API 网关密钥的 ID,而不是实际值。有没有办法获得价值?

标签: amazon-web-servicesamazon-cloudformationaws-api-gateway

解决方案


根据以下线程不支持属性“值”〜
https://github.com/awslabs/serverless-application-model/issues/206

第 3 方在此处一目了然地维护了可用属性: https ://theburningmonk.com/cloudformation-ref-and-getatt-cheatsheet/

经过一番研究,我觉得没有其他方法可以检索 ApiKey 的值,只能使用调用 lambda 函数的自定义资源。这是我的示例代码。

#######################################################
##### Start of Custom functions #####
#######################################################
ValueFunc:
  Type: AWS::Lambda::Function
  Properties:
    Code:
      ZipFile: >
        var response = require('cfn-response');
        var AWS = require('aws-sdk');

        exports.handler = function(event, context) {
          var apiKeyID = event.ResourceProperties.ApiKeyID;
          var apigateway = new AWS.APIGateway();
          var params = {
            apiKey: apiKeyID,
            includeValue: true
          };

          apigateway.getApiKey(params, function(err, ApiKeyData) {
            if (err) {
              console.log(err, err.stack); // an error occurred
              var responseData = { "mykey" : "error reading ApiKey" };
              response.send(event, context, response.SUCCESS, responseData);
            } else {
              console.log(ApiKeyData.value);      // successful response
              var responseData = { "mykey" : ApiKeyData.value };
              response.send(event, context, response.SUCCESS, responseData);
            }
          });
        };
    Handler: index.handler
    Runtime: nodejs8.10
    Timeout: 30
    Role: !Sub "arn:aws:iam::${AWS::AccountId}:role/${LambdaExecutionRole}"
GetApiKeyValue:
  Type: Custom::LambdaCallout
  Properties:
    ServiceToken: !GetAtt ValueFunc.Arn
    ApiKeyID: !Ref ApiKey

推荐阅读