2016-09-14 116 views
1

我正在使用AWS Lambda函數使用Boto3創建API密鑰。使用boto3在AWS API網關中使用boto3創建API密鑰

以下測試本地成功:

import boto3 

client = boto3.client('apigateway') 

response = client.create_api_key(
    name='test_user_from_boto', 
    description='This is the description', 
    enabled=True, 
    generateDistinctId=True, 
    value='', 
    stageKeys=[{ 
     'restApiId':'aaa', 
     'stageName':'beta' 
    }] 
) 

這工作沒有問題返回一個字典作爲expected。返回字典包含一個value密鑰,該密鑰具有生成的api密鑰值,這正是我所追求的。

在AWS Lambda中執行類似操作時,返回字典不包含value密鑰。

這是我的Lambda hander函數。

import boto3 


api_id = 'zzz' 
plan_id_map = { 
    'trial': 'aaa', 
    'basic': 'bbb', 
    'professional': 'ccc' 
} 

def handler(event, context): 
    user_name = event['user_name'] 
    stage = event['stage'] 
    plan = event['plan'] 

    client = boto3.client('apigateway') 
    api_key_response = client.create_api_key(
     name=user_name, 
     description='', 
     enabled=True, 
     # generateDistinctId=True, # including this argument throws an error 
     # value='', # including this argument throws an error 
     stageKeys=[{ 
      'restApiId': api_id, 
      'stageName': stage 
     }] 
    ) 

    user_key_id = api_key_response['id'] 
    user_api_key = api_key_response['value'] # throws a key error here 

    plan_response = client.create_usage_plan_key(
     usagePlanId=plan_id_map[plan], 
     keyId=user_key_id, 
     keyType='API_KEY')  

    return { 
     'user_name': user_name, 
     'user_key_id': user_key_id, 
     'user_api_key': user_api_key 
    } 

從印刷api_key_response結果如下:

{ 
    u'name': u'test_user_from_lambda', 
    'ResponseMetadata': { 
     'HTTPStatusCode': 201, 
     'RequestId': 'b8298d38-7aec-11e6-8322-5bc341fc4b73', 
     'HTTPHeaders': { 
      'x-amzn-requestid': 'b8298d38-7aec-11e6-8322-5bc341fc4b73', 
      'date': 'Thu, 15 Sep 2016 02:33:00 GMT', 
      'content-length': '203', 
      'content-type': 'application/json' 
     } 
    }, 
    u'createdDate': datetime.datetime(2016, 9, 15, 2, 33, tzinfo=tzlocal()), 
    u'lastUpdatedDate': datetime.datetime(2016, 9, 15, 2, 33, tzinfo=tzlocal()), 
    u'enabled': True, 
    u'id': u'xyzxyz', 
    u'stageKeys': [u'abcabc/beta'] 
} 

當嘗試使用get_api_key,我得到一個參數驗證錯誤:

get_api_key_response = client.get_api_key(
    apiKey='585yw0f1tk', 
    includeValue=True 
) 

Unknown parameter in input: "includeValue", must be one of: apiKey: ParamValidationError 

是對AWS boto3模塊修改排除value鍵?如何返回生成的API密鑰?

+0

它會拋出什麼錯誤? – ydaetskcoR

+0

這不是一個錯誤,只有在AWS Lambda實現的字典中才會返回鍵值'',否則將返回該值。 –

+1

那麼'api_key_response'在這一點上看起來像什麼呢?嘗試打印 – ydaetskcoR

回答

2

這裏的區別可歸因於您的Lambda環境中的AWS SDK的不同版本與您的開發環境。

在較新版本的SDK中,作爲安全措施,某些響應中省略了API密鑰值。您可以通過單獨調用get_api_key來檢索API Key值,其中includeValue = True

+0

我嘗試使用'get_api_key'與'includeValue = True'參數和'includeValue'參數驗證失敗。見OP。 –

+0

我應該注意到,我在我的開發環境上使用boto3 v1.3.1,這與AWS實現相同。 –

+0

我建議在您的Lambda函數中捆綁最新版本的SDK(1.4)。 Lambda在SDK版本上往往落後。請參閱http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html –