我正在使用 CloudFormation 创建堆栈,但目前在模板编写过程中遇到困难。这是我的 JSON 模板:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"LambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
import json
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context): # Get bucket name from the S3 event
print(event)
bucket_name = event['detail']['requestParameters']['bucketName']
# Create a bucket policy
bucket_policy = json.dumps({
s3 = boto3.client('s3')
def lambda_handler(event, context): # Get bucket name from the S3 event
print(event)
bucket_name = event['detail']['requestParameters']['bucketName']
# Create a bucket policy
bucket_policy = json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Sid": "MustBeEncryptedAtRest",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": [
"arn:aws:s3:::{}".format(bucket_name),
"arn:aws:s3:::{}/*".format(bucket_name)
],
"Condition": {
"StringNotEquals": {
"s3:x-amz-server-side-encryption": [
"AES256",
"aws:kms"
]
}
}
},
{
"Sid": "MustBeEncryptedInTransit",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::{}".format(bucket_name),
"arn:aws:s3:::{}/*".format(bucket_name)
],
"Condition": {
"Bool": {
"aws:SecureTransport": "false"
}
}
}
]
})
}
# Set the new policy s3.put_bucket_policy(Bucket = bucket_name, Policy = bucket_policy),
"Handler": lambda_handler,
"Role": ----
"Runtime": python3 .7
}
}
但是我在 "Code": import json
行上收到错误。我什至使用了不同的 JSON 验证器,但我无法理解为什么它根据亚马逊 CloudFormation 的格式不正确。
有什么想法吗?
最佳答案
您不能像这样使用 Lambda 函数输入,对于 JSON,其格式应类似于下面的输入示例。
"LambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"import json",
"import boto3",
"",
"s3 = boto3.client('s3')",
"",
"def lambda_handler(event, context):",
"print(\"Do something\")"
]
]
}
},
"Handler": "index.lambda_handler",
"Role": {
"Ref": "LambdaRole"
},
"Runtime": "python3.7"
}
}
请记住,CloudFormation 是 JSON 或 YAML,这意味着它必须进行解析,对于 Lambda,您可以指定针对您所使用的语言格式化的函数,也可以指定 Zip 文件。
关于JSON CloudFormation 格式不正确。我的 JSON 文件不正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898763/