[英]Set IAM role to run AWS CLI Python subprocess in AWS Lambda
我创建了一个包含 AWS CLI 的 Lambda 层,因为aws sync
命令在 boto3 中不可用,并且副本 function 速度太慢,无法在达到最大 Lambda 超时之前完成 s3 到 s3 的传输。
我可以运行 AWS CLI 命令(ls、sync 等)作为 Lambda 的执行角色。我需要从 Lambda 运行aws sync
以作为有权访问源和目标存储桶的不同 IAM 用户同步两个 s3 存储桶。
如何配置 CLI 以特定用户身份运行?
下面的命令在本地成功配置了用户,但是当使用 Lambda 中的子进程 function 运行时,get-caller-identity 的 output 仍然是 Lambda 角色的 ARN。
/opt/aws configure set aws_access_key_id <id>
/opt/aws configure set aws_secret_access_key <key>
/opt/aws sts get-caller-identity
为了运行 configure set id 和 key 命令,我必须设置一个环境变量以绕过只读的 Lambda 文件系统以将凭据写入 /temp 目录。
环境变量:
key: HOME
value: /tmp
注意:有一个填充的凭据文件写入:/temp/.aws/credentials
Lambda:
import logging
import subprocess
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def run_command(command):
command_list = command.split(' ')
try:
logger.info("Running shell command: \"{}\"".format(command))
result = subprocess.run(command_list, stdout=subprocess.PIPE);
logger.info("Command output:\n---\n{}\n---".format(result.stdout.decode('UTF-8')))
except Exception as e:
logger.error("Exception: {}".format(e))
return False
return True
def lambda_handler(event, context):
run_command('/opt/aws configure set aws_access_key_id <id>')
run_command('/opt/aws configure set aws_secret_access_key <key>')
# not set to new IAM user
run_command('/opt/aws sts get-caller-identity')
谢谢阅读!
将 IAM 访问凭证作为环境变量传递给子进程,而不是尝试运行aws configure
:
result = subprocess.run(command_list, stdout=subprocess.PIPE, env={
'AWS_ACCESS_KEY_ID': <id>,
'AWS_SECRET_ACCESS_KEY': <id>,
});
解释:
Lambda 运行时环境为其使用的角色设置了环境变量, 记录在此处,并且这些环境变量优先于您尝试通过aws configure
命令执行的任何操作。 因此,解决这个问题的最简单方法是覆盖通过env
参数传递给子进程的环境变量。
我认为您对aws configure
的调用无论如何都不起作用,因为所做的只是写入~/.aws/credentials
文件,并且该文件在 AWS Lambda 环境中不可写,只有/tmp
是可写的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.