rea*_*dev 7 amazon-ec2 amazon-web-services amazon-vpc aws-lambda aws-secrets-manager
我有一个需要与私有 VPC 中的 EC2 实例“本地”通信的 lambda。API 密钥存储在 Secrets Manager 中。
使用 Secrets Manager 提供的默认代码和必要的 IAM 角色,我可以从我的 Lambda 中的 Secrets Manager 读取 API 密钥:
# Use this code snippet in your app.
# If you need more information about configurations or implementing the sample code, visit the AWS docs:
# https://aws.amazon.com/developers/getting-started/python/
import boto3
import base64
from botocore.exceptions import ClientError
def get_secret():
secret_name = "MYSECRET"
region_name = "ap-southeast-2"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
... # Default error handling..
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
return secret
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
return decoded_binary_secret
def lambda_handler(event, context):
secrt = get_secret()
return {
'statusCode': 200,
"headers": {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
'body': secrt
}
Run Code Online (Sandbox Code Playgroud)
此 Lambda 能够从 Secrets Manager 成功检索和打印 API 密钥。
为了与 EC2 实例通信,我有一个带有辅助层的 Lambda 和一些简单的测试代码:
import apihelper
import json
def lambda_handler(event, context):
conn = apihelper.getConnection('API KEY')
return {
'statusCode': 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
'body': json.dumps(conn.listProducts())
}
Run Code Online (Sandbox Code Playgroud)
此 lambda 位于 VPC 子网中,并具有与 EC2 实例通信所需的安全组规则。硬编码API KEY它成功地从 EC2 实例返回预期数据。
当我尝试组合它们以便 API 密钥不是硬编码时,Lambda 不再有效。没有错误消息只是超时。
我试过了:
allow all在安全组上放置入站和出站规则我想我已经将范围缩小到 VPC。在我将它放入 VPC 之前,第一个打印出秘密的 Lambda 可以完美运行。但我不知道在哪里查看或如何配置它以允许 Lambda 与 VPC 内的 EC2 以及 Secrets Manager 进行通信。
Mar*_*cin 10
没有错误消息只是超时。
不幸的是,VPC中的 lambda 函数没有互联网访问权限,也没有公共 IP。从文档:
将函数连接到公共子网不会为其提供Internet 访问权限或公共 IP 地址。
因此,当您使用boto3:
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
Run Code Online (Sandbox Code Playgroud)
连接到Secrets Manager它超时,因为boto3无法Secrets Manager从 VPC连接到管理器。
有两种方法可以纠正这种情况:
将您的函数放在私有子网中,并使用NAT 网关/实例和正确配置的路由表来提供 Internet 访问,并因此提供Secrets Manager.
在私有子网中为 Secrets Manager设置VPC 接口终端节点。这样,您的 lambda 函数将能够连接到Secrets Manager使用端点,而无需互联网。
| 归档时间: |
|
| 查看次数: |
4423 次 |
| 最近记录: |