AWS SAM problem with deploy Severless Api with auth - amazon-web-services

I think i do something wrong in my .yaml file. Probably its problem with AWS::Serverless::Api.
Before i add it everything was fine. I just want to configure api with authorization. I also want to know how to configure which request will be authorized.
I had this error after deploy command:
Initiating deployment
Waiting for changeset to be created..
Error: Failed to create changeset for the stack: SampleImagesApi, ex: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Unresolved resource dependencies [ServerlessRestApi] in the Outputs block of the template
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
python3.8
Sample SAM Template for SampleAwsImagesApi
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
MyApi:
Type: AWS::Serverless::Api
DependsOn:
Properties:
StageName: prod
Auth:
DefaultAuthorizer: MyLambdaTokenAuth
Authorizers:
MyLambdaTokenAuth:
FunctionPayloadType: REQUEST
FunctionArn: !GetAtt AuthFunction.Arn
Identity:
Headers: Authorization # OPTIONAL; Default: 'Authorization'
ValidationExpression: Bearer *
ReauthorizeEvery: 20 # OPTIONAL; Service Default: 300
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:
PackageType: Image
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
RestApiId:
Ref: MyApi
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world
DockerTag: python3.8-v1
HelloWorld2Function:
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:
PackageType: Image
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: /hello2
Method: get
RestApiId:
Ref: MyApi
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world2
DockerTag: python3.8-v1
LoginFunction:
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:
PackageType: Image
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: /login
Method: post
RestApiId:
Ref: MyApi
Metadata:
Dockerfile: Dockerfile
DockerContext: ./login
DockerTag: python3.8-v1
AuthFunction:
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:
PackageType: Image
Metadata:
Dockerfile: Dockerfile
DockerContext: ./auth
DockerTag: python3.8-v1
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

using cfn-lint CLI to validate your template can help you debug it - https://github.com/aws-cloudformation/cfn-python-lint
I tried it locally and there's a couple of errors going on:
E0000 Null value at line 16 column 15
template-2.yaml:16:15
E0001 Error transforming template: Resource with id [AuthFunction] is invalid. 'ImageUri' must be set.
template.yaml:1:1
E0001 Error transforming template: Resource with id [HelloWorld2Function] is invalid. 'ImageUri' must be set.
template.yaml:1:1
E0001 Error transforming template: Resource with id [HelloWorldFunction] is invalid. 'ImageUri' must be set.
template.yaml:1:1
E0001 Error transforming template: Resource with id [LoginFunction] is invalid. 'ImageUri' must be set.
template.yaml:1:1

Related

YAML file not deploying - Invalid value for '--parameter-overrides'

I have a very simple YAML file to build an API Gateway and a lambda function. If I use straight cloud formation commands, it works fine.
If I try to run it with sam, the build takes forever - 10 minutes or so - but does finally conclude. However, the deploy does not work.
Here is the YAML file
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Storygraf backend API
Globals:
Function:
Timeout: 3
Resources:
ExpressApi:
Type: AWS::Serverless::Api
Properties:
StageName: dev
ExpressLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
CodeUri: ./
Handler: lambda.handler
MemorySize: 512
Runtime: nodejs14.x
Timeout: 30
Events:
ProxyApiRoot:
Type: Api
Properties:
RestApiId: !Ref ExpressApi
Path: /
Method: ANY
cors: true
ProxyApiGreedy:
Type: Api
Properties:
RestApiId: !Ref ExpressApi
Path: /{proxy+}
Method: ANY
cors: true
SAM Commands
sam build
sam deploy --guided
Error
Error: Invalid value for '--parameter-overrides': is not in valid format. It must look something like 'ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro' or 'KeyPairName=MyKey InstanceType=t1.micro'
I have no idea what this error means.

Unresolved resource dependencies [BasicAWSApiGateway] in the Outputs block of the template

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
readOrdersFunction:
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:
FunctionName: readOrders
CodeUri: read_order/
Handler: read_orders.lambda_handler
Runtime: python3.8
Events:
ReadOrdersApi:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
RestApiId: !Ref BasicAWSApiGateway
Path: /read
Method: get
BasicAWSApiGateway:
Type: AWS::Serverless::Api
Properties:
Name: Basic AWS Api Gateway
StageName: Staging
Outputs:
BasicAWSApiGateway:
Description: 'API Gateway endpoint URL for Staging stage for Hello World function'
Value: !Sub 'https://${BasicAWSApiGateway}.execute-api.${AWS::Region}.amazonaws.com/Staging/read/'
BasicAWSApiGatewayRestApiId:
Description: 'API Gateway ARN for Basic AWS API Gateway'
Value: !Ref BasicAWSApiGateway
Export:
Name: BasicAWSApiGateway-RestApiId
BasicAWSApiGatewayRootResourceId:
Value: !GetAtt BasicAWSApiGateway.RootResourceId
Export:
Name: BasicAWSApiGateway-RootResourceId
Indentation/whitespace is significant in YAML. BasicAWSApiGateway is indented too far

AWS SAM Deploy error - Validation Error | CreateChangeSet Operation Error

