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 –