問題描述
從 AWS Lambda 函數創建 CloudFormation 堆棧,傳遞 API Gateway 參數 (Create CloudFormation stack from AWS Lambda function, passing API Gateway parameters)
我無法在 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"
}
參考解法
方法 1:
I modified the code of your lambda function. Please check comments in the code for clarification:
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)
By the way, such function and API gateway can spin up a lot of ec2 instances very quickly. So that you are aware of this.