Tag Archives: template.yml

Overriding Global Variables – AWS SAM Local

Hi everyone,

Today I’ve added local overrides to the global variables in my template.yml file. This was pretty finicky – a lot of conflicting suggestions out there unfortunately. These are the settings that ended up working for me.

local-env-var-overrides.json:

{
    "Parameters": {
        "RDS_HOSTNAME_TEST": "192.168.0.31"
    }
}

template.yaml

Globals:
  Function:
    Environment:
      Variables:        
        RDS_HOSTNAME_TEST:
          Type: String
          Default: 'DEFAULT'

aws sam local command:

sam local start-api --env-vars "local-env-var-overrides.json"

create.js

exports.createTrapHandler = async (event, context, callback) => {

	try {

        console.log("RDS_HOSTNAME_TEST: " + process.env.RDS_HOSTNAME_TEST)
        // Outputs: 192.168.0.31

This link ended up being pretty useful: https://www.npmjs.com/package/aws-sam-local

Advertisements

Cognito Auth with AWS SAM

Hi everyone,

I’ve spent today implementing Cognito with AWS SAM and it took quite a while to work out what needed to be done – unfortunately there’s a lot of conflicting doco out there. Posting a sample template just in case it’s able to help anyone else out.

The first thing to do is to explicitly define you rest API. By default AWS SAM will generate one with a default logical id of ServerlessRestApi. You’ll need to override this:

Resources:
  # See links for more info
  # Referencing cognito authorizer: https://github.com/awslabs/serverless-application-model/issues/512#issuecomment-411284092
  # Logical id is auto generated: https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  # Sample template.yml: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml
  MyCustomApi:
    Type: "AWS::Serverless::Api"
    Properties:
      StageName: Prod
      Auth: # We will eventually define other auth options here such as Usage Plans/Api Keys, AWS_IAM, and Resource Policies
        DefaultAuthorizer: MyCustomCognitoAuthorizer
        Authorizers:
          MyCustomCognitoAuthorizer:
            UserPoolArn: !GetAtt MyCustomCognitoUserPool.Arn # Can be a string, or array
            # Identity: # Optional
              # Header: ... # Optional; Default: Authorization
              # ValidationExpression: ...  # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?

You’ll also need to create a user pool and client:

# Creating a cognito user pool - https://github.com/awslabs/serverless-application-model/blob/master/examples/2016-10-31/api_cognito_auth/template.yaml
  MyCustomCognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Ref CognitoUserPoolName
      # LambdaConfig:
        # PreSignUp: !GetAtt PreSignupLambdaFunction.Arn
      Policies:
        PasswordPolicy:
          MinimumLength: 8
      UsernameAttributes:
        - email
      Schema:
        - AttributeDataType: String
          Name: email
          Required: false

  MyCustomCognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref MyCustomCognitoUserPool
      ClientName: !Ref CognitoUserPoolClientName
      GenerateSecret: false

You then add the api id and the auth attribute to each of your function properties. If you’ve used the default authorizer property when defining the associated api you can override it by using authorizer: none.

GetBreedFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: breed.getBreedHandler
      Policies: arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess
      Runtime: nodejs8.10
      Environment:
        Variables:
          TABLE_CAT_BREED: !Ref CatBreedTable
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /breed/{breedId}
            Method: get
            RestApiId: !Ref MyCustomCustomApi
            Auth:
              Authorizer: NONE

Hopefully that’s able to help you out. If you run into any trouble I found the following link pretty useful: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml

AWS SAM not re-creating DynamoDb Table that was manually deleted – CodeStar

Hi everyone,

I ran into a bit of an issue after deleting a DynamoDb table via the AWS Console that had been created via CloudFormation (using AWS SAM). After deleting it I had expected it to be re-created automatically on the next deploy. Unfortunately this didn’t happen.

I came across the following AWS article that does a pretty good job of summarising the issue: https://aws.amazon.com/premiumsupport/knowledge-center/failing-stack-updates-deleted/

To fix it, I removed all references to the table from my template.yml file (this includes the table definition and any !Ref tags). After pushing this changeset I returned all of the references and re-pushed.

Let me know if you have any issues!

Cheers,
Chris

Error: Invalid value for “–parameter-overrides”: ParameterKey=TABLE_NAME,ParameterValue=CatBreeds is not in valid format. It must look something like ‘ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro’ – AWS SAM CLI

Hi everyone,

I ran into the following error while using the AWS SAM Cli:

Error: Invalid value for "--parameter-overrides": ParameterKey=PURPLE_FROG,ParameterValue=CatBreeds is not in valid format. It must look something like 'ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro'

This is the command I was running:

sam local start-api --parameter-overrides "ParameterKey=PURPLE_FROG,ParameterValue=CatBreeds"

The error message is unfortunately very misleading. After a fair bit of testing I found that the cause is actually the underscore in the parameter key and has nothing to do with the command format. Renaming all of the parameters to something like “PURPLEFROG” works.

Cheers,
Chris

AWS SAM Cheat Sheet/Quick Reference

Hi everyone,

This will just be a living cheat sheet or quick reference for using AWS SAM with nodejs. I’ll add to it as I find things that are useful or I might need again.

General AWS SAM Info:

Description Example More
Validate template sam validate
Start AWS Sam Locally https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html
Access config variable in Lambda const CAT_BREED_TABLE = process.env.CAT_BREED_TABLE; https://stackoverflow.com/a/48491845/522859
Dynamically reference another resource in template.yml CAT_BREED_TABLE: !Ref DynamoDbCatBreedTable https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html

Dynamo DB Local Info:

Description Example More
Create table aws dynamodb create-table –table-name CatBreeds –attribute-definitions AttributeName=CatBreedId,AttributeType=S –key-schema AttributeName=CatBreedId,KeyType=HASH –provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
–endpoint-url http://192.168.0.31:8000
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.CLI.html
List Tables aws dynamodb list-tables –endpoint-url http://192.168.0.31:8000 https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.CLI.html
List All Rows in Table aws dynamodb scan –table-name PestinatorTable –endpoint-url http://192.168.0.31:8000 https://stackoverflow.com/a/52236600/522859

Node.js Info:

Description Example More
Run tests npm test