Showing posts with label Serverless. Show all posts
Showing posts with label Serverless. Show all posts

Wednesday, 25 September 2019

Cognito and API

exports.handler = (event, context, callback) => {
    const token = event.authorizationToken;
    //Use token
    if (token == 'allow') {
        const policy = genPolicy('allow', event.methodArn);
        const principalId = 'aflaf78fd7afalnv';
        const context = {
            simpleAuth: true
        };
        const response = {
            principalId: principalId,
            policyDocument: policy,
            context: context
        };
        callback(null, response);
    } else if (token == 'deny') {
        const policy = genPolicy('deny', event.methodArn);
        const principalId = 'aflaf78fd7afalnv';
        const context = {
        simpleAuth: true
        };
        const response = {
            principalId: principalId,
            policyDocument: policy,
            context: context
        };
        callback(null, response);
    } else {
       callback('Unauthorized');
    }
 
};

function genPolicy(effect, resource) {
    const policy = {};
    policy.Version = '2012-10-17';
    policy.Statement = [];
    const stmt = {};
    stmt.Action = 'execute-api:Invoke';
    stmt.Effect = effect;
    stmt.Resource = resource;
    policy.Statement.push(stmt);
    return policy;
}

------------------------------------------------------------------------------------
var xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');
xhr.onreadystatechange = function(event) {
  console.log(JSON.parse(event.target.response));
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'allow');
xhr.send(JSON.stringify({age: 29, height: 73, income: 1900}));

-------------------------------------------------------------------------------------------------------

#set($inputRoot = $input.path('$'))
{
  "age" : "$inputRoot.age",
  "height": "$inputRoot.height",
  "income": "$inputRoot.income",
  "userId": "$context.authorizer.principalId"
}

----------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const params = {
        Item: {
            "UserId": {
                S: event.userId
            },
            "Age": {
                N: event.age
            },
            "Height": {
                N: event.height
            },
            "Income": {
                N: event.income
            }
        },
        TableName: "compare-yourself"
    };
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);
            callback(null, data);
        }
    });
};


---------------------------------------------------------------------------------------



Tuesday, 24 September 2019

AWS Serverless APIs & Apps


exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, {message: 'Hi, I\m Raj'});
};

-------------------------------------------------------------------------------------------------------------------

https://codepen.io/pen/?editors=0010

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');
xhr.onreadystatechange = function(event) {
  console.log(event.target.response);
}
xhr.send();

---------------------------------------------------------------------------------------------------------------------

exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, event);
};

-----------------------------------------------------------------------------------------------------------

{
    "name": "Raj Kumar Gupta",
    "age": 28
}

------------------------------------------------------------------------------------------


exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, {headers: {'Control-Access-Allow-Origin': '*'}});
};

---------------------------------------------------------------------------------------------------------

exports.handler = (event, context, callback) => {
    console.log(event);
    callback(null, {headers: {'Control-Access-Allow-Origin': '*'}});
};

----------------------------------------------------------------------------------------------------


exports.handler = (event, context, callback) => {
    console.log(event);
    const age = event.personData.age;
    callback(null, age * 2);
};



------------------------------------------------------------------------------------------------------------------


{
    "personData": {
        "name": "Raj Kumar Gupta",
        "age": 28
    }

}

-----------------------------------------------------------------------------------------------

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "CompareData",
  "type": "object",
  "properties": {
    "age": {"type": "integer"},
    "height": {"type": "integer"},
    "income": {"type": "integer"}
  },
  "required": ["age", "height", "income"]
}

--------------------------------------------------------------------------------------

{
    "age": 28,
    "height": 72,
    "income": 2500
}

-------------------------------------------------------------------------------------------------------

exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, 'Deleted!');
};

-----------------------------------------------------------------------------------------------------------------


exports.handler = (event, context, callback) => {
    const type = event.type;
    if (type == 'all') {
        callback(null, 'All the data');
    } else if (type == 'single') {
        callback(null, 'Just my data');
    } else {
        callback(null, 'Hello from Lambda');
    } 
};

------------------------------------------------------------------------------------------------------

{
    "type": "$input.params('type')"


-----------------------------------------------------------


var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');

xhr.onreadystatechange = function(event) {

  console.log(event.target.response);

}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({age: 28, height: 72, income: 2500}));


-------------------------------------------------------------------------------------------------------------

