我可以通过CloudFormation向我的lambda函数添加代码提交触发器吗

时间:2019-04-26 19:37:14

标签: aws-lambda amazon-cloudformation aws-codecommit

我正在编写一个lambda函数,希望有人更新存储库的master分支来触发它。回购已存在于帐户中。

cloudformation中是否可以将触发器添加到lambda函数中?我猜想我可以创建一些cloudwatch规则来触发lambda,但宁愿将其全部保留在lambda中。

谢谢 R

1 个答案:

答案 0 :(得分:0)

如果您正在使用AWS无服务器转换,则可以将其自我包含在lambda中。尽管该转换会生成cloudwatch规则和lambda权限,但基本上与您提到的相同。

不过,这是一个示例,可以做您想做的事

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31


Description: Pipeline which triggers lambda for codecommit changes


Parameters:
  BranchName:
    Default: master
    Description: The GIT branch
    Type: String
  RepositoryName:
    Description: The GIT repository
    Type: String
  StackOwner:
    Description: The stack owner
    Type: String


Resources:

  BasicLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action: sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: logs:*
                Resource: arn:aws:logs:*:*:*
              - Effect: Allow
                Action: '*'
                Resource: '*'

  PipelineTriggerFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/trigger
      Handler: codetrigger.handler
      MemorySize: 256
      Role: !GetAtt BasicLambdaRole.Arn
      Runtime: python3.6
      Timeout: 900
      Environment:
        Variables:
          TestVariable: "TestValue"
      Events:
        CodeCommitPushEvent:
          Type: CloudWatchEvent
          Properties:
            Pattern:
              source:
                - aws.codecommit
              resources:
                - !Sub 'arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${RepositoryName}'
              detail:
                event:
                  - referenceCreated
                  - referenceUpdated
                repositoryName:
                  - !Ref RepositoryName
                referenceName:
                  - !Ref BranchName
      Tags:
        'owner': !Ref StackOwner
        'task': !Ref RepositoryName

显然,可以更好地指定lambda角色,而不要像示例中那样提供所有权限。