1. 程式人生 > >Using API Gateway stage variables to manage Lambda functions

Using API Gateway stage variables to manage Lambda functions

Ed Lima Ed Lima, Cloud Support Engineer

There’s a new feature on Amazon API Gateway called stage variables. Stage variables act like environment variables and can be used to change the behavior of your API Gateway methods for each deployment stage; for example, making it possible to reach a different back end depending on which stage the API is running on. This blog post will demonstrate how to use stage variables with two different AWS Lambda functions.

For this example we will use the sample functions from the Lambda Walkthrough. Sign in to the AWS Management console, open the Lambda console, and create the required functions (make sure you’re using the appropriate IAM execution role:

GetHelloWorld

console.log('Loading event');

exports.handler = function(event, context) {
  context.done(null, {"Hello":"World"});  // SUCCESS with message
};

GetHelloWorldWithName

console.log('Loading event');
            
exports.handler = function(event, context) {
  var name = (event.name === undefined ? 'No-Name' : event.name);
  context.done(null, {"Hello":name}); // SUCCESS with message
};

In the API Gateway console, create a new API called LambdaVar:

In the root resource, create a new GET method. In Integration type for the new method, choose Lambda Function, then select your Lambda Region, and type ${stageVariables.lbfunc} in the Lambda Function field. This tells API Gateway to read the value for this field from a stage variable at runtime:

The console detects the stage variable and displays the Add Permission to Lambda Function message:

Next, you manually give permissions to your Lambda functions, using the AWS CLI. This enables API Gateway to execute the functions. The CLI command must be issued with credentials that have permission to call the “add-permission” action of the Lambda APIs. The output from the AWS CLI will contain the policy statement that was set on the Lambda function resource policies.

aws lambda add-permission --function-name arn:aws:lambda:us-west-2:XXXXXXXXXXXXX:function:GetHelloWithName --source-arn arn:aws:execute-api:us-west-2:XXXXXXXXXXXXX:y91j2l4bnd/*/GET/ --principal apigateway.amazonaws.com --statement-id 95486b16-7d8a-4aca-9322-5f883ab702a6 --action lambda:InvokeFunction

# expected output
{
    "Statement": "{\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-west-2: XXXXXXXXXXXX:y91j2l4bnd/*/GET/\"}},\"Action\":[\"lambda:InvokeFunction\"],\"Resource\":\"arn:aws:lambda:us-west-2:XXXXXXXXXXXX:function:GetHelloWithName\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Sid\":\"95486b16-7d8a-4aca-9322-5f883ab702a6\"}"
}

aws lambda add-permission --function-name arn:aws:lambda:us-west-2:XXXXXXXXXXXXX:function:GetHelloWorld --source-arn arn:aws:execute-api:us-west-2:XXXXXXXXXXXXX:y91j2l4bnd/*/GET/ --principal apigateway.amazonaws.com --statement-id 95486b16-7d8a-4aca-9322-5f883ab702a6 --action lambda:InvokeFunction

# expected output
{
    "Statement": "{\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-west-2: XXXXXXXXXXXXX:y91j2l4bnd/*/GET/\"}},\"Action\":[\"lambda:InvokeFunction\"],\"Resource\":\"arn:aws:lambda:us-west-2: XXXXXXXXXXXXX:function:GetHelloWorld\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Sid\":\"95486b16-7d8a-4aca-9322-5f883ab702a6\"}"
}

Back in the console, you can now create your first stage. Choose Deploy API. In Stage name, type dev. In Stage description, type a description for your new stage, and then choose Deploy.

After the API deploys, on the Stage Editor page, choose the Stage Variables tab and add the stage variable from your API configuration, lbfunc. As you can see from the screenshot the value assigned to the new stage variable is the name of the Lambda function we want to invoke:

The second Lambda function, GetHelloWithName, can also receive a name parameter. You can configure the API to read the incoming parameter from the query string and pass it to the JSON body for the Lambda function by using mapping templates. To do this, go back to the GET method and choose Integration Request. Under Mapping Templates, add the following mapping template for the application/json content type:

{ "name": "$input.params('name')" }

To apply the change, deploy the API to a new stage called prod:

Next, set up the stage variable in the new deployment stage to point to the second Lambda function, GetHelloWithName:

Now you are ready to test!

The dev stage invoke URL directs you to the GetHelloWorld Lambda function:

The prod stage invoke URL with the appropriate query string directs you to the GetHelloWithName Lambda function and returns a value:

If you try to use the query string on the first stage, the query string will simply be ignored because the Lambda function is not configured to handle the parameter:

There it is: a nice way to optimize your Amazon API Gateway resources by using a single method with 2 different stages that use 2 different Lambda functions.

Alternatively, you can mix and match static names with stage variables in the integrations. For example, instead of having 2 different Lambda functions you can have a single Lambda function with multiple versions and aliases. Then, in the integration setup, you can simply use the stage variables to point to the correct alias. For instance, using an alias to one of the Lambda functions above, add the following: GetHelloWithName:${stageVariables.lambdaAlias} as Integration Type:

