AWS宣布API Gateway支持资源策略,能否为SAM创建的AWS::Serverless::Api附加资源策略?
Absolutely! You can definitely attach a resource policy to an AWS::Serverless::Api created via CloudFormation SAM—this is fully supported, and there are a couple of straightforward ways to implement it. Let me walk you through the options:
1. Inline Policy via the Policy Property
The AWS::Serverless::Api resource has a native Policy property that lets you define your resource policy directly within the API definition. This is the simplest approach for most use cases:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MyServerlessApi: Type: AWS::Serverless::Api Properties: StageName: Prod Policy: Version: '2012-10-17' Statement: - Effect: Allow Principal: AWS: arn:aws:iam::123456789012:user/MyTrustedUser Action: execute-api:Invoke Resource: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyServerlessApi}/*/*/*'
SAM will automatically associate this inline policy with the underlying API Gateway REST API, so you don't need extra linking steps.
2. Standalone Policy Resource
If you prefer to keep your policy logic separate (for reusability or better organization), you can create an AWS::ApiGateway::ResourcePolicy and link it to your Serverless API using the RestApiId property:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MyServerlessApi: Type: AWS::Serverless::Api Properties: StageName: Prod MyApiResourcePolicy: Type: AWS::ApiGateway::ResourcePolicy Properties: RestApiId: !Ref MyServerlessApi PolicyDocument: Version: '2012-10-17' Statement: - Effect: Deny Principal: '*' Action: execute-api:Invoke Resource: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyServerlessApi}/*/*/*' Condition: NotIpAddress: aws:SourceIp: '192.168.0.0/16'
Key Things to Remember
- Always use the correct
execute-apiaction names and resource ARN format:arn:aws:execute-api:<region>:<account-id>:<api-id>/<stage>/<method>/<resource-path>. Wildcards (*) work for stages, methods, or paths when needed. - Leverage CloudFormation functions like
!Ref,!Sub, and!GetAttto dynamically populate values (e.g., account ID, region) instead of hardcoding them—this makes your template more portable. - Test your policy thoroughly to ensure it enforces the intended access controls (you can use the API Gateway console's policy simulator or test invocations with different principals).
内容的提问来源于stack exchange,提问作者niqui

