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

mth*_*mth 10 amazon-web-services aws-cloudformation aws-codepipeline aws-codebuild

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

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

基本上,Code:为了获得CodeBuild文件(这是我在CodePipeline中的输出工件),我应该放在Lambda函数的属性中?

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
Run Code Online (Sandbox Code Playgroud)

buildspec.yml:

version: 0.2
phases:
  install:
    commands:
      - pip install -r requirements.txt -t libs
artifacts:
  type: zip
  files:
    - template.yml
    - main.py
    - lib/*
Run Code Online (Sandbox Code Playgroud)

mth*_*mth 12

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

{
  "buildBucketName" : { "Fn::GetArtifactAtt" : ["MyAppBuild", "BucketName"]},
  "buildObjectKey" : { "Fn::GetArtifactAtt" : ["MyAppBuild", "ObjectKey"]}
}
Run Code Online (Sandbox Code Playgroud)

然后改变了我的CF模板:

AWSTemplateFormatVersion: 2010-09-09
Parameters:
  buildBucketName:
    Type: String
  buildObjectKey:
    Type: String

  Resources:
    ...
    LambdaFunction:
        ...
        Code:
            S3Bucket: !Ref buildBucketName
            S3Key: !Ref buildObjectKey
Run Code Online (Sandbox Code Playgroud)

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