How to use serverless for deploying code to AWS?

Serverless is a very useful tool for deploying your code to AWS. It automatically deploys your code to AWS. You just need to configure it properly for correct flow.

First to use serverless need to configure AWS. I have shown my blog. Please do the steps first. Please follow the below link for more info.

How to configure AWS CLI?
Firstly, we need to install the serverless to tour machine.
Prerequisite: NPM
npm install -g serverless
By entering this command node will install the serverless globally to your machine. Once it is installed please check by entering the following command.
sls
If it installed properly it will warn you that no current project showing for serverless.
After a successful installation, we need to make the serverless.yml file.
Here you can define your own rules. Here you can create the lambdas, s3 buckets any AWS service which supports the AWS cloud formation.
# This is your service name.
service: test-service 
provider:
  name: aws
  runtime: python3.7

  # you can overwrite defaults here
  stage: ${opt:stage,'dev'}
  region: ${opt:region, 'us-east-2'}
  timeout: 120
  memorySize: 2014

# you can add statements to the Lambda function's IAM Role here
  iamRoleStatements:
    - Effect: 'Allow'
      Action:
        - 's3:PutObject'
        - 's3:GetObject'
        - 'ses:SendEmail'
        - 'ses:SendRawEmail'
        - 'sqs:SendMessage'
        - 'sqs:GetQueueUrl'
      Resource: '*'

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true# This is how we can create lambda for perticular trigger.     functions:
  testlambda:
    handler: lamdas/test/test_lambda
    description: Test lambda
    timeout: 300
    events:
      - schedule:
          rate: rate(2 minutes)
          enabled: true# This is how we can create the s3 bucketresources:
  Resources:
    S3BucketTest:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: test-bucket
As shown above, it is your serverless.yml file. Here we have created the s3 bucket and lambda. serverless will automatically create the bucket in s3 and upload your code to s3. Here you can call your code using the lambdas.
After creating this file you can start deploying your code to AWS by following the below command.
serverless deploy -v
Here it starts deploying your code to AWS. It can take a while around 30 to 45 mins. As it is creating the dockers and upload your code it will take time after first time deploying your code in the second time it will not take much time.
In some cases, if your zip if above 10 MB it will fail to deploy your code. So, try to minimize your file size as low as possible.
Now after successful deployment, you can call your lambda directly by just the following code.
sls invoke -f testlambda -l
Here we have invoked our lambda function.
Bingo, we have deployed our code to AWS successfully.

1 comment:

Powered by Blogger.