首页 文章

如何在CloudFormation中使用CodeBuild的输出工件?

提问于
浏览
5

所以我有一个相当简单的堆栈我正在尝试设置由一个订阅SNS主题的Lambda函数组成 . 我想使用CodePipeline有三个阶段:Source(GitHub) - > Build(CodeBuild) - > Deploy(CloudFormation) .

我设法凑齐了一个模板和buildspec文件,这是有效的,除了我失去了我应该如何引用CodeBuild在CloudFormation模板中产生的输出工件;现在我只有占位符内联代码 .

基本上,我应该在Lambda函数的 Code: 属性中放置什么才能获取CodeBuild文件(这是我在CodePipeline中的输出工件)?

template.yml:

AWSTemplateFormatVersion: 2010-09-09
Resources:
  SNSTopic:
    Type: 'AWS::SNS::Topic'
    Properties:
      Subscription:
        - Endpoint: !GetAtt
            - LambdaFunction
            - Arn
          Protocol: lambda
  LambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Runtime: python3.6
      Handler: main.lamda_handler
      Timeout: '10'
      Role: !GetAtt
        - LambdaExecutionRole
        - Arn
      Code:
        ZipFile: >
          def lambda_handler(event, context):
            print(event)
            return 'Hello, world!'
  LambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName: !GetAtt
        - LambdaFunction
        - Arn
      Action: 'lambda:InvokeFunction'
      Principal: sns.amazonaws.com
      SourceArn: !Ref SNSTopic

buildspec.yml:

version: 0.2
phases:
  install:
    commands:
      - pip install -r requirements.txt -t libs
artifacts:
  type: zip
  files:
    - template.yml
    - main.py
    - lib/*

2 回答

  • 2

    最后通过AWS支持找到了解决方案 . 首先,我将此JSON放在CodePipeline的CloudFormation部署步骤中的参数覆盖中:

    {
      "buildBucketName" : { "Fn::GetArtifactAtt" : ["MyAppBuild", "BucketName"]},
      "buildObjectKey" : { "Fn::GetArtifactAtt" : ["MyAppBuild", "ObjectKey"]}
    }
    

    然后改变了我的CF模板:

    AWSTemplateFormatVersion: 2010-09-09
    Parameters:
      buildBucketName:
        Type: String
      buildObjectKey:
        Type: String
    
      Resources:
        ...
        LambdaFunction:
            ...
            Code:
                S3Bucket: !Ref buildBucketName
                S3Key: !Ref buildObjectKey
    

    这将CodeBuild作为参数输出的输出工件存储桶名称和对象密钥传递给CF,这样它就可以动态获取S3中的输出工件位置,而无需对任何内容进行硬编码,从而使模板更具可移植性 .

  • 5

    您的CodeBuild应该将您的zip文件丢弃到S3存储桶 . 因此,在LambdaFunction资源的“代码”部分中,您可以指向它 .

    Code:
       S3Bucket: the_bucket_where_CodeBuild_dropped_your_zip
       S3Key: the_name_of_the_zip_file_dropped
    

    你不需要'ZipFile:'

相关问题