具有clouformation的AWS lambda代码部署问题

时间:2018-02-08 16:18:00

标签: python-3.x amazon-web-services aws-lambda amazon-cloudformation

我正在尝试通过cloudformation部署lambda函数(python 3),即使堆栈创建成功,我在部署后遇到代码对齐问题!

以下是部署前来自cloudformation模板的实际代码:

lambdaEbsFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Code:
        ZipFile: >
          #!/usr/bin/env python

          import boto3
          import json
          import logging
          from __future__ import print_function

          #setup simple logging for INFO.
          logger = logging.getLogger()
          logger.setLevel(logging.ERROR)

          #define the connection for EC2.
          ec2 = boto3.resource('ec2', region_name="us-east-2")
          def lambda_handler(event, context):
            def tag_them(instance, detail):
                tempTags=[]
                v={}

                for t in instance.tags:
                    #pull the name tag and add volume detail
                    if t['Key'] == 'Name':
                        v['Value'] = t['Value'] + " - " + str(detail)
                        v['Key'] = 'Name'
                        tempTags.append(v)
                    #append the wanted tags to EBS
                    elif t['Key'] == 'Owner':
                        print("[INFO]: Owner tag " + str(t))
                        tempTags.append(t)
                    elif t['Key'] == 'Environment':
                        print("[INFO]: Environment Tag " + str(t))
                        tempTags.append(t)
                    else:
                        print("[INFO]: Skip Tag - " + str(t))

                print("[INFO] " + str(tempTags))
                return(tempTags)

            base_instances = ec2.instances.filter(
                Filters = [

                            {
                                'Name': 'tag:Name',
                                'Values': ['Jenkins Server']
                            },

                        ]
            )

            for instance in base_instances:
                for vol in instance.volumes.all():
                    tag = vol.create_tags(Tags=tag_them(instance, vol.attachments[0]['Device']))
                    print("[INFO]: " + str(tag))

创建成功堆栈后,这是控制台中的lambda函数!在这里我有什么错误的缩进或其他东西吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

根据此SO回答https://stackoverflow.com/a/21699210/970247,您应使用ZipFile: |代替ZipFile: >来正确保留换行符。

编辑: 遵循Abi在评论中的建议:首选 Lambda 代码在 S3 中,只需在模板中链接回来。这可能很麻烦,但幸运的是,使用 AWS CLI 可以实现自动化。您基本上可以在计算机上引用本地文件,并使用aws package该工具将自动将lambda代码上传到S3并生成带有相应链接的模板。 Here's the doc regarding that specific functionality