在无服务器框架中引用现有的 Cloudformation 堆栈输出

Reference Existing Cloudformation Stack Outputs in Serverless Framework

我们正在评估是否对我们的一些新 AWS 应用程序基础设施使用 Serverless。我们大量使用 Cloudformation(由 Ansible 部署),因此我们需要能够清晰地引用现有 Cloudformation 堆栈的输出——一个直接的例子是获取我们现有 AWS 网络基础设施的子网 ID 以供 lambda 函数使用.

经过大量浏览,我还没有看到一个开箱即用的方法来做到这一点。我们现有的 Cloudformation 堆栈的命名方式是,如果我只需键入堆栈的名称和所需的输出变量,我就可以在各种环境中可靠地获得所需的输出。我看到的一种可能的解决方案是使用 aws cli 提取变量并将它们作为环境变量传递给无服务器,但如果可能的话我想要一种更简洁的方法。

我认为处理您的示例案例的最简单方法是让 lambda 使用 boto3 调用 boto3.client('cloudformation', region_name=*specified region*).describe_stacks(StackName=*specified stack*)['Stacks']。此列表包含与指定的 StackName 匹配的所有堆栈,如果您的所有网络基础设施共享其名称的子集,您可以通过为该子字符串指定 StackName 来列出所有这些。每个 Stack 对象都包含一个 'Outputs' 块。参见 here

如果您想公开它以便于从任何地方使用,您可以将 API 网关 GET 方法附加到 lambda 并将其公开到 HTML 表单。

如果 Serverless Framework allows you to use Intrinsic Functions within your CloudFormation templates, you can create cross-stack references within a CloudFormation template by exporting stack output values from one stack (using the Exports property in the Outputs section), and using the Fn::ImportValue 内部函数在另一个堆栈中引用导出值。