cre*_*ian 4 amazon-web-services aws-cloudformation boto3 aws-lambda aws-sam-cli
我知道如何调用我已命名且已作为 Lambda 函数存在的 lambda 函数,但是我如何让 FunctionA 调用我在 AWS SAM 模板中一起定义的 FunctionB,并且事先不知道名称,也就是动态的。
有没有办法在创建之前将 FunctionB 的名称作为 SAM 模板的一部分传递,以便模板在创建 FunctionA 之前知道 FunctionB 的全名的名称?
我看到很多关于仅在本地测试的问题
小智 7
SAM 与 CloudFormation 不同。SAM 有一个捷径。SAM 资源类型AWS::Serverless::Function简化了这一点。
在此示例 SAM 模板中,示例资源“CallerFunction”具有:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
A SAM template where lambda function caller invokes lambda function microservice.
Resources:
CallerFunction:
Type: AWS::Serverless::Function
Properties:
Description: 'A lambda that invokes the function microservice'
CodeUri: caller/
Handler: app.handler
Runtime: nodejs10.x
Policies:
- LambdaInvokePolicy:
FunctionName:
!Ref MicroserviceFunction
Environment:
Variables:
MICROSERVICE_FUNCTION: !Ref MicroserviceFunction
MicroserviceFunction:
Type: AWS::Serverless::Function
Properties:
Description: 'A microservice lambda'
CodeUri: microservice/
Handler: index.handler
Runtime: nodejs10.x
Policies: CloudWatchLogsFullAccess
Run Code Online (Sandbox Code Playgroud)
享受无服务器带来的乐趣!
您可以将其他函数的名称或 ARN 作为环境变量传递。例如:
Resources:
FunctionA:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Runtime: python3.6
Role: !Sub ${FunctionRole.Arn}
Environment:
Variables:
# pass FunctionB ARN as environment variable
FUNCTION_B_ARN: !Sub ${FunctionB.Arn}
Code:
ZipFile: |
import os
def handler(event, context):
# use environment variable
print(os.getenv("FUNCTION_B_ARN"))
FunctionB:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Runtime: python3.6
Role: !Sub ${FunctionRole.Arn}
Code:
ZipFile: |
def handler(event, context):
print("hello world")
FunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Version: '2012-10-17'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1124 次 |
| 最近记录: |