通过Cloudformation,CodeBuild和CodePipeline将python包部署到AWS Lambda

时间:2017-02-23 14:43:27

标签: amazon-web-services aws-lambda amazon-cloudformation aws-codepipeline aws-codebuild

我想为我的AWS基础架构和AWS Lambda函数设置CI / CD管道。我们的想法是将所有内容都包含在代码,版本控制和自动化中。我只想git push到存储库并让CodePipeline从那里接管,更新我的基础设施,运行测试,如果成功,用最新的代码更新我的Lambda函数。

我将我的CloudFormation模板基于this excellent example。它看起来像这样:

AWSTemplateFormatVersion: 2010-09-09
Description: playground pipeline 1
Parameters:
  SourceRepositoryName:
    Type: String
    Default: lambda-playground
  SourceBranchName:
    Type: String
    Default: master

Resources:
  ArtifactsBucket:
    Type: AWS::S3::Bucket
    DependsOn: CloudFormationRole
    DeletionPolicy: Delete
    Properties:
      BucketName: lambda-playground-artifacts

  CodeBuildRole:
    Type: AWS::IAM::Role
    DependsOn: CloudFormationRole
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codebuild.amazonaws.com
      Policies:
        - PolicyName: ServiceRole
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Sid: CloudWatchWriteLogsPolicy
                Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'
              - Sid: CodeCommitPullPolicy
                Effect: Allow
                Action:
                  - codecommit:GitPull
                Resource: '*'
              - Sid: S3GetObjectPolicy
                Effect: Allow
                Action:
                  - s3:GetObject
                  - s3:GetObjectVersion
                Resource: '*'
              - Sid: S3PutObjectPolicy
                Effect: Allow
                Action:
                  - s3:PutObject
                Resource: '*'

  CodePipelineRole:
    Type: AWS::IAM::Role
    DependsOn: CloudFormationRole
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codepipeline.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess

  CloudFormationRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - cloudformation.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess

  CodeCommitRepository:
    Type: AWS::CodeCommit::Repository
    Properties:
      RepositoryName: !Ref SourceRepositoryName

  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    DependsOn: CloudFormationRole
    Properties:
      Description: A playground of Lambda
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/python:2.7.12
        Type: LINUX_CONTAINER
      Name: lambda-playground
      ServiceRole: !GetAtt CodeBuildRole.Arn
      Source:
        Type: CODEPIPELINE
      TimeoutInMinutes: 5

  CodePipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      ArtifactStore:
        Type: S3
        Location: !Ref ArtifactsBucket
      Name: !Ref AWS::StackName
      RestartExecutionOnUpdate: true
      RoleArn: !GetAtt CodePipelineRole.Arn
      Stages:
        - Name: Source
          Actions:
            - Name: Source
              ActionTypeId:
                Category: Source
                Owner: AWS
                Provider: CodeCommit
                Version: 1
              Configuration:
                RepositoryName: !Ref SourceRepositoryName
                BranchName: !Ref SourceBranchName
              OutputArtifacts:
                - Name: SourceOutput
        - Name: PipelineDeploy
          Actions:
            - Name: UpdatePipeline
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Provider: CloudFormation
                Version: 1
              Configuration:
                ActionMode: CREATE_UPDATE
                Capabilities: CAPABILITY_IAM
                RoleArn: !GetAtt CloudFormationRole.Arn
                StackName: !Ref AWS::StackName
                TemplatePath: SourceOutput::infra.yml
              InputArtifacts:
                - Name: SourceOutput
        - Name: Build
          Actions:
            - Name: BuildAndTest
              ActionTypeId:
                Category: Build
                Owner: AWS
                Provider: CodeBuild
                Version: 1
              Configuration:
                ProjectName: !Ref CodeBuildProject
              InputArtifacts:
                - Name: SourceOutput
              OutputArtifacts:
                - Name: BuildOutput

  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtifactsBucket
        S3Key: !Ref BuildOutput # DOES NOT WORK
      FunctionName: playground-fc
      Handler: src.main.handler
      # TODO: Role: foo
      Runtime: python2.7

Outputs:
  ArtifactsBucketURL:
    Description: Artifacts bucket URL
    Value: !GetAtt ArtifactsBucket.WebsiteURL
  RepositoryURL:
    Description: SSH URL of the repository
    Value: !GetAtt CodeCommitRepository.CloneUrlSsh

所以我有一个包含3个阶段的CodePipeline - Source,它抓取CodeCommit仓库中的代码PipelineDeploy,在必要时更新我的​​CloudFormation堆栈,并运行配置的Build CodeBuild项目。

我的buildspec.yml在这里:

version: 0.1

phases:
  install:
    commands:
      - pip install -r requirements.txt -t lib
  pre_build:
    commands:
      - python lib/pytest.py src
artifacts:
  type: zip
  files:
    - src/**/*
    - lib/**/*

它只是安装必要的库,通过pytest运行测试并创建一个部署zip。此zip文件是OutputArtifact阶段的Build,并存储在ArtifactsBucket中。但是,每次都会获得一个唯一的名称(例如dfVV6Uh),这是有道理的,但我不知道如何在LambdaFunction中引用它 - >属性 - >代码 - > S3Key字段。

所以我的问题是,如何创建堆栈/管道,在完成所有步骤后,将最新版本部署到我的AWS Lambda函数?有没有办法可以使用CodeDeploy来做到这一点?这里的最佳做法是什么?

2 个答案:

答案 0 :(得分:4)

您可以使用Parameter Override Fn::GetArtifactAttObjectKey属性动态提供AWS CodePipeline为您的CloudFormation部署操作生成的工件.zip的名称。

使用您的示例,UpdatePipeline CloudFormation部署操作的配置如下所示:

Configuration:
  ActionMode: CREATE_UPDATE
  Capabilities: CAPABILITY_IAM
  RoleArn: !GetAtt CloudFormationRole.Arn
  StackName: !Ref AWS::StackName
  TemplatePath: SourceOutput::infra.yml
  ParameterOverrides:
    {
      "LambdaKey" : { "Fn::GetArtifactAtt" : ["LambdaFunctionSource", "ObjectKey"]}
    }
InputArtifacts:
- Name: SourceOutput
- Name: BuildOutput

然后,声明然后引用您的CloudFormation堆栈模板中的LambdaKey参数:

Parameters:
  LambdaKey:
    Type: String
  # ...
Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtifactsBucket
        S3Key: !Ref LambdaKey
      # ...

答案 1 :(得分:1)

有一个如何实现类似功能的例子(通过CodePipeline / CodeBuild部署lambda函数)。 http://docs.aws.amazon.com/lambda/latest/dg/automating-deployment.html

这个例子是用NodeJS编写的lambda函数,但基本思路是一样的。在通过CodeBuild构建工件并让CodePipeline在阶段内管理工件传播之后,您可以使用CloudFormation部署/更新lambda函数。

如果有帮助,请告诉我。