【问题标题】:Create CloudFormation stack from AWS Lambda function, passing API Gateway parameters从 AWS Lambda 函数创建 CloudFormation 堆栈,传递 API Gateway 参数
【发布时间】:2021-05-11 19:51:08
【问题描述】:

我无法在 Lambda 函数中获取参数。如果我在 lambda 中提到参数值,它可以正常工作。当我从 Lambda 函数中删除参数值并尝试从 API 网关或测试 lambda 时,它会处理默认参数值。请帮忙 我的 Lambda 函数是:

import boto3
import time
import json

datetime = time.strftime("%Y%m%d%H%M%S")
stackname = 'myec2'
client = boto3.client('cloudformation')
response = client.create_stack(
  StackName= (stackname+ '-' + datetime),
  TemplateURL='https://testnaeem.s3.amazonaws.com/ec2tags.yaml',
  Parameters=[
  {
    "ParameterKey": "MyInstanceName",
    "ParameterValue": " "
  },
  {
    "ParameterKey": "MyInstanceType",
    "ParameterValue": " "
  }
]
)


def lambda_handler(event, context):
            return(response)

我的 CloudFormation 模板是:

---
Parameters:
  MyInstanceType:
    Description: Instance type description
    Type: String
  MyInstanceName:
    Description: Instance type description
    Type: String  

Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      AvailabilityZone: us-east-1a
      ImageId:  ami-047a51fa27710816e
      InstanceType: !Ref MyInstanceType
      KeyName: miankeyp
      Tags:
        - Key : Name
          Value : !Ref MyInstanceName
        - Key : app 
          Value : demo

请帮助 Lambda 函数需要进行哪些更改。

我的测试值是:

{
  "MyInstanceName": "demott",
  "MyInstanceType": "t2.micro"
}

【问题讨论】:

  • 您能否再次澄清一下,什么不起作用,什么是预期行为,如何重现问题,错误消息是什么?
  • 没有错误,但是默认取参数值。因为我正在传递实例大小 t2.micr,但它占用了 m1.small。
  • 您的模板中没有默认值,而在 lambda 中您只是使用空字符串。
  • 模板中没有默认值,但仍使用 m1.small 实例启动 ec2。
  • 如果我在 lambda 函数中使用字符串,那么它可以正常工作。但我想从 API 网关或 lambda 测试函数传递字符串“参数值”。

标签: api aws-lambda amazon-cloudformation serverless gateway


【解决方案1】:

我修改了您的 lambda 函数的代码。请检查代码中的 cmets 进行澄清:

import boto3
import time
import json

datetime = time.strftime("%Y%m%d%H%M%S")
stackname = 'myec2'
client = boto3.client('cloudformation')

def lambda_handler(event, context):

    print(event) # to check what your even actually is
    # it will be printed out in CloudWatch Logs for your
    # function

    # you have to check what the event actually looks like
    # and adjust event['MyInstanceName'] and event['MyInstanceType']
    # in the following code

    response = client.create_stack(
      StackName= (stackname+ '-' + datetime),
      TemplateURL='https://testnaeem.s3.amazonaws.com/ec2tags.yaml',
      Parameters=[
      {
        "ParameterKey": "MyInstanceName",
        "ParameterValue": event['MyInstanceName']
      },
      {
        "ParameterKey": "MyInstanceType",
        "ParameterValue": event['MyInstanceType']
      }
    ]
    )

    return(response)

顺便说一句,这样的功能和 API 网关可以非常快速地启动大量 ec2 实例。让您意识到这一点。

【讨论】:

  • 谢谢你,Marcin 这个解决方案有效。是的,但我的经理要求这种类型的 API 来自动部署资源。他们的安全解决方案是什么
  • @Naeem 很高兴它有效。它的用例特定。如果你的经理想要这个,那么我想他/她一定有充分的理由。
猜你喜欢
  • 2015-11-10
  • 2022-06-10
  • 2017-05-07
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2022-01-13
相关资源
最近更新 更多