var xhr = new XMLHttpRequest();

xhr.open('DELETE', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');

xhr.onreadystatechange = function(event) {

  console.log(event.target.response);

}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();


---------------------------------------------------------------------------------------------------------------

var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/all');

xhr.onreadystatechange = function(event) {

  console.log(event.target.response);

}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();

Data Storage with DynamoDB by Raj Gupta

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const params = {
        Item: {
            "UserId": {
                S: "gakhhhih"
            },
            "Age": {
                N: "28"
            },
            "Income": {
                N: "2500"
            }
        },
        TableName: "compare-yourself"
    };
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);
            callback(null, data);
        }
    });
};

---------------------------------------------------------------------------------------------------------

#set($inputRoot = $input.path('$'))
{
  "age" : "$inputRoot.age",
  "height": "$inputRoot.height",
  "income": "$inputRoot.income"
}


-----------------------------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const params = {
        Item: {
            "UserId": {
                S: "user_" + Math.random()
            },
            "Age": {
                N: event.age
            },
            "Height": {
                N: event.height
            },
            "Income": {
                N: event.income
            }
        },
        TableName: "compare-yourself"
    };
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);
            callback(null, data);
        }
    });
};

------------------------------------------------------------------------------------------------------------------------

var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');

xhr.onreadystatechange = function(event) {

  console.log(event.target.response);

}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({age: 26, height: 71, income: 2100}));

----------------------------------------------------------------------------------------------------

{
  "type": "all",
  "key2": "value2",
  "key3": "value3"
}

--------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const type = event.type;
    if (type == 'all') {
        const params = {
            TableName: 'compare-yourself'
        };
        dynamodb.scan(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                callback(null, data);
            }
        });
    } else if (type == 'single') {
        callback(null, 'Just my data');
    } else {
        callback(null, 'Hello from Lambda');
    }   
};


-------------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const type = event.type;
    if (type == 'all') {
        const params = {
            TableName: 'compare-yourself'
        };
        dynamodb.scan(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                const items = data.Items.map(
                    (dataField) => {
                        return {age: +dataField.Age.N, height: +dataField.Height.N, income: +dataField.Income.N};
                    }
                );
                callback(null, items);
            }
        });
    } else if (type == 'single') {
        callback(null, 'Just my data');
    } else {
        callback(null, 'Hello from Lambda');
    }   
};


-------------------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const type = event.type;
    if (type == 'all') {
        const params = {
            TableName: 'compare-yourself'
        };
        dynamodb.scan(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                const items = data.Items.map(
                    (dataField) => {
                        return {age: +dataField.Age.N, height: +dataField.Height.N, income: +dataField.Income.N};
                    }
                );
                callback(null, items);
            }
        });
    } else if (type == 'single') {
        const params = {
            Key: {
                "UserId": {
                    S: "gakhhhih"
                }
            },
            TableName: "compare-yourself"
        };
        dynamodb.getItem(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                callback(null, data);
            }
         
        });
     
    } else {
        callback('Something went to wrong');
    } 
};

------------------------------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const type = event.type;
    if (type == 'all') {
        const params = {
            TableName: 'compare-yourself'
        };
        dynamodb.scan(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                const items = data.Items.map(
                    (dataField) => {
                        return {age: +dataField.Age.N, height: +dataField.Height.N, income: +dataField.Income.N};
                    }
                );
                callback(null, items);
            }
        });
    } else if (type == 'single') {
        const params = {
            Key: {
                "UserId": {
                    S: "gakhhhih"
                }
            },
            TableName: "compare-yourself"
        };
        dynamodb.getItem(params, function(err, data) {
            if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log(data);
                callback(null, {age: +data.Item.Age.N, income: +data.Item.Income.N});
            }
           
        });
        
    } else {
        callback('Something went to wrong');
    }   
};

-------------------------------------------------------------------------------------------------------------------

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/single');
xhr.onreadystatechange = function(event) {
  console.log(JSON.parse(event.target.response));
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();

---------------------------------------------------------------------------------------------------------

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-1', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const params = {
        Key: {
            "UserId": {
                S: "gakhhhih"
            }
        },
        TableName: "compare-yourself"
    };
    dynamodb.deleteItem(params, function (err, data) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);
            callback(null, data);
        }
    });
 
};

-------------------------------------------------------------------------------------------------------

var xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://ktl8ycz4w8.execute-api.us-east-1.amazonaws.com/dev/compare-yourself');
xhr.onreadystatechange = function(event) {
  console.log(JSON.parse(event.target.response));
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();


------------------------------------------------------------------------------------------------------------

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "CompareData",
  "type": "array",
  "items": {
        "type": "object",
        "properties": {
        "age": {"type": "integer"},
        "height": {"type": "integer"},
        "income": {"type": "integer"}
  },
  "required": ["age", "height", "income"]
  }
}

--------------------------------------------------------------------------------------------



Tuesday, 17 September 2019

Serverless - Passing input through API Gateway to your Lambda Functions by Raj Gupta

we create a GET method on a resource specified by a sequence of path parameters to call the backend Lambda function. The path parameter values specify the input data to the Lambda function


[root@ip-172-31-82-149 ~]# ls amazing-api anaconda-ks.cfg original-ks.cfg [root@ip-172-31-82-149 ~]# cd amazing-api/ [root@ip-172-31-82-149 amazing-api]# ls handler.py serverless.yml [root@ip-172-31-82-149 amazing-api]# export AWS_ACCESS_KEY_ID=AKIAWSYHFCM3Y6ZLJWN6 [root@ip-172-31-82-149 amazing-api]# export AWS_SECRET_ACCESS_KEY=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 [root@ip-172-31-82-149 amazing-api]# serverless deploy Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless: Creating Stack... Serverless: Checking Stack create progress... ..... Serverless: Stack create finished... Serverless: Uploading CloudFormation file to S3... Serverless: Uploading artifacts... Serverless: Uploading service amazing-api.zip file to S3 (314 B)... Serverless: Validating template... Serverless: Updating Stack... Serverless: Checking Stack update progress... ............................... Serverless: Stack update finished... Service Information service: amazing-api stage: dev region: us-east-1 stack: amazing-api-dev resources: 10 api keys: None endpoints: GET - https://da3w2i5gj0.execute-api.us-east-1.amazonaws.com/dev/results functions: hello: amazing-api-dev-hello layers: None Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing. [root@ip-172-31-82-149 amazing-api]#

[root@ip-172-31-82-149 amazing-api]# vi handler.py [root@ip-172-31-82-149 amazing-api]# cat handler.py import json def hello(event, context): if event['httpMethod']=='GET' and event['queryStringParameters']['query']: body = { "message": 'Your Query is' +event['queryStringParameters']['query'] } response = { "statusCode": 200, "body": json.dumps(body) } return response [root@ip-172-31-82-149 amazing-api]#serverless deploy

https://da3w2i5gj0.execute-api.us-east-1.amazonaws.com/dev/results?query=india

Enter this in URL query=india

Now to use post method do the below changes

[root@ip-172-31-82-149 amazing-api]# vi serverless.yml

functions: hello: handler: handler.hello events: - http: path: results method: get - http: path: query method: post

[root@ip-172-31-82-149 amazing-api]# vi handler.py

[root@ip-172-31-82-149 amazing-api]# cat handler.py
import json