In your stage, add the lambdaAlias stage variable accordingly:

This variable will refer to the Lambda alias of your function:

As you can see, the new stage variables feature enables you to dynamically access different back ends, using fewer configuration steps and resources/methods in your API Gateway. The variables add even more flexibility to stages when deploying your API, which can enable different use cases in your environments.

相關推薦

Using API Gateway stage variables to manage Lambda functions

Ed Lima, Cloud Support Engineer There’s a new feature on Amazon API Gateway called stage variables. Stage variables act like environment

Connected contracting: Using off-chain smart contracts to manage a supply chain

Summary Learn how to track perishable goods on a Hyperledger blockchain using a smart legal contract running on Clause to capture the

Pass Custom Headers Through Amazon API Gateway to an AWS Lambda Function

By default, a Lambda function only ingests the request body received by an API created in the API Gateway. To pass custom headers f

結合API GatewayLambda實現登入時的重定向和表單提交請求(Python3實現)

1. 建立Lambda函式,程式碼如下: 1 from urllib import parse 2 3 def lambda_handler(event, context): 4 body = event['body'] 5 print("-----------body:"

AWS Lambda Console Now Enables You to Manage and Monitor Serverless Applications

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Tutorial for building a Web Application with Amazon S3, Lambda, DynamoDB and API Gateway

Tutorial for building a Web Application with Amazon S3, Lambda, DynamoDB and API GatewayI recently attended Serverless Day at the AWS Loft in downtown San

Code Evaluation With AWS Lambda and API Gateway

This tutorial details how AWS Lambda and API Gateway can be used to develop a simple code evaluation API, where an end user submits code, via an AJAX fo

Using bower to manage static files with Django

Using bower to manage static files with DjangoSharing a way to manage libraries like bootstrap, jquery with bower without using any external app.first of a

Resolve "Malformed Lambda Proxy Response" or 502 Errors With API Gateway

exports.handler = (event, context, callback) => { var responseBody = { "key3": "value3", "key2": "value2", "key1

Resolve 500 Errors With Lambda and API Gateway

If you build an API with Lambda integration using the API Gateway console, the console automatically requests to add the required permissions f

Using Kubernetes secrets to manage credentials

Doug Tidwell is a Senior Software Engineer at IBM. His job as a content strategist for the developerWorks team is to figure out how to deliver as much usef

api-gateway實踐(3)Linux環境啟動

iad system 啟動mysql lin edi sql 查看 redis mysq 1、啟動、查看mysql 1.1、啟動mysql systemctl status mariadb 1.2、查看mysql systemctl status m

api-gateway實踐(4)網關服務集成驗證

pig server 服務集 blank 網關 ces ron ken localhost 原始服務地址: http://10.110.17.20:7070/spring-oauth-server/m/user_info?access_token=8d671613-da31

api-gateway

包括 詳細介紹 idp ati sdn 命令 rop uri 密碼 #spring-oauth-server <strong>Spring與OAuth2的整合</strong> 項目用Maven管理, 字符編碼: UTF-8 使用的技術與版本號<

api-gateway實踐(12)新服務網關 - 審批產生網關身份!

服務 1.2 界面 resource details sco grant .cn 後臺 一、創建網關側身份 1、client身份(oauth_client_details) 1.1、數據結構 1.2、界面代碼 <form id="formDto" cla

MAVEN Error: Using platform encoding (GBK actually) to copy filtered resources.....

XML tracking pom.xml文件 pos bsp cli -a ati Coding 環境:Maven3.2.5+MyEclipse 2015CI 現象:在Maven編譯過程中出現錯誤信息:Using platform encoding (GBK act

api-gateway實踐(15)新服務網關 -運行環境搭建

index 列表 svc 環境搭建 1-1 cred dex .com 運行環境搭建 一、運行環境 10.110.17.20 /opt/tomcat8.5.15/webapps http://10.110.17.20:7070/admin 二、應用列表 服務消費者: htt

api-gateway實踐(19)InputStream的復用

數組下標 例如 本地緩存 api 標記 擔心 部分 supported aos 相關鏈接: inputstream復制:http://www.cnblogs.com/happyaday/p/4616023.html 對象克隆:https://zhidao.baidu.com

api-gateway實踐(8)新服務網關 - 第二次評審結果匯總

完成 image nbsp 實踐 編寫 表達 res 添加 logs 一、王靜 1、緩存數據同步問題 2、組 上線下線 3、創建分組後集市默認不顯示 有version時顯示 4、inspur-app 改為網關認證 5 、url,正則表達式? 6 、api 編輯可以修改方法

api-gateway實踐(7)新服務網關 - 網關請求監控統計

version 提供者 evc 響應 vclient nbsp 日期時間 實時監控 red 一、實時監控 用戶點擊服務實例,系統顯示服務實例-version下的api列表, 用戶點擊某個api的如下兩個圖標 1、API請求次數監控 橫軸:時間,粒度為分鐘 縱軸:請求訪問次數