genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

AWS lambda with serverless framework #143

Open genkio opened 7 years ago

genkio commented 7 years ago

study notes taken from the packtpub Learning AWS Lambda course.

Create and deploy AWS Lambda, API Gateway via Serverless

# first add your AWS IAM user credential
$ vim ~/.aws/credentials

# install serverless framework
$ npm i -g serverless

$ mkdir hello-serverless && cd hello-serverless

# generate your first service with name simple from template aws-nodejs
$ sls create --t aws-nodejs --n simple

# update serverless.yml
provider:
  name: aws
  runtime: nodejs4.3
  stage: dev
  region: us-east-1

# deploy the Lambda function hello
$ sls deploy -f hello

# test the deployed function
$ sls invoke -f hello

# or test the function locally
$ sls invoke local -f hello

# update serverless.yml to prepare deploy our API gateway
functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

# deploy again
$ sls deploy -f hello

# now you'll be able to invoke your lambda function via API gateway

Testing and debugging Lambda functions

To retrieve console logs from our app when invoking remote Lambda function via Serverless

$ sls logs -f hello

All logs can be found in AWS Lambda dashboard -> your function monitoring page -> view logs in CloudWatch

Invoke Lambda function with event parameters with serverless

# event.json
{
  "body": "{\"article_id\":\"1\"}"
}

$ sls invoke -f readArticle -p ./event.json

Create AWS DynamoDB table with Serverless

# update serverless.yml
resources:
 Resources:
   NewResource:
     Type: AWS::DynamoDB::Table
     Properties:
      TableName: BlogTable
      AttributeDefinitions:
        - AttributeName: article_id
          AttributeType: S
      KeySchema:
        - AttributeName: article_id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1

$ sls deploy

Enable Lambda function to interact with DynamoDB

# update serverless.yml
provider:
  name: aws
  runtime: nodejs4.3
  iamRoleStatements: # permissions for all of your functions can be set here
    - Effect: Allow
      Action: # Gives permission to DynamoDB tables in a specific region
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-1:*:*"

$ sls deploy