微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 AWS Lambda 函数创建 CloudFormation 堆栈,传递 API 网关参数

如何解决从 AWS Lambda 函数创建 CloudFormation 堆栈,传递 API 网关参数

我无法在 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"
}

解决方法

我修改了你的 lambda 函数的代码。请检查代码中的注释以进行澄清:

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 实例。以便您了解这一点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。