I get the following error upon attempting to sam deploy --guided my lambda application.
Error: Failed to create changeset for the stack: {stack-name}, An error occurred (ValidationError) when calling the CreateChangeSet operation: Stack:arn:aws:cloudformation:ap-southeast-2:014009325916:stack/{stack-name}/f2212bf0-bb41-11ea-8ef3-0aa7af0536b6 is in ROLLBACK_COMPLETE state and can not be updated.
Some further context into this issue is that all of my lambda functions do not have authorization defined. Not sure if that is related but I'm stating it in the case that it is.
I frankly have no idea how to go about this issue. Any help is appreciated.
===
Context: Building an automated trading system
Request for Cloudformation Template:
yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A tradingview alert wrapper that interprets alerts and makes trades according to them.
Globals:
Function:
# CodeUri: function/.
# Runtime: python3.8
# Policies:
# - AWSLambdaFullAccess
# Tracing: Active
# Timeout: 30
Environment:
Variables:
APIKEY: ""
SECRETKEY: ""
Resources:
tradeFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.trade
Description: The primary execution function
CodeUri: function/.
Runtime: python3.8
Policies:
- AWSLambdaFullAccess
Tracing: Active
Timeout: 60
Events:
inputResponse:
Type: Api
Auth:
ApiKeyRequired: false
Authorizer: NONE
Properties:
Path: /trade
Method: post
printAccountBalanceFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: function/.
Runtime: python3.8
Policies:
- AWSLambdaFullAccess
Tracing: Active
Timeout: 30
Handler: app.print_account_balance
Description: Returns account balance over time or trade
Events:
inputResponse:
Type: Api
Properties:
Path: /print_account_balance
Method: get
startTradesFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: function/.
Runtime: python3.8
Policies:
- AWSLambdaFullAccess
Tracing: Active
Timeout: 30
Handler: app.start_trades
Description: Resets trade log for a fresh start
Events:
inputResponse:
Type: Api
Properties:
Path: /start_trades
Method: get
retrieveTradeLogFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: function/.
Runtime: python3.8
Policies:
- AWSLambdaFullAccess
Tracing: Active
Timeout: 30
Handler: app.retrieve_trade_log
Description: Return all the trade logs in the dyanamoDB database
Events:
inputResponse:
Type: Api
Properties:
Path: /retrieve_trade_log
Method: get
The error is encountered to my understanding when one does an initial deployment and that initial deployment fails. As a result of this, something breaks and the deployment service can not execute successfully. To fix this issue, simple delete the aws cloudformation stack and redeploy.
One can use the following command to delete:
aws cloudformation delete-stack --stack-name <insert stack-name>
Reference
Might need to run sam build first so your resources can get the latest changes

How to configure `TracingConfig` on cloudformation?

I want to enable x-ray for my lambda function and below is the template file:
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.lambdaHandler
Runtime: nodejs8.10
TracingConfig:
Mode: Active
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: post
I got below error when I deploy via sam deploy command:
Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [HelloWorldFunction] is invalid. property TracingConfig not defined for resource of type AWS::Serverless::Function
It shows the TracingConfig is not defined. What is the correct way to configure that for my lambda?
Based on this docs, it should be Tracing only. So the correct one should be as below
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.lambdaHandler
Runtime: nodejs8.10
Tracing: Active
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: post

Pass a referance to API Gateway to Lambda

I'm using the Serverless framework and one of my lambda functions needs to know the API gateway id. I tried setting an envierment varable like the following.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs6.10
Environment:
Variables:
API_GATEWAY: !Ref ApiGatewayRestApi
Resources:
Test:
Type: AWS::Serverless::Function
Properties:
Handler: LeadLambda.test
CodeUri: ./Lead
Events:
GetResource:
Type: Api
Properties:
Path: /
Method: get
But when I try and deploy I get a circular dependency error.
Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Circular dependency between resources: [TestGetResourcePermissionProd, ServerlessRestApi, Test, TestGetResourcePermissionTest, ServerlessRestApiDeploymentb5240aa4ca, ServerlessRestApiProdStage]
The solution I ended up using was to hard code the integration uri in the API instead of referencing the Lambda.
Globals:
Function:
Runtime: nodejs6.10
Environment:
Variables:
API: !Sub https://${Api}.execute-api.${AWS::Region}.amazonaws.com/prod
Resources:
Entry:
Type: AWS::Serverless::Function
Properties:
FunctionName: prompt-stack-Entry
Handler: LeadLambda.entry
CodeUri: s3://ddg-prompt/LeadLambda.zip
Role: !GetAtt LeadRole.Arn
Events:
GetResource:
Type: Api
Properties:
Path: /lead
Method: POST
RestApiId: !Ref Api
Api:
Type: AWS::Serverless::Api
Properties:
StageName: prod
DefinitionBody:
swagger: 2.0
info:
title:
Ref: AWS::StackName
paths:
/lead:
post:
responses:
'200':
description: Successful operation
responseTemplates:
application/json: ""
x-amazon-apigateway-integration:
httpMethod: POST
type: aws
uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:prompt-stack-Entry/invocations
responses:
default:
statusCode: '200'
responseTemplates:
application/json: ''