七牛服務器入門教程
by Dmitri Zimine
由Dmitri Zimine
使用無服務器,StepFunction和StackStorm Exchange構建社區注冊應用 (Building a community sign-up app with Serverless, StepFunctions, and StackStorm Exchange)
Build a real-world serverless application on AWS with Serverless framework and ready-to-use functions from StackStorm Exchange open-source catalog.
使用無服務器框架和StackStorm Exchange開源目錄中的即用型功能,在AWS上構建真實的無服務器應用程序。
Episode One | Episode Two | Episode Three | Episode Four
第一集| 第二集 | 第三集 | 第四集
Read on if you are:
如果您是,請繼續閱讀:
A serverless developer using Serverless framework who wants to check out ready-to use functions from the StackStorm Exchange open-source catalog,
一位使用無服務器框架的無服務器開發人員,他希望從StackStorm Exchange開源目錄中檢出可立即使用的功能,
A StackStorm user who lives in AWS and misses the breadth of StackStorm Exchange integrations there.
居住在AWS中的StackStorm用戶,卻錯過了那里的StackStorm Exchange集成的廣度。
Anyone who has 2 hours to follow-along and learn serverless with something more elaborate and real-life than a Hello-world example.
任何有2個小時的跟蹤學習和無服務器學習經驗的人,都比Hello-world示例更精致,更真實。
If you only got 8 minutes to spare, skim the text and examples, spend an extra 30 seconds browsing StackStorm Exchange to see the potential, and bookmark this post to get back to it when you need it.
如果您僅剩下8分鐘的時間,請瀏覽文本和示例,花30秒鐘額外的時間瀏覽StackStorm Exchange以查看潛力,并為該帖子添加書簽以在需要時返回它。
介紹 (Intro)
When I explored Serverless with Python, StepFunctions, and Web Front-end, one thing I missed is a catalog of reusable integrations. Something like 200 connectors for Azure Logic apps. Or 130 integration packs for StackStorm.
當我使用Python,StepFunctions和Web Front-end探索Serverless時 ,我錯過的一件事是可重用集成的目錄。 類似于200個用于Azure Logic應用程序的連接器 。 或130個用于StackStorm的集成包 。
When we need to wire in Slack, Jira, Stripe, or Nest, could we skip digging into their APIs and authentication intrinsics, and just grab a ready-to-use function?
當我們需要連接Slack,Jira,Stripe或Nest時,是否可以跳過對它們的API和身份驗證內在函數的了解,而只是獲取一個現成的功能?
Now we can do exactly that: StackStorm just announced a plugin for Serverless framework that turns integrations from StackStorm Exchange into AWS Lambda functions.
現在我們可以完全做到這一點:StackStorm剛剛宣布了一個用于無服務器框架的插件,該插件可以將StackStorm Exchange的集成轉換為AWS Lambda函數。
In this tutorial, I’ll show how to use the plugin and Exchange integrations, in the context of building a serverless community on-boarding application from a ground-up. Let’s make this conversational and fun.
在本教程中,我將展示如何從頭開始構建無服務器社區入門應用程序,以及如何使用插件和Exchange集成。 讓我們變得有趣而有趣。
I assume no familiarity with either Serverless framework nor StackStorm. But you should know how to code, and be smart to compensate for mistakes and omissions I’ll inevitably make.
我假設對Serverless框架或StackStorm都不熟悉。 但是您應該知道如何編碼,并且要聰明地彌補我不可避免的錯誤和遺漏。
We will be going slow, with excruciating details, thus it is going to be four episodes.
我們將走得很慢,細節令人毛骨悚然,因此將是四集。
In this first episode, I’ll set everything up and deploy my first StackStorm Exchange action.
在第一集中,我將設置所有內容并部署我的第一個StackStorm Exchange操作。
In the next episode, we’ll add more actions.
在下一集中,我們將添加更多操作。
In the third episode I’ll wire them together with a AWS StepFunction.
在第三集中,我將它們與AWS StepFunction連接在一起。
In the fourth episode we’ll add Web Front-end with the Reflection and Summary. Each episode will take about an hour to follow.
在第四集中,我們將在Web前端添加反射和摘要。 每個情節大約需要一個小時。
Ready? Let’s rock.
準備? 開始狂歡吧。
應用程序 (The application)
We will build a community on-boarding application. Actually, rebuilding from scratch the one we run at StackStorm. It’s like SlackIn with a multi-step customizable on-boarding workflow. The app presents a registration web-form, which passes new user info through API Gateway to the StepFunction workflow that carries on-boarding steps.
我們將構建一個社區入門應用程序。 實際上,從頭開始重建我們在StackStorm上運行的那個。 就像SlackIn一樣, 它具有多步可定制的入職工作流程。 該應用程序顯示一個注冊網絡表單,該表單通過API網關將新的用戶信息傳遞給執行注冊步驟的StepFunction工作流程。
In my case, the steps are 1) invite users to Slack 2) create contact record in ActiveCampaign CRM tool and 3) put a user record into internal DynamoDB table. Here is how it looks:
在我的情況下,步驟是1)邀請用戶使用Slack; 2)在ActiveCampaign CRM工具中創建聯系人記錄;以及3)將用戶記錄放入內部DynamoDB表中。 外觀如下:
You can find the previous implementation on github, or use it and join StackStorm community on Slack for questions about StackStorm Exchange integration.
您可以在github上找到以前的實現,或者使用它并在Slack上加入StackStorm社區 ,以獲取有關StackStorm Exchange集成的問題。
準備好 (Getting Ready)
First, you’ll need AWS account, NodeJS, Docker, and Serverless framework. And Slack! As our first action will be inviting users to Slack.
首先,您需要AWS帳戶,NodeJS,Docker和無服務器框架。 和松弛! 作為第一步,我們將邀請用戶使用Slack。
Make sure Node.JS is installed, and it’s version is
8.4.0
or higher.確保已安裝Node.JS ,并且其版本為
8.4.0
或更高版本。Install Serverless framework, and setup AWS credentials for it following this guide.
安裝無服務器框架 ,并按照本指南為其設置AWS憑證。
Install Docker. The plugin uses it for build environment to make the lambdas binary compatible to AWS execution environment no matter what OS you’re using for development. There is a way to make it work without Docker but don’t take chances.
安裝Docker 。 該插件將其用于構建環境,以使lambdas二進制文件與AWS執行環境兼容,無論您使用哪種OS進行開發。 有一種方法可以使它在沒有Docker的情況下工作,但不要冒險。
Slack! Our action will require admin access and will be using undocumented Slack API (docs here, pun intended) to invite new users. The easiest is to just go ahead create a new team. Takes 4 min. Slack won’t mind — they’ll show growth to their VC.
松弛! 我們的操作將需要管理員訪問權限,并將使用未記錄的Slack API(此處為雙關語)來邀請新用戶。 最簡單的方法就是繼續建立新的團隊 。 需要4分鐘。 Slack不在乎-他們將向VC顯示增長。
Once the workspace is created, time to get an authentication token. Go to api.slack.com/custom-integrations/legacy-tokens. Fear not the “Legacy Warnings”: this tutorial will turn legacy before they do. Do what they say, get your token.
一旦創建了工作空間,就該獲取身份驗證令牌了。 前往api.slack.com/custom-integrations/legacy-tokens 。 不要害怕“遺留警告”:本教程將先解決遺留問題。 照他們說的做,拿到你的令牌。
PRO TIP: Use this quick hack to get and use your own user’s auth token. Much faster, good for playing and debugging. But please never, never use it for production!
專業提示:使用此快速技巧來獲取和使用您自己用戶的身份驗證令牌。 快得多,適合播放和調試。 但是請永遠不要將其用于生產!
創建一個項目,添加第一個動作 (Create a project, add a first action)
Try sls --help
to make sure that at least something works. sls
is a shorthand for serverless
, the Serverless framework CLI. Now put your coffee aside, time to create a project. Some folks like using templates that come with serverless: sls create --template
. I prefer to start from scratch:
嘗試使用sls --help
來確保至少可以正常工作。 sls
是serverless
(無服務器框架CLI)的簡寫。 現在,將咖啡放在一邊,時間來創建一個項目。 一些人喜歡使用無服務器附帶的模板: sls create --template
。 我更喜歡從頭開始:
mkdir slack-signup-serverless-stormlesscd slack-signup-serverless-stormless
npm init
# Once you answer questions, the project is set up.
Next, install serverless-plugin-stackstorm
, the one that plugs in the StackStorm Exchange actions.
接下來,安裝serverless-plugin-stackstorm
,它可以插入StackStorm Exchange操作。
npm install --save-dev serverless-plugin-stackstorm
… and create a minimal serverless.ym
file so that sls
command will pick up the plugin:
…并創建一個最小的serverless.ym
文件,以便sls
命令選擇該插件:
Now, create the first action. I’ll use a battle-tested Slack pack from StackStorm Exchange. Which action, you say? Ok, StackStorm Exchange is not smart enough yet to show pack’s action list, but sls stackstorm
will rescue us.
現在, 創建第一個動作 。 我將使用來自StackStorm Exchange的經過戰斗測試的Slack軟件包 。 您說哪個動作? 好的,StackStorm Exchange還不夠智能,無法顯示pack的操作列表,但是sls stackstorm
可以拯救我們。
sls stackstorm info --pack slack
sls stackstorm info --pack slack
Oh my! There’re so many! what are they? I guess I need a PR to print action description. Meantime, | grep admin
will get us the one we need: slack.users.admin.invite
. Let's query the action for it's parameters:
天啊! 有很多! 這些是什么? 我想我需要PR才能打印動作說明。 同時, | grep admin
| grep admin
將為我們提供所需的文件: slack.users.admin.invite
。 讓我們查詢動作的參數:
$ sls stackstorm info --action slack.users.admin.inviteslack.users.admin.invite ...... Send an invitation to join a Slack OrgParameters attempts [integer] ......... description is missing channels [string] .......... Channels to auto join. email [string] (required) ... Email address to send invitation to. first_name [string] ........ Users first name set_active [boolean] ....... Should the user be active. token [string] ............. Slack API token.Config action_token [string] ...... Slack Action token. admin [object] ............. Admin-action specific settings. post_message_action [object] Post message action specific settings. sensor [object] ............ Sensor specific settings.
Awesome! We can see that there is only one required parameter, email
, but I'll add first_name
to stay conversational. The token can be passed as parameters, or as config. And if I choose to use config, my prior tribal knowledge hints that the admin [object]
requires only admin_token
. The very one I asked you to remember when you were setting up Slack workspace.
太棒了! 我們可以看到只有一個必需的參數email
,但是我將添加first_name
來保持對話狀態。 令牌可以作為參數或配置傳遞。 而且,如果我選擇使用config,則我先前的部落知識表明admin [object]
僅需要admin_token
。 我要您記住設置Slack工作區時的那個。
PRO TIP: While we are still polishing the plugin to expose all the Config details, you can find it out by exploring StackStorm Exchange pack config schema in config.schema.yaml
file. For example, here is config.example.yaml for our Slack pack.
專業提示:在我們仍在完善插件以公開所有Config詳細信息的同時,您可以通過探索config.schema.yaml
文件中的StackStorm Exchange包配置架構來找到它。 例如,這是我們的Slack包的config.example.yaml 。
Now we have all we need to create the heart of any Serverless project: the serverless.yml
. Here it comes:
現在,我們擁有創建任何無服務器項目的核心所需的全部內容: serverless.yml
。 它來了:
This is a good time to learn a bit of Serverless. Take a quick break to skim Core Concepts and bookmark Serverless.yml Reference.
這是學習一點無服務器的好時機。 快速瀏覽一下Core Concepts并為Serverless.yml Reference添加書簽。
I threw in the events
section in lines 9:12 so that we can invoke the function with REST call through AWS API Gateway endpoint. Serverless framework will do all the Gateway magic.
我將events
部分放在9:12行中,以便我們可以通過AWS API Gateway端點通過REST調用來調用該函數。 無服務器框架將完成所有網關魔術。
Note that this default configuration instructs API Gateway to pass the REST POST call with POST body under the body
key (details here. When we POST {"first_name": "Santa", "email": "santa@mad.russian.xmas.com"}
, the event passed to the Lambda is:
請注意,此默認配置指示API網關通過body
密鑰下的POST正文傳遞REST POST調用( 詳細信息 。 此處 ,當我們POST {"first_name": "Santa", "email": "santa@mad.russian.xmas.com"}
,傳遞給Lambda的事件是:
..."body": { "first_name": "Santa", "email": "santa@mad.russian.xmas.com"}
Knowing the input data structure is important to map it to the action input parameters. It’s intuitive: input
represents event
parameter of AWS Lambda programming model(BTW should we call it event
? Vote with a PR!).
知道輸入數據結構對于將其映射到動作輸入參數很重要。 直觀: input
代表AWS Lambda編程模型的 event
參數(順便說一句,我們應該將其稱為event
嗎?請投票給PR!)。
Jinja is used to map the inputs; our JavaScript friends who're less familiar with this common Python tool find it intuitive enough in simple cases; and Stack-overflow is full of magic Jinja tricks.
Jinja用于映射輸入; 不熟悉此通用Python工具JavaScript朋友會發現它在簡單情況下足夠直觀; 而Stack-overflow充滿了神奇的Jinja技巧。
In lines 16:17 of serverless.yml
I map the two parameters from input body to desired action input parameters. Optionally, you can also form a function output from action results. I’ll keep it simple for now (line 20:22) and save more tricks for later.
中的行16:17 serverless.yml
我從輸入體的兩個參數所需的操作輸入參數映射。 您也可以選擇從操作結果中形成函數輸出。 我現在將其保持簡單(第20:22行),并保存更多技巧以供日后使用。
To keep the config separate, I created a file env.yml
that and put my config parameters in it:
為了使配置分開,我創建了一個文件env.yml
并將其配置參數放入其中:
# ./env.yml# WARNING: Don't commit to Github :)slack: admin_token: "xoxs-111111111111-..." organization: "my-team"
Then I used it in serverless.yml
like this: admin: ${file(env.yml):slack}
. Note how this syntax puts the object from the key in the file to the key in serverless.yml
.
然后,我用它在serverless.yml
這樣的: admin: ${file(env.yml):slack}
。 請注意,此語法如何將對象從文件中的密鑰放入serverless.yml
的密鑰。
Ok, that’s it! The function is ready to fly to AWS with sls deploy
. But I take it sloooow. Step by step. First, I’ll package it locally.
好的,就是這樣! 該功能已準備就緒,可以通過sls deploy
轉到AWS。 但是我覺得這很糟糕 。 一步步。 首先,我將其打包在本地。
sls package
The very first time takes a long time as this is the time when the plugin installs its runtime dependencies. It pulls the Docker images from the Hub. It installs StackStorm runners — the code that knows how to run StackStorm Exchange packs. It pulls the slack
pack from Exchange. It installs slack
pack python dependencies. It does a lot of work for us, and it takes time. Good news: it's only the first time.
第一次需要很長時間,因為這是插件安裝其運行時依賴項的時間。 它從集線器中提取Docker映像。 它安裝了StackStorm運行程序—該代碼知道如何運行StackStorm Exchange包。 它將slack
包從Exchange中拉出來。 它安裝了slack
pack python依賴項。 它為我們做了很多工作,而且需要時間。 好消息:這只是第一次。
Oh, did I mention that you must be connected? Or do we assume internet connection a basic commodity like breathing air and electric power? At least before FCC repeals Network Neutrality? So yes, you need internet connection to live in the serverless world.
哦,我是否提到您必須連接? 還是我們假設互聯網連接是呼吸空氣和電力之類的基本商品? 至少在FCC取消網絡中立性之前? 因此,是的,您需要Internet連接才能生活在無服務器的世界中。
Now let’s run this locally.
現在讓我們在本地運行它。
sls stackstorm docker run --function InviteSlack --verbose \--data \'{"body": {"first_name": "Santa", "email": "santa@mad.russian.xmas.com"}}'
Local runs happen in a container — you’ll see Spin Docker container to run a function
CLI output. It takes a bit longer, but ensures that the execution environment matches AWS lambda very closely, so better safe than sorry.
本地運行在容器中進行-您將看到Spin Docker container to run a function
CLI輸出。 這需要花費更長的時間,但是可以確保執行環境非常緊密地匹配AWS lambda,因此比遺憾更安全。
When I debug input and output parameter transformations, I may not want to call the actual function, like in case of Slack rate-limiting API. Use --passthrough
parameter that tells the plugin to do the dry-run and skip the action invocation.
當我調試輸入和輸出參數轉換時,我可能不想調用實際函數,例如使用Slack速率限制API的情況。 使用--passthrough
參數,告訴插件進行空運行并跳過動作調用。
Now we are really ready. Let’s deploy the function to AWS, and run it “serverless”.
現在我們已經準備好了。 讓我們將該功能部署到AWS上,然后“無服務器”運行它。
sls deploy
It will take some while — now it’s serverless (and honestly, our bundle is a bit bloated, patience! plugin developers are currently busy solving other problems, we will optimize it as soon as we can)
這將需要一些時間-現在它已經是無服務器的了(老實說,我們的捆綁包有點,腫,耐心!插件開發人員目前正在忙于解決其他問題,我們將盡快對其進行優化)
PRO TIP: if something goes wrong at this point, most likely something is not right with your AWS setup. Go back to “Getting Ready, step 2”. Read Serverless Installation doc. Google, Stack-overflow, Serverless Gitter channel or Forum.
專業提示:如果此時出現問題,則很可能是您的AWS設置不正確。 返回到“準備就緒,第2步”。 閱讀無服務器安裝文檔。 Google,堆棧溢出,無服務器Gitter頻道或論壇 。
You might be curious to see how it looks in the AWS console. If the PRO in you is saying “no, you should stay cool and use CLI”, don’t listen. Go indulge yourself, open a browser and take a good look at your Lambda. While there, you might also inspect the API Gateway endpoint that sls
created for you.
您可能想知道它在AWS控制臺中的外觀。 如果您的PRO在說“不,您應該保持冷靜并使用CLI”,請不要聽。 沉迷于自己,打開瀏覽器,仔細看一下Lambda。 在此處時,您可能還會檢查sls
為您創建的API Gateway端點。
But to test it, we’ll go back to terminal. Here is how to run your Lambda with sls
:
但是要進行測試,我們將回到終端。 這是使用sls
運行Lambda的方法:
sls invoke --function InviteSlack --log --data '{"body": {"first_name": "Santa", "email": "santa@mad.russian.xmas.com"}}'
Finally, let’s POST to the API endpoint. The endpoint was printed at the end of sls deploy
and you should have taken notice, but it's OK if you didn't: you can always get it by typing sls info
.
最后,讓我們發布到API端點。 端點是在sls deploy
結束時打印的,您應該已經注意到了,但是如果沒有,也可以:通過輸入sls info
可以始終獲得端點。
You curl
lovers go ahead use it to POST; be sure to set Content-Type=application/json
header. Me - I'll show off with httpie, aka CURL for humans:
curl
戀人請繼續使用它進行發布; 確保設置Content-Type=application/json
標頭。 我-我將使用httpie (也稱為人類的CURL)進行炫耀:
# DON'T copy-paste! Use YOUR endpoint!
http --json POST https://YOUR-ENDPOINT.amazonaws.com/dev/invite \email=test@example.com first_name=Dmitri
How did it go? Everything worked, at least for me. Let’s fire yet another most useful sls
command to check the CloudWatch logs:
怎么樣了 一切正常,至少對我而言。 讓我們啟動另一個最有用的sls
命令來檢查CloudWatch日志:
sls logs --function InviteSlack
Success! And the end of the first episode. Enough for now: Christmas time is here, take it slow, enjoy!
成功! 第一集的結尾。 現在已經足夠:圣誕節到了,慢慢來,盡情享受吧!
The code example so far is on Github at 1-add-first-action.
到目前為止的代碼示例在Github上的1-add-first-action上 。
Episode 2: Adding more actions
第2集 : 添加更多操作
Hope this helped you learn something new, find something interesting, or provoked some good thoughts. Please share your thoughts in the comments here, or tweet me @dzimine.
希望這可以幫助您學習新知識,發現有趣事物或激發一些好的想法。 請在此處的評論中分享您的想法,或在推特上給我@dzimine 。
翻譯自: https://www.freecodecamp.org/news/tutorial-building-a-community-on-boarding-app-with-serverless-stepfunctions-and-stackstorm-b2f7cf2cc419/
七牛服務器入門教程