AWS lambda从CloudFormation读取参数或输出 [英] AWS lambda read parameter or outputs from CloudFormation

查看:66
本文介绍了AWS lambda从CloudFormation读取参数或输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看似非常简单的任务,但很难找到很好的例子.
因此,任务如下:AWS Lambda将一些消息发送到AWS-SQS.

Looks as really simple task but it's difficult to find good example on it.
So, the task is following: AWS lambda puts some message to AWS-SQS.

AWS Lambda的代码包含以下行:

Code of AWS lambda contains such line:

var QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/ID/QUEUE_NAME';",

为了摆脱此代码,可能有两个选择:

In order to get rid of this code there are possible two options:

  1. 创建查询,该查询将根据区域和队列名称 SQS查找此队列名称可预测;
  2. 创建Cloud Formaion脚本并在其中指定这些依赖项.

基于这一事实,定期触发器(lambda)一天会工作多次,因此最好在部署期间指定此依赖项.

Based on this fact that periodic trigger (lambda) will work many times a day it's better to specify this dependency duting deployment.

通常看起来像是直接任务和云形成脚本已创建:

In general it looks like as straight forward task and cloud formations script was created:

 "Resources": {
"LF2HNR1": {
  "Type": "AWS::Lambda::Function",
    "Properties": {
    "Description": "This is  lambda trigger",
    "Handler": "index.myHandler",
    "Runtime": "nodejs",
    "Timeout": "300",

并且还指定了lambda依赖于SQS的依赖性:

And also dependency was specified that lambda depends on SQS:

 "DependsOn": [
    "SQSQ562D4"
  ]
},
"SQSQ562D4": {
  "Type": "AWS::SQS::Queue",
  "Properties": {},

  }

但是,如何以编程方式在lambda代码中获取SQS url并不是一项艰巨的任务:

Hovewer it's not stright forward task how to programmatically get SQS url in lambda code:

    exports.handler = function(event, context) {
 var params = {
    MessageBody: JSON.stringify(event),
 var QUEUE_URL = ????

推荐答案

我建议您检索 SQS URL 并将其用作 CloudFormation 输出:

I suggest you retrieve the SQS URL and use it as CloudFormation output:

"Outputs" : {
    "SQSQ562D4" : {
      "Description" : "URL of the source queue",
      "Value" : { "Ref" : "SQSQ562D4" }
    }
}

授予您的 Lambda 函数 cloudformation:DescribeStacks 权限,以读取您的 CloudFormation 堆栈的输出并将此输出在运行时加载到您的代码中以进行访问 SQS URL .

Grant your Lambda function cloudformation:DescribeStacks permission to read outputs of your CloudFormation stack and load this output in your code at runtime to access the SQS URL.

请勿使用以下答案中的方法.它在函数运行时加载资源配置(队列URI),而不是在Lambda Function部署时注入资源.下面的方法是增加延迟,可能在AWS服务速率限制方面出现随机问题,并且可能依赖于AWS​​ CloudFormation API.

Don't use the approach from the answer below. It's loading resource configuration (the queue URI) in function run time instead of injecting it at Lambda Function deploy time. Below approach is increasing latency, can have random issues with AWS service rate limiting and can is dependent on the AWS CloudFormation API.

这篇关于AWS lambda从CloudFormation读取参数或输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