AWS SAM cloudformation: API Gateway can't invoke lambda (AWS::Serverless::Function ) - aws-lambda

I created a template.yaml file to declare a simple lambda function that is invoked by api gateway. When I try to invoke the function from the api gateway url the request fails with {"message": "Internal server error"} and in cloudwatch api gateway logs I see the error message Invalid permissions on Lambda function.
This is my template.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
AliasName:
Type: String
Default: dev
Resources:
DynamoDBTenantTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: clientApiKey
AttributeType: S
KeySchema:
- AttributeName: clientApiKey
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
TableName: !Sub "authtable-${AliasName}"
AmeAuthenticatorLambda:
Type: AWS::Serverless::Function
Properties:
Handler: authenticator.handler
Policies: AmazonDynamoDBFullAccess
Runtime: nodejs8.10
CodeUri: src/
Environment:
Variables:
TABLE_NAME: !Sub "authtable-${AliasName}"
Events:
AuthenticatorEvent:
Type: Api
Properties:
Path: /authentication/
Method: POST
The SAM Documentation says that the syntax above is able to create the necessary permissions and API declaration implicitly.
I also followed an example from AWS website.
If I add to the template.yaml file a lambda:InvokeFunction permission then the invocation works, but by reading the documentation doing that should not be necessary.
What can be going wrong?

Related

How to add desired policy to lambda with cloudformation & SAM

I want to make a lambda function that has access to dynamoDB and other lambda functions.
However, I don't know how to make an appropriate YAML template for SAM to give appropriate permissions.
Especially, I don't understand the confusing 3 entries including definitions
of the permissions (AWS::IAM::Role, AWS::Serverless::Function, AWS::Lambda::Permission). Which entry should I use to add the necessary permissions?
Here is my YAML below. But the created my_lambda_role does not have AWSLambdaRole policy and policy for dynamoDB. As a result, the lambda fails to access to dynamoDB. Please tell me how to fix it.
MyLambdaRole:
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
- arn:aws:iam::aws:policy/service-role/AWSLambdaRole
RoleName: my_lambda_role
OnConnectFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: onconnect/
Handler: index.lambda_handler
MemorySize: 256
Role: !GetAtt MyLambdaRole.Arn
Runtime: python3.6
Environment:
Variables:
TABLE_NAME: !Ref TableName
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref TableName
- Statement:
- Effect: Allow
Action:
- 'execute-api:ManageConnections'
Resource:
- 'arn:aws:execute-api:*:*:*/#connections/*'
OnConnectPermission:
Type: AWS::Lambda::Permission
DependsOn:
- MyAPI
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref OnConnectFunction
Principal: apigateway.amazonaws.com
You can add the missing policies. Depending on what you want, but if you want full access, then you can add AmazonDynamoDBFullAccess:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/service-role/AWSLambdaRole
- arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess

Invalid template resource property 'Policies'

Can you please help with what is wrong here?
when I am trying to run this following cloud formation stack getting error. I am trying to create the lambda function with the sns role using cloud formation Invalid template resource property 'Policies'
AWSTemplateFormatVersion: '2010-09-09'
Description: VPC function.
Resources:
Function:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Code:
S3Bucket: teste-artifact-bucket
S3Key: function.zip
Runtime: python3.6
Timeout: 5
TracingConfig:
Mode: Active
LambdaExecutionRole:
Description: Creating service role in IAM for AWS Lambda
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Sub: ${ProjectId}-execution
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
PolicyName: Lamda addtional access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sns:Subscribe
- sns:Publish
- sns:CreateTopic
- logs:PutLogEvents
- logs:CreateLogStream
- logs:CreateLogGroup
Resource: '*'
ManagedPolicyArns:
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole'
LambdaFunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${ProjectId}'
RetentionInDays: 60
Policies code block isn't indented far enough

SAM give access to Cognito

I want to be able to call cognito functions through boto3 from my Lambda function in Python environment. What's the best way to give this type of access? I've done the following yaml but not sure if that's the best practice or I'm making the template longer.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
Policies:
- AWSLambdaExecute # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- cognito-idp:ListUsers
Resource: 'arn:aws:cognito-idp:us-east-2:****:*****'
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
I'm talking about the "Policies", is my template up to the standards? or is there a shortcut I can take?

Can i add a codecommit trigger to my lambda function via CloudFormation

Im writing a lambda function that i want to be triggered by somebody updating the master branch of a repo. The repo already exists on the account.
Is there a way in cloudformation that i can add the trigger to the lambda function? I guess at a snip i could cretae some cloudwatch rule to trigger the lambda, but would rather keep it all inside the lambda.
Thanks
R
If you are using AWS serverless transform then you can self contain it within the lambda. Although the transform generates the cloudwatch rule and the lambda permission, so it's basically the same you mentioned.
nevertheless here's an example to do what you want
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Pipeline which triggers lambda for codecommit changes
Parameters:
BranchName:
Default: master
Description: The GIT branch
Type: String
RepositoryName:
Description: The GIT repository
Type: String
StackOwner:
Description: The stack owner
Type: String
Resources:
BasicLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: logs:*
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action: '*'
Resource: '*'
PipelineTriggerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/trigger
Handler: codetrigger.handler
MemorySize: 256
Role: !GetAtt BasicLambdaRole.Arn
Runtime: python3.6
Timeout: 900
Environment:
Variables:
TestVariable: "TestValue"
Events:
CodeCommitPushEvent:
Type: CloudWatchEvent
Properties:
Pattern:
source:
- aws.codecommit
resources:
- !Sub 'arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${RepositoryName}'
detail:
event:
- referenceCreated
- referenceUpdated
repositoryName:
- !Ref RepositoryName
referenceName:
- !Ref BranchName
Tags:
'owner': !Ref StackOwner
'task': !Ref RepositoryName
Obviously, specify the lambda role better and not give all permissions as provided in the example.

AWS Lambda scheduled with CodeStar: SyncResources com.amazon.coral.service.InternalFailure

I'm trying to deploy scheduled AWS Lambda function using CodeStar.
I have started from the webserver template of CodeStart and I have modified the template.yml in order to use the scheduled events.
AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar
Parameters:
ProjectId:
Type: String
Description: AWS CodeStar projectID used to associate new resources to team members
Resources:
HelloWorld:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: nodejs6.10
Role:
Fn::ImportValue:
!Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region','LambdaTrustRole']]
Events:
MyEvent:
Type: Schedule
Properties:
Schedule: rate(5 minutes)
I had attached the Policie CloudWatchEventsFullAccess to the Role CodeStarWorker-xxxxx-CloudFormation in order to allow the events:PutRule.
When I launch the CodePipeline I end getting an error in the deploy stage (CloudFormation) saying:
CREATE_FAILED AWS::CodeStar::SyncResources SyncResources1493352569577 com.amazon.coral.service.InternalFailure
No resources in your CloudFormation template are related to CodeStar so I think removing the 'AWS::CodeStar' line one the top should fix it.

Resources