所以我有一个相当简单的堆栈我尝试设置由订阅SNS主题的单个Lambda函数组成。我想在三个阶段使用CodePipeline:Source(GitHub) - >构建(CodeBuild) - >部署(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/*
答案 0 :(得分:10)
最后通过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中的输出工件位置,而无需对任何内容进行硬编码,从而使模板更具可移植性。
答案 1 :(得分:2)
您的CodeBuild应该将您的zip文件丢弃到S3存储桶。因此,在LambdaFunction资源的Code部分中,您指向它。
Code:
S3Bucket: the_bucket_where_CodeBuild_dropped_your_zip
S3Key: the_name_of_the_zip_file_dropped
您不需要'ZipFile:'
答案 2 :(得分:0)
我意识到这个问题很老,但是我想就SAM回答它
project_root/
template.yaml
buildspec.yaml
my_lambda/
my_lambda.py
requirements.txt
template.yaml:
Transform: AWS::Serverless-2016-10-31
Resources:
MyLambda:
Type: AWS::Serverless::Function
Properties:
Handler: my_lambda.lambda_handler
CodeUri: my_lambda/
Runtime: python3.8
buildspec.yaml:
version: 0.2
phases:
install:
runtime-versions:
python: 3.8
commands:
- pip install aws-sam-cli
build:
commands:
- sam build
- sam package --s3-bucket mybucket --s3-prefix sam | sam deploy -t /dev/stdin --stack-name FOOSTACK --capabilities CAPABILITY_IAM
注意:
sam build
会pip install
您的λrequirements.txt
sam package
将压缩您的lambda,并用其内容的md5命名它,然后为您上传到S3(仅已更改)sam deploy
将创建一个CloudFormation变更集并为您运行它