1633074306
Hello! Today we will deploy a serverless infrastructure based on AWS Lambda for uploading images (and any other files) with private storage in an AWS S3 bucket. We will be using terraform scripts that are uploaded and available at my kompotkot/hatchery GitHub repository.
1655426640
Serverless M (or Serverless Modular) is a plugin for the serverless framework. This plugins helps you in managing multiple serverless projects with a single serverless.yml file. This plugin gives you a super charged CLI options that you can use to create new features, build them in a single file and deploy them all in parallel
Currently this plugin is tested for the below stack only
Make sure you have the serverless CLI installed
# Install serverless globally
$ npm install serverless -g
To start the serverless modular project locally you can either start with es5 or es6 templates or add it as a plugin
# Step 1. Download the template
$ sls create --template-url https://github.com/aa2kb/serverless-modular/tree/master/template/modular-es6 --path myModularService
# Step 2. Change directory
$ cd myModularService
# Step 3. Create a package.json file
$ npm init
# Step 3. Install dependencies
$ npm i serverless-modular serverless-webpack webpack --save-dev
# Step 1. Download the template
$ sls create --template-url https://github.com/aa2kb/serverless-modular/tree/master/template/modular-es5 --path myModularService
# Step 2. Change directory
$ cd myModularService
# Step 3. Create a package.json file
$ npm init
# Step 3. Install dependencies
$ npm i serverless-modular --save-dev
If you dont want to use the templates above you can just add in your existing project
plugins:
- serverless-modular
Now you are all done to start building your serverless modular functions
The serverless CLI can be accessed by
# Serverless Modular CLI
$ serverless modular
# shorthand
$ sls m
Serverless Modular CLI is based on 4 main commands
sls m init
sls m feature
sls m function
sls m build
sls m deploy
sls m init
The serverless init command helps in creating a basic .gitignore
that is useful for serverless modular.
The basic .gitignore
for serverless modular looks like this
#node_modules
node_modules
#sm main functions
sm.functions.yml
#serverless file generated by build
src/**/serverless.yml
#main serverless directories generated for sls deploy
.serverless
#feature serverless directories generated sls deploy
src/**/.serverless
#serverless logs file generated for main sls deploy
.sm.log
#serverless logs file generated for feature sls deploy
src/**/.sm.log
#Webpack config copied in each feature
src/**/webpack.config.js
The feature command helps in building new features for your project
This command comes with three options
--name: Specify the name you want for your feature
--remove: set value to true if you want to remove the feature
--basePath: Specify the basepath you want for your feature, this base path should be unique for all features. helps in running offline with offline plugin and for API Gateway
options | shortcut | required | values | default value |
---|---|---|---|---|
--name | -n | ✅ | string | N/A |
--remove | -r | ❎ | true, false | false |
--basePath | -p | ❎ | string | same as name |
Creating a basic feature
# Creating a jedi feature
$ sls m feature -n jedi
Creating a feature with different base path
# A feature with different base path
$ sls m feature -n jedi -p tatooine
Deleting a feature
# Anakin is going to delete the jedi feature
$ sls m feature -n jedi -r true
The function command helps in adding new function to a feature
This command comes with four options
--name: Specify the name you want for your function
--feature: Specify the name of the existing feature
--path: Specify the path for HTTP endpoint helps in running offline with offline plugin and for API Gateway
--method: Specify the path for HTTP method helps in running offline with offline plugin and for API Gateway
options | shortcut | required | values | default value |
---|---|---|---|---|
--name | -n | ✅ | string | N/A |
--feature | -f | ✅ | string | N/A |
--path | -p | ❎ | string | same as name |
--method | -m | ❎ | string | 'GET' |
Creating a basic function
# Creating a cloak function for jedi feature
$ sls m function -n cloak -f jedi
Creating a basic function with different path and method
# Creating a cloak function for jedi feature with custom path and HTTP method
$ sls m function -n cloak -f jedi -p powers -m POST
The build command helps in building the project for local or global scope
This command comes with four options
--scope: Specify the scope of the build, use this with "--feature" tag
--feature: Specify the name of the existing feature you want to build
options | shortcut | required | values | default value |
---|---|---|---|---|
--scope | -s | ❎ | string | local |
--feature | -f | ❎ | string | N/A |
Saving build Config in serverless.yml
You can also save config in serverless.yml file
custom:
smConfig:
build:
scope: local
all feature build (local scope)
# Building all local features
$ sls m build
Single feature build (local scope)
# Building a single feature
$ sls m build -f jedi -s local
All features build global scope
# Building all features with global scope
$ sls m build -s global
The deploy command helps in deploying serverless projects to AWS (it uses sls deploy
command)
This command comes with four options
--sm-parallel: Specify if you want to deploy parallel (will only run in parallel when doing multiple deployments)
--sm-scope: Specify if you want to deploy local features or global
--sm-features: Specify the local features you want to deploy (comma separated if multiple)
options | shortcut | required | values | default value |
---|---|---|---|---|
--sm-parallel | ❎ | ❎ | true, false | true |
--sm-scope | ❎ | ❎ | local, global | local |
--sm-features | ❎ | ❎ | string | N/A |
--sm-ignore-build | ❎ | ❎ | string | false |
Saving deploy Config in serverless.yml
You can also save config in serverless.yml file
custom:
smConfig:
deploy:
scope: local
parallel: true
ignoreBuild: true
Deploy all features locally
# deploy all local features
$ sls m deploy
Deploy all features globally
# deploy all global features
$ sls m deploy --sm-scope global
Deploy single feature
# deploy all global features
$ sls m deploy --sm-features jedi
Deploy Multiple features
# deploy all global features
$ sls m deploy --sm-features jedi,sith,dark_side
Deploy Multiple features in sequence
# deploy all global features
$ sls m deploy --sm-features jedi,sith,dark_side --sm-parallel false
Author: aa2kb
Source Code: https://github.com/aa2kb/serverless-modular
License: MIT license
1598408880
The Basics
AWS KMS is a Key Management Service that let you create Cryptographic keys that you can use to encrypt and decrypt data and also other keys. You can read more about it here.
Important points about Keys
Please note that the customer master keys(CMK) generated can only be used to encrypt small amount of data like passwords, RSA key. You can use AWS KMS CMKs to generate, encrypt, and decrypt data keys. However, AWS KMS does not store, manage, or track your data keys, or perform cryptographic operations with data keys.
You must use and manage data keys outside of AWS KMS. KMS API uses AWS KMS CMK in the encryption operations and they cannot accept more than 4 KB (4096 bytes) of data. To encrypt application data, use the server-side encryption features of an AWS service, or a client-side encryption library, such as the AWS Encryption SDK or the Amazon S3 encryption client.
Scenario
We want to create signup and login forms for a website.
Passwords should be encrypted and stored in DynamoDB database.
What do we need?
Lets Implement it as Serverless Application Model (SAM)!
Lets first create the Key that we will use to encrypt and decrypt password.
KmsKey:
Type: AWS::KMS::Key
Properties:
Description: CMK for encrypting and decrypting
KeyPolicy:
Version: '2012-10-17'
Id: key-default-1
Statement:
- Sid: Enable IAM User Permissions
Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
Action: kms:*
Resource: '*'
- Sid: Allow administration of the key
Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:user/${KeyAdmin}
Action:
- kms:Create*
- kms:Describe*
- kms:Enable*
- kms:List*
- kms:Put*
- kms:Update*
- kms:Revoke*
- kms:Disable*
- kms:Get*
- kms:Delete*
- kms:ScheduleKeyDeletion
- kms:CancelKeyDeletion
Resource: '*'
- Sid: Allow use of the key
Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:user/${KeyUser}
Action:
- kms:DescribeKey
- kms:Encrypt
- kms:Decrypt
- kms:ReEncrypt*
- kms:GenerateDataKey
- kms:GenerateDataKeyWithoutPlaintext
Resource: '*'
The important thing in above snippet is the KeyPolicy. KMS requires a Key Administrator and Key User. As a best practice your Key Administrator and Key User should be 2 separate user in your Organisation. We are allowing all permissions to the root users.
So if your key Administrator leaves the organisation, the root user will be able to delete this key. As you can see **KeyAdmin **can manage the key but not use it and KeyUser can only use the key. ${KeyAdmin} and **${KeyUser} **are parameters in the SAM template.
You would be asked to provide values for these parameters during SAM Deploy.
#aws #serverless #aws-sam #aws-key-management-service #aws-certification #aws-api-gateway #tutorial-for-beginners #aws-blogs
1656636720
Serverless Framework: Deploy on Scaleway Functions
The Scaleway functions plugin for Serverless Framework allows users to deploy their functions and containers to Scaleway Functions with a simple serverless deploy
.
Serverless Framework handles everything from creating namespaces to function/code deployment by calling APIs endpoint under the hood.
npm install serverless -g
)Let's work into ~/my-srvless-projects
# mkdir ~/my-srvless-projects
# cd ~/my-srvless-projects
The easiest way to create a project is to use one of our templates. The list of templates is here
Let's use python3
serverless create --template-url https://github.com/scaleway/serverless-scaleway-functions/tree/master/examples/python3 --path myService
Once it's done, we can install mandatory node packages used by serverless
cd mypython3functions
npm i
Note: these packages are only used by serverless, they are not shipped with your functions.
Your functions are defined in the serverless.yml
file created:
service: scaleway-python3
configValidationMode: off
useDotenv: true
provider:
name: scaleway
runtime: python310
# Global Environment variables - used in every functions
env:
test: test
# Storing credentials in this file is strongly not recommanded for security concerns, please refer to README.md about best practices
scwToken: <scw-token>
scwProject: <scw-project-id>
# region in which the deployment will happen (default: fr-par)
scwRegion: <scw-region>
plugins:
- serverless-scaleway-functions
package:
patterns:
- '!node_modules/**'
- '!.gitignore'
- '!.git/**'
functions:
first:
handler: handler.py
# Local environment variables - used only in given function
env:
local: local
Note: provider.name
and plugins
MUST NOT be changed, they enable us to use the scaleway provider
This file contains the configuration of one namespace containing one or more functions (in this example, only one) of the same runtime (here python3
)
The different parameters are:
service
: your namespace nameuseDotenv
: Load environment variables from .env files (default: false), read Security and secret managementconfigValidationMode
: Configuration validation: 'error' (fatal error), 'warn' (logged to the output) or 'off' (default: warn)provider.runtime
: the runtime of your functions (check the supported runtimes above)provider.env
: environment variables attached to your namespace are injected to all your namespace functionsprovider.secret
: secret environment variables attached to your namespace are injected to all your namespace functions, see this example projectscwToken
: Scaleway token you got in prerequisitesscwProject
: Scaleway org id you got in prerequisitesscwRegion
: Scaleway region in which the deployment will take place (default: fr-par
)package.patterns
: usually, you don't need to configure it. Enable to include/exclude directories to/from the deploymentfunctions
: Configure of your fonctions. It's a yml dictionary, with the key being the function namehandler
(Required): file or function which will be executed. See the next section for runtime specific handlersenv
(Optional): environment variables specific for the current functionsecret
(Optional): secret environment variables specific for the current function, see this example projectminScale
(Optional): how many function instances we keep running (default: 0)maxScale
(Optional): maximum number of instances this function can scale to (default: 20)memoryLimit
: ram allocated to the function instances. See the introduction for the list of supported valuestimeout
: is the maximum duration in seconds that the request will wait to be served before it times out (default: 300 seconds)runtime
: (Optional) runtime of the function, if you need to deploy multiple functions with different runtimes in your Serverless Project. If absent, provider.runtime
will be used to deploy the function, see this example project.events
(Optional): List of events to trigger your functions (e.g, trigger a function based on a schedule with CRONJobs
). See events
section belowcustom_domains
(Optional): List of custom domains, refer to Custom Domain DocumentationYou configuration file may contains sensitive data, your project ID and your Token must not be shared and must not be commited in VCS.
To keep your informations safe and be able to share or commit your serverles.yml
file you should remove your credentials from the file. Then you can :
.env
file and keep it secretTo use .env
file you can modify your serverless.yml
file as following :
# This will alow the plugin to read your .env file
useDotenv: true
provider:
name: scaleway
runtime: node16
scwToken: ${env:SCW_SECRET_KEY}
scwProject: ${env:SCW_DEFAULT_PROJECT_ID}
scwRegion: ${env:SCW_REGION}
And then create a .env
file next to your serverless.yml
file, containing following values :
SCW_SECRET_KEY=XXX
SCW_DEFAULT_PROJECT_ID=XXX
SCW_REGION=fr-par
You can use this pattern to hide your secrets (for example a connexion string to a database or a S3 bucket).
Based on the chosen runtime, the handler
variable on function might vary.
Node has two module systems: CommonJS
modules and ECMAScript
(ES
) modules. By default, Node treats your code files as CommonJS modules, however ES modules have also been available since the release of node16
runtime on Scaleway Serverless Functions. ES modules give you a more modern way to re-use your code.
According to the official documentation, to use ES modules you can specify the module type in package.json
, as in the following example:
...
"type": "module",
...
This then enables you to write your code for ES modules:
export {handle};
function handle (event, context, cb) {
return {
body: process.version,
statusCode: 200,
};
};
The use of ES modules is encouraged, since they are more efficient and make setup and debugging much easier.
Note that using "type": "module"
or "type": "commonjs"
in your package.json will enable/disable some features in Node runtime. For a comprehensive list of differences, please refer to the official documentation, the following is a summary only:
commonjs
is used as default valuecommonjs
allows you to use require/module.exports
(synchronous code loading, it basically copies all file contents)module
allows you to use import/export
ES6 instructions (asynchronous loading, more optimized as it imports only the pieces of code you need)Path to your handler file (from serverless.yml), omit ./
, ../
, and add the exported function to use as a handler :
- src
- handlers
- firstHandler.js => module.exports.myFirstHandler = ...
- secondHandler.js => module.exports.mySecondHandler = ...
- serverless.yml
In serverless.yml:
provider:
# ...
runtime: node16
functions:
first:
handler: src/handlers/firstHandler.myFirstHandler
second:
handler: src/handlers/secondHandler.mySecondHandler
Similar to node
, path to handler file src/testing/handler.py
:
- src
- handlers
- firstHandler.py => def my_first_handler
- secondHandler.py => def my_second_handler
- serverless.yml
In serverless.yml:
provider:
# ...
runtime: python310 # or python37, python38, python39
functions:
first:
handler: src/handlers/firstHandler.my_first_handler
second:
handler: src/handlers/secondHandler.my_second_handler
Path to your handler's package, for example if I have the following structure:
- src
- testing
- handler.go -> package main in src/testing subdirectory
- second
- handler.go -> package main in src/second subdirectory
- serverless.yml
- handler.go -> package main at the root of project
Your serverless.yml functions
should look something like this:
provider:
# ...
runtime: go118
functions:
main:
handler: "."
testing:
handler: src/testing
second:
handler: src/second
With events
, you may link your functions with specific triggers, which might include CRON Schedule (Time based)
, MQTT Queues
(Publish on a topic will trigger the function), S3 Object update
(Upload an object will trigger the function).
Note that we do not include HTTP triggers in our event types, as a HTTP endpoint is created for every function. Triggers are just a new way to trigger your Function, but you will always be able to execute your code via HTTP.
Here is a list of supported triggers on Scaleway Serverless, and the configuration parameters required to deploy them:
rate
: CRON Schedule (UNIX Format) on which your function will be executedinput
: key-value mapping to define arguments that will be passed into your function's event object during execution.To link a Trigger to your function, you may define a key events
in your function:
functions:
handler: myHandler.handle
events:
# "events" is a list of triggers, the first key being the type of trigger.
- schedule:
# CRON Job Schedule (UNIX Format)
rate: '1 * * * *'
# Input variable are passed in your function's event during execution
input:
key: value
key2: value2
You may link Events to your Containers too (See section Managing containers
below for more informations on how to deploy containers):
custom:
containers:
mycontainer:
directory: my-directory
# Events key
events:
- schedule:
rate: '1 * * * *'
input:
key: value
key2: value2
You may refer to the follow examples:
Custom domains allows users to use their own domains.
For domain configuration please Refer to Scaleway Documentation
Integration with serverless framework example :
functions:
first:
handler: handler.handle
# Local environment variables - used only in given function
env:
local: local
custom_domains:
- func1.scaleway.com
- func2.scaleway.com
Note As your domain must have a record to your function hostname, you should deploy your function once to read its hostname. Custom Domains configurations will be available after the first deploy.
Note: Serverless Framework will consider the configuration file as the source of truth.
If you create a domain with other tools (Scaleway's Console, CLI or API) you must refer created domain into your serverless configuration file. Otherwise it will be deleted as Serverless Framework will give the priority to its configuration.
Requirements: You need to have Docker installed to be able to build and push your image to your Scaleway registry.
You must define your containers inside the custom.containers
field in your serverless.yml manifest. Each container must specify the relative path of its application directory (containing the Dockerfile, and all files related to the application to deploy):
custom:
containers:
mycontainer:
directory: my-container-directory
# port: 8080
# Environment only available in this container
env:
MY_VARIABLE: "my-value"
Here is an example of the files you should have, the directory
containing your Dockerfile and scripts is my-container-directory
.
.
├── my-container-directory
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── server.py
│ └── (...)
├── node_modules
│ ├── serverless-scaleway-functions
│ └── (...)
├── package-lock.json
├── package.json
└── serverless.yml
Scaleway's platform will automatically inject a PORT environment variable on which your server should be listening for incoming traffic. By default, this PORT is 8080. You may change the port
in your serverless.yml
.
You may use the container example to getting started.
The serverless logs
command lets you watch the logs of a specific function or container.
Pass the function or container name you want to fetch the logs for with --function
:
serverless logs --function <function_or_container_name>
serverless info
command gives you informations your current deployement state in JSON format.
MUST
use this library if you plan to develop with Golang).This plugin is mainly developed and maintained by Scaleway Serverless Team
but you are free to open issues or discuss with us on our Community Slack Channels #serverless-containers and #serverless-functions.
Author: Scaleway
Source Code: https://github.com/scaleway/serverless-scaleway-functions
License: MIT license
1617875400
2020 was a difficult year for all of us, and it was no different for engineering teams. Many software releases were postponed, and the industry slowed its development speed quite a bit.
But at least at AWS, some teams released updates out of the door at the end of the year. AWS Lambda received two significant improvements:
With these two new features and Lambda Layers, we now have three ways to add code to Lambda that isn’t directly part of our Lambda function.
The question is now: when should we use what?
In this article, I try to shine some light on the Lambda Layers, Lambda Extensions, and Docker image for Lambda.
First things first. All these Lambda features can be used together. So if you think about where to put your code, at least your decisions aren’t mutually exclusive. You can upload a Docker image and attach a regular Lambda Layer and a Lambda Extension. The same is possible if your Lambda function is based on a ZIP archive.
What does this all mean? Keep reading and find out.
#aws #aws-lambda #serverless #devops #docker #lambda
1627169220
In this video we are going to learn the differences between ec2 vs lambda by going over:
#aws #lambda #ec2 #serverless #aws lambda