В предыдущем посте я показал вам, как создавать и развертывать AWS Lambda. Мы продолжим эту работу и рассмотрим обновление только кода для этой лямбды. Мы также добавим конечную точку REST в AWS Lambda с помощью AWS API Gateway .
Поэтому, прежде чем продолжить … если вы этого еще не сделали, следуйте инструкциям в предыдущем посте, чтобы убедиться, что у вас запущен экземпляр AWS Lambda.
Шаг 1: Обновите свою лямбду
Вставьте следующее в update-lambda.sh
|
01
02
03
04
05
06
07
08
09
10
11
12
|
#!/bin/bash### Create the lambda packagezip -j helloworld.zip *.pyfunction_name="helloworld"package_file=helloworld.zip### Update the lambda codeaws lambda update-function-code \ --function-name $function_name \ --zip-file fileb://$package_file |
или для Java
|
01
02
03
04
05
06
07
08
09
10
11
12
|
#!/bin/bash### Create the lambda packagemvn packagefunction_name="helloworld"package_file="target/lambda-java-example-1.0-SNAPSHOT.jar"### Update the lambda codeaws lambda update-function-code \ --function-name $function_name \ --zip-file fileb://$package_file |
Сделайте исполняемый скрипт chmod +x update-lambda.sh и обновите ваш lambda ./update-lambda.sh .
Шаг 2: Передайте что-нибудь своей лямбде
Теперь, когда мы знаем, как обновить лямбду в облаке, давайте внесем изменения, чтобы мы могли передать что-то в качестве параметра. Вместо того чтобы сказать «Привет, мир!» мы хотим, чтобы он передал привет кому бы то ни было.
В Python:
|
1
2
|
def lambda_handler(event, context): return "Hello {}!".format(event['to']) |
или как в Java:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
package example;import com.amazonaws.services.lambda.runtime.Context;public class Hello { public String lambdaHandler(Request request, Context context) { return "Hello " + request.getTo() + "!"; }}class Request { private String to; public void setTo(String to) { this.to = to; } public String getTo() { return to; }} |
Шаг 3: Скажите лямбда, чтобы поздороваться с кем бы
|
1
|
aws lambda invoke --invocation-type RequestResponse --function-name helloworld --payload '{"to": "whomever"}' output.txt |
Вы должны увидеть Привет, кто бы ни! в выходном тексте
Шаг 4: Добавим API остальных
Вставьте следующий сценарий в файл, такой как create-api.sh , измените разрешения для файла для выполнения и выполните сценарий. Сделай глубокий вдох …
Примечание: этот сценарий ожидает определения переменных среды AWS_REGION и AWS_ACCOUNT_ID
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
#!/bin/bashset -eregion=$AWS_REGIONaccount_id=$AWS_ACCOUNT_IDecho "Creating a new API and capturing it's ID ..."api_id=$(aws apigateway create-rest-api \ --name HelloWorldAPI \ --description "Hello World API" \ --output text \ --query 'id')echo "> API ID is: $api_id"echo "Storing the API ID on disk - we'll need it later ..."echo $api_id > api_id.txtecho "Geting the root resource id for the API ..."root_id=$(aws apigateway get-resources \ --rest-api-id "${api_id}" \ --output text \ --query 'items[?path==`'/'`].[id]')echo root_id=$root_idecho "Creating a resource for the /hello path"resource_id=$(aws apigateway create-resource \ --rest-api-id "${api_id}" \ --parent-id "${root_id}" \ --path-part hello | jq -r .id) echo "Resource id is $resource_id"echo "Creating the GET method on the /hello resource"aws apigateway put-method \ --rest-api-id "${api_id}" \ --resource-id "${resource_id}" \ --http-method GET \ --authorization-type NONE echo "Integrating the GET method to lambda. Note that the request tempalate uses API Gateway template language to pull in the query parameters as a JSON event for the lambda."aws apigateway put-integration \ --rest-api-id "${api_id}" \ --resource-id "${resource_id}" \ --http-method GET \ --type AWS \ --request-templates '{ "application/json": "{\n #foreach($param in $input.params().querystring.keySet())\n \"$param\": \"$util.escapeJavaScript($input.params().querystring.get($param))\" \n #end\n }" }' \ --integration-http-method POST \ --uri arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${region}:${account_id}:function:helloworld/invocationsecho "Creating a default response for the GET method"aws apigateway put-method-response \ --rest-api-id "${api_id}" \ --resource-id "${resource_id}" \ --http-method GET \ --status-code 200echo "Creating a default response for the integration"aws apigateway put-integration-response \ --rest-api-id "${api_id}" \ --resource-id "${resource_id}" \ --http-method GET \ --status-code 200 \ --selection-pattern ".*"echo "Adding permission for the API to call the lambda for test so we can use the console to make the api call"aws lambda add-permission \ --function-name helloworld \ --statement-id apigateway-helloworld-get-test \ --action lambda:InvokeFunction \ --principal apigateway.amazonaws.com \ --source-arn "arn:aws:execute-api:${region}:${account_id}:${api_id}/*/GET/hello"echo "Adding permission for the API to call the lambda from any HTTP client"aws lambda add-permission \ --function-name helloworld \ --statement-id apigateway-helloworld-get \ --action lambda:InvokeFunction \ --principal apigateway.amazonaws.com \ --source-arn "arn:aws:execute-api:${region}:${account_id}:${api_id}/api/GET/hello"echo "Creating a deployment"aws apigateway create-deployment \ --rest-api-id "${api_id}" \ --stage-name api echo "All done! you can invoke the api on https://${api_id}.execute-api.${region}.amazonaws.com/api/hello?to=whomever" |
Шаг 5: вызов API
Последний вывод скриптов содержит URL-адрес, который вы можете вставить в браузер. Вы должны увидеть ответ «Привет, кто бы ни!» как только вы нажмете, введите в браузере.
Шаг 6: Очистка
Вы можете использовать скрипт delete.sh созданный в предыдущем посте, для удаления лямбды. Чтобы удалить API: вставьте следующий скрипт и выполните как обычно.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
#!/bin/bashecho "Reading API id that I store in my create-api script"api_id=$(<api_id.txt)echo "Removing the permissions from the lambda"aws lambda remove-permission \ --function-name helloworld \ --statement-id apigateway-helloworld-getaws lambda remove-permission \ --function-name helloworld \ --statement-id apigateway-helloworld-get-testecho "Deleting the API"aws apigateway delete-rest-api \ --rest-api-id "${api_id}" |
Шаг 7: Расслабьтесь … все кончено;)
… пока что!!!
| Ссылка: | AWS Lambda с API Gateway от нашего партнера JCG Масхука Бадара в блоге Crafted Software . |