def hello(event, context):

    if event['httpMethod']=='GET' and event['queryStringParameters']['query']:
    body = {
        "message": 'Your Query is' +event['queryStringParameters']['query']
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    if event['httpMethod']=='POST' and event['body']:
    body = {
        "message": 'received your body text', 'msgBody':event['body']
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }


    return response
[root@ip-172-31-82-149 amazing-api]#serverless deploy


curl -d '{"Country":"India"} -H "Content-Type: application/json" -x POST https://da3w2i5gj0.execute-api.us-east-1.amazonaws.com/dev/query









Monday, 16 September 2019

Serverless - Integrating With API Gateway with Lambda Functions by Raj Gupta

In this section, we show how to create and test an API with Lambda integration using the API Gateway console. With the Lambda proxy integration, when a client submits an API request, API Gateway passes to the integrated Lambda function the raw request as-is.

[root@ip-172-31-82-149 amazing-api]# sls invoke -f hello { "body": "{\"input\": {}, \"message\": \"Welcome to Raj by serverless\"}", "statusCode": 200 } [root@ip-172-31-82-149 amazing-api]#

[root@ip-172-31-82-149 amazing-api]# cat serverless.yml

functions: hello: handler: handler.hello events: - http: path: results method: get

[root@ip-172-31-82-149 amazing-api]# cat handler.py

import json def hello(event, context): if event['httpMethod']=='GET': body = { "message": "Welcome to Raj by serverless", "input": event } response = { "statusCode": 200, "body": json.dumps(body) } return response



[root@ip-172-31-82-149 amazing-api]# export AWS_ACCESS_KEY_ID=AKIAWSYHFCM3Y6ZLJWN6
[root@ip-172-31-82-149 amazing-api]# export AWS_SECRET_ACCESS_KEY=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
[root@ip-172-31-82-149 amazing-api]# serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service amazing-api.zip file to S3 (432 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
........................
Serverless: Stack update finished...
Service Information
service: amazing-api
stage: dev
region: us-east-1
stack: amazing-api-dev
resources: 10
api keys:
  None
endpoints:
  GET - https://dkoi2da9zk.execute-api.us-east-1.amazonaws.com/dev/results
functions:
  hello: amazing-api-dev-hello
layers:
  None
Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.
[root@ip-172-31-82-149 amazing-api]#


Now if access the api gateway URL https://dkoi2da9zk.execute-api.us-east-1.amazonaws.com/dev/results


Create first project using boilerplate "aws-python" by Raj Gupta


# Create project directory $ mkdir amazing-api # Create project using boilerplate $ sls create --template aws-python Modify the service as required $ edit `serverless.yml` file Modify function text $ edit `handler.py` file

# Deploy function $ sls deploy # Invoke remote function $ sls invoke --function hello # Invoke function locally $ sls invoke local --function hello

--------------------------------------------------------------------------------------------------------




----------------------------------------------------------------------------------------------------------------

[root@ip-172-31-82-149 ~]# mkdir amazing-api [root@ip-172-31-82-149 ~]# ls amazing-api anaconda-ks.cfg original-ks.cfg [root@ip-172-31-82-149 ~]# cd amazing-api/ [root@ip-172-31-82-149 amazing-api]# ls [root@ip-172-31-82-149 amazing-api]# sls create --template aws-python Serverless: Generating boilerplate... _______ __ | _ .-----.----.--.--.-----.----| .-----.-----.-----. | |___| -__| _| | | -__| _| | -__|__ --|__ --| |____ |_____|__| \___/|_____|__| |__|_____|_____|_____| | | | The Serverless Application Framework | | serverless.com, v1.52.0 -------' Serverless: Successfully generated boilerplate for template: "aws-python" Serverless: NOTE: Please update the "service" property in serverless.yml with your service name [root@ip-172-31-82-149 amazing-api]# ls handler.py serverless.yml [root@ip-172-31-82-149 amazing-api]# cat handler.py import json def hello(event, context): body = { "message": "Go Serverless v1.0! Your function executed successfully!", "input": event } response = { "statusCode": 200, "body": json.dumps(body) } return response # Use this code if you don't use the http event with the LAMBDA-PROXY # integration """ return { "message": "Go Serverless v1.0! Your function executed successfully!", "event": event } """ [root@ip-172-31-82-149 amazing-api]# cat serverless.yml # Welcome to Serverless! # # This file is the main config file for your service. # It's very minimal at this point and uses default values. # You can always add more config options for more control. # We've included some commented out config examples here. # Just uncomment any of them to get that config option. # # For full config options, check the docs: # docs.serverless.com # # Happy Coding! service: amazing-api # app and org for use with dashboard.serverless.com #app: your-app-name #org: your-org-name # You can pin your service to only deploy with a specific Serverless version # Check out our docs for more details # frameworkVersion: "=X.X.X" provider: name: aws runtime: python2.7 # you can overwrite defaults here # stage: dev # region: us-east-1 # you can add statements to the Lambda function's IAM Role here # iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*" # you can define service wide environment variables here # environment: # variable1: value1 # you can add packaging information here #package: # include: # - include-me.py # - include-me-dir/** # exclude: # - exclude-me.py # - exclude-me-dir/** functions: hello: handler: handler.hello # The following are a few example events you can configure # NOTE: Please make sure to change your handler code to work with those events # Check the event documentation for details # events: # - http: # path: users/create # method: get # - websocket: $connect # - s3: ${env:BUCKET} # - schedule: rate(10 minutes) # - sns: greeter-topic # - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000 # - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx # - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx # - iot: # sql: "SELECT * FROM 'some_topic'" # - cloudwatchEvent: # event: # source: # - "aws.ec2" # detail-type: # - "EC2 Instance State-change Notification" # detail: # state: # - pending # - cloudwatchLog: '/aws/lambda/hello' # - cognitoUserPool: # pool: MyUserPool # trigger: PreSignUp # - alb: # listenerArn: arn:aws:elasticloadbalancing:us-east-1:XXXXXX:listener/app/my-load-balancer/50dc6c495c0c9188/ # priority: 1 # conditions: # host: example.com # path: /hello # Define function environment variables here # environment: # variable2: value2 # you can add CloudFormation resource templates here #resources: # Resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value" [root@ip-172-31-82-149 amazing-api]# ls handler.py serverless.yml [root@ip-172-31-82-149 amazing-api]# ve serverless.yml -bash: ve: command not found [root@ip-172-31-82-149 amazing-api]# vi serverless.yml [root@ip-172-31-82-149 amazing-api]# vi handler.py [root@ip-172-31-82-149 amazing-api]#



[root@ip-172-31-82-149 amazing-api]# sls deploy Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless Error --------------------------------------- AWS provider credentials not found. Learn how to set up AWS provider credentials in our docs here: <http://slss.io/aws-creds-setup>. Get Support -------------------------------------------- Docs: docs.serverless.com Bugs: github.com/serverless/serverless/issues Issues: forum.serverless.com Your Environment Information --------------------------- Operating System: linux Node Version: 10.14.1 Framework Version: 1.52.0 Plugin Version: 2.0.0 SDK Version: 2.1.1

[root@ip-172-31-82-149 amazing-api]# export AWS_ACCESS_KEY_ID=AKIAWSYHFCM3Y6ZLJWN6 [root@ip-172-31-82-149 amazing-api]# export AWS_SECRET_ACCESS_KEY=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 [root@ip-172-31-82-149 amazing-api]# serverless deploy Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless: Creating Stack... Serverless: Checking Stack create progress... ..... Serverless: Stack create finished... Serverless: Uploading CloudFormation file to S3... Serverless: Uploading artifacts... Serverless: Uploading service amazing-api.zip file to S3 (407 B)... Serverless: Validating template... Serverless: Updating Stack... Serverless: Checking Stack update progress... ................ Serverless: Stack update finished... Service Information service: amazing-api stage: dev region: us-east-1 stack: amazing-api-dev resources: 5 api keys: None endpoints: None functions: hello: amazing-api-dev-hello layers: None Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing. [root@ip-172-31-82-149 amazing-api]#

[root@ip-172-31-82-149 amazing-api]# sls invoke --function hello { "body": "{\"input\": {}, \"message\": \"Welcome to Raj by serverless\"}", "statusCode": 200 } [root@ip-172-31-82-149 amazing-api]#


How to install Serverless toolkit in RHEL 8 by Raj Gupta

Serverless is your toolkit for deploying and operating serverless architectures. Focus on your application, not your infrastructure. Build faster with serverless architectures: ------------------------------------------------------------------ Develop, test and deploy in a single environment, to any cloud provider. You don’t have to provision infrastructure or worry about scale. Serverless teams cut time to market in half.

--------------------------------------------------------------------------------------------------------------------------------
yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm yum -y install npm npm install -g serverless sls create --help



-----------------------------------------------------------------------------------------------------------------------


[root@ip-172-31-82-149 ~]# yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm Red Hat Update Infrastructure 3 Client Configuration Server 8 2.0 kB/s | 2.1 kB 00:01 Red Hat Enterprise Linux 8 for x86_64 - AppStream from RHUI (RPMs) 22 MB/s | 9.2 MB 00:00 Red Hat Enterprise Linux 8 for x86_64 - BaseOS from RHUI (RPMs) 18 MB/s | 7.3 MB 00:00 epel-release-latest-8.noarch.rpm 16 kB/s | 21 kB 00:01 Dependencies resolved. ======================================================================================================================================================================== Package Arch Version Repository Size ======================================================================================================================================================================== Installing: epel-release noarch 8-5.el8 @commandline 21 k Transaction Summary ======================================================================================================================================================================== Install 1 Package Total size: 21 k Installed size: 30 k Downloading Packages: Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transaction Preparing : 1/1 Installing : epel-release-8-5.el8.noarch 1/1 Running scriptlet: epel-release-8-5.el8.noarch 1/1 Verifying : epel-release-8-5.el8.noarch 1/1 Installed: epel-release-8-5.el8.noarch Complete! [root@ip-172-31-82-149 ~]# yum -y install npm Extra Packages for Enterprise Linux 8 - x86_64 536 kB/s | 1.3 MB 00:02 Dependencies resolved. ======================================================================================================================================================================== Package Arch Version Repository Size ======================================================================================================================================================================== Installing: npm x86_64 1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed rhel-8-appstream-rhui-rpms 3.6 M Installing dependencies: nodejs x86_64 1:10.14.1-1.module+el8+2632+6c5111ed rhel-8-appstream-rhui-rpms 8.6 M Enabling module streams: nodejs 10 Transaction Summary ======================================================================================================================================================================== Install 2 Packages Total download size: 12 M Installed size: 57 M Downloading Packages: (1/2): npm-6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64.rpm 13 MB/s | 3.6 MB 00:00 (2/2): nodejs-10.14.1-1.module+el8+2632+6c5111ed.x86_64.rpm 18 MB/s | 8.6 MB 00:00 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Total 8.1 MB/s | 12 MB 00:01 Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transaction Running scriptlet: npm-1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64 1/1 Preparing : 1/1 Installing : nodejs-1:10.14.1-1.module+el8+2632+6c5111ed.x86_64 1/2 Installing : npm-1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64 2/2 Running scriptlet: npm-1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64 2/2 Verifying : npm-1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64 1/2 Verifying : nodejs-1:10.14.1-1.module+el8+2632+6c5111ed.x86_64 2/2 Installed: npm-1:6.4.1-1.10.14.1.1.module+el8+2632+6c5111ed.x86_64 nodejs-1:10.14.1-1.module+el8+2632+6c5111ed.x86_64 Complete! [root@ip-172-31-82-149 ~]# npm install -g serverless npm WARN deprecated superagent@3.8.3: Please note that v5.0.1+ of superagent removes User-Agent header by default, therefore you may need to add it yourself (e.g. GitHub blocks requests without a User-Agent header). This notice will go away with v5.0.2+ once it is released. /usr/bin/serverless -> /usr/lib/node_modules/serverless/bin/serverless.js /usr/bin/slss -> /usr/lib/node_modules/serverless/bin/serverless.js /usr/bin/sls -> /usr/lib/node_modules/serverless/bin/serverless.js > spawn-sync@1.0.15 postinstall /usr/lib/node_modules/serverless/node_modules/spawn-sync > node postinstall > serverless@1.52.0 postinstall /usr/lib/node_modules/serverless > node ./scripts/postinstall.js +--------------------------------------------------+ | | | Serverless Framework successfully installed! | | To start your first project, run “serverless”. | | | +--------------------------------------------------+ + serverless@1.52.0 added 542 packages from 348 contributors in 23.932s [root@ip-172-31-82-149 ~]# sls create --help Plugin: Create create ........................ Create new Serverless service --template / -t .................... Template for the service. Available templates: "aws-clojure-gradle", "aws-clojurescript-gradle", "aws-nodejs", "aws-nodejs-typescript", "aws-alexa-typescript", "aws-nodejs-ecma-script", "aws-python", "aws-python3", "aws-groovy-gradle", "aws-java-maven", "aws-java-gradle", "aws-kotlin-jvm-maven", "aws-kotlin-jvm-gradle", "aws-kotlin-nodejs-gradle", "aws-scala-sbt", "aws-csharp", "aws-fsharp", "aws-go", "aws-go-dep", "aws-go-mod", "aws-ruby", "aws-provided", "azure-nodejs", "cloudflare-workers", "cloudflare-workers-enterprise", "cloudflare-workers-rust", "fn-nodejs", "fn-go", "google-nodejs", "google-python", "google-go", "kubeless-python", "kubeless-nodejs", "openwhisk-java-maven", "openwhisk-nodejs", "openwhisk-php", "openwhisk-python", "openwhisk-ruby", "openwhisk-swift", "spotinst-nodejs", "spotinst-python", "spotinst-ruby", "spotinst-java8", "twilio-nodejs", "plugin" and "hello-world" --template-url / -u ................ Template URL for the service. Supports: GitHub, BitBucket --template-path .................... Template local path for the service. --path / -p ........................ The path where the service should be created (e.g. --path my-service) --name / -n ........................ Name for the service. Overwrites the default name of the created service. [root@ip-172-31-82-149 ~]#