我正在尝试使用BOTO3来创建一个调用lambda函数的Api Gateway方法。到目前为止,我一直无法找到如何授予必要的权限。
奇怪的是,通过AWS控制台手动设置lambda方法名称会自动设置权限。我无法在代码中复制它。
这是我用来设置网关的代码:
# Create a rest api
self.rest_api = self.apigateway.create_rest_api(
name='AWS_CMS_Operations'
)
# Get the rest api's root id
root_id = self.apigateway.get_resources(
restApiId=self.rest_api['id']
)['items'][0]['id']
# Create an api resource
api_resource = self.apigateway.create_resource(
restApiId=self.rest_api['id'],
parentId=root_id,
pathPart='AWS_CMS_Manager'
)
# Add a post method to the rest api resource
api_method = self.apigateway.put_method(
restApiId=self.rest_api['id'],
resourceId=api_resource['id'],
httpMethod='POST',
authorizationType='NONE'
)
# Add an integration method to the api resource
self.apigateway.put_integration(
restApiId=self.rest_api['id'],
resourceId=api_resource['id'],
httpMethod='POST',
type='AWS',
integrationHttpMethod='POST',
uri=self.create_api_invocation_uri()
)
# Set the put method response for the api resource
self.apigateway.put_method_response(
restApiId=self.rest_api['id'],
resourceId=api_resource['id'],
httpMethod='POST',
statusCode='200',
responseModels={
'application/json': 'Empty'
}
)
# Set the put integration response for the api resource
self.apigateway.put_integration_response(
restApiId=self.rest_api['id'],
resourceId=api_resource['id'],
httpMethod='POST',
statusCode='200',
responseTemplates={
'application/json': ''
}
)
# Create a deployment of the rest api
self.apigateway.create_deployment(
restApiId=self.rest_api['id'],
stageName='prod'
)
# Give the api deployment permission to trigger the lambda function
self.lmda.add_permission(
FunctionName=self.lmda_function['FunctionName'],
StatementId='apigateway-production-aws-cms',
Action='lambda:InvokeFunction',
Principal='apigateway.amazonaws.com',
SourceArn=self.create_api_permission_uri(api_resource)
)
除了为网关设置适当的权限以调用lambda之外,一切正常。
答案 0 :(得分:0)
来自此tutorial的第3.6节是一个示例CLI命令:
$ aws lambda add-permissionn \
--function-name <function-name> \
--statement-id apigateway-test-2 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "<method-arn">
应该直截了当地翻译成Boto3。
答案 1 :(得分:0)
我可以使用以下代码在Boto3中运行该功能:
source_arn = f'arn:aws:execute-api:{REGION}:{account_id}:{api_id}/*/*/{api_path}'
lambda_client.add_permission(FunctionName=lambda_function_arn, StatementId=f'invoke_{api_id}',
Action='lambda:InvokeFunction', Principal='apigateway.amazonaws.com',
SourceArn=source_arn)
这不使用原始问题中的约定,但是我想指出三件事,这可能有助于解决该问题的任何人: