I am using SAM template to deploy Lambda function and api gateway. I am using AWS::Serverless::Function to define my lambda function. I am using AWS::Serverless::Api to define my API. I am also using AWS::Lambda::Permission to grant permission to apigateway for the function.
The problem is resource creation of AWS::Lambda::Permission fails because my Alias is not available. My LambdaFunction resource creates the Alias but before even it is getting created the Lambda permission resource creation is triggered and it fails if it doesn't see the Alias mentioned.
i use "aws cloudformation deploy" to deploy the template
Adding DependsOn attribute to LambdaPermission resource doesn't work
> LambdaFunction:
> Type: AWS::Serverless::Function
> Properties:
> Handler: MyHandler
> Runtime: !Ref LambdaJavaVersion
> CodeUri: ./build.jar
> Description: !Sub "${LambdaName} function"
> Role: !GetAtt LambdaIAMRole.Arn
> FunctionName: !Ref LambdaName
> AutoPublishAlias: prod
> APIResource:
> DependsOn: LambdaFunction
> Type: AWS::Serverless::Api
> Properties:
> DefinitionUri: ./swagger/swagger.yml
> EndpointConfiguration: REGIONAL
> StageName: prod
>
> LambdaPermission:
> DependsOn:
> - LambdaFunction
> - APIResource
> Type: AWS::Lambda::Permission
> Properties:
> FunctionName: !Join
> - ""
> - [!GetAtt LambdaFunction.Arn,":","prod"]
> Action: lambda:InvokeFunction
> Principal: apigateway.amazonaws.com
> SourceArn: !Join
> - ""
> - [!Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}",':',!Ref
> APIResource,'/*/*/*']
I would like to create the LambdaPermission only after Alias is published.
After struggling with this myself, I found this in the documentation:
AutoPublishAlias Property Is Specified
When the AutoPublishAlias property of an
AWS::Serverless::Functionis specified, AWS SAM generates the following AWS CloudFormation resources:
AWS::Lambda::AliasandAWS::Lambda::Version.AWS::Lambda::Alias
LogicalId:
<function‑LogicalId>Alias<alias‑name><alias‑name> is the string that AutoPublishAlias is set to. For example, if you set AutoPublishAlias to live, the LogicalId is: MyFunctionAliaslive.
Referenceable property:
<function‑LogicalId>.Alias
The last line is the solution. So to make your permission depend on the alias, and therefore, get created only after the alias has been created, you can reference the alias this way:
YAML
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref LambdaFunction.Alias
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
JSON
"LambdaPermission": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"FunctionName": {
"Ref": "LambdaFunction.Alias"
},
"Action": "lambda:InvokeFunction",
"Principal": "apigateway.amazonaws.com"
}
}
The DependsOn property is not necessary as the permission now implicitly depends on the alias to be created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With