Boto:从配置中动态获取Python代码中的aws_access_key_id和aws_secret_access_key?

问题描述 投票:2回答:3

我将aws_access_key_idaws_secret_access_key存储在~/.boto中,并且想知道我是否有办法使用Boto在我的python代码中检索这些值,因为我需要将它们插入到我的SQL语句中以从S3复制CSV文件。

python python-3.x amazon-web-services boto
3个回答
2
投票

这应该工作:

import boto
access_key = boto.config.get_value('Credentials', 'aws_access_key_id')
secret_key = boto.config.get_value('Credentials', 'aws_secret_access_key')

0
投票

如果~/.aws/credentials不起作用,这里有一个帮助,将在boto.config中查看。我没有详细研究它,但有点看起来Boto 2没有看到~/.aws/credentials

def get_aws_credentials():
    # I think this will look in ~/.boto ([Credentials] section)
    aws_access_key_id = boto.config.get_value("Credentials", 'aws_access_key_id')
    aws_secret_access_key = boto.config.get_value("Credentials", 'aws_secret_access_key')

    # I don't think Boto 2 looks in ~/.aws/credentials, so we look
    if aws_access_key_id is None or aws_secret_access_key is None:
        with open(os.path.expanduser("~/.aws/credentials")) as f:
            for line in f:
                try:
                    key, val = line.strip().split('=')
                    if key == 'aws_access_key_id':
                        aws_access_key_id = val
                    elif key == 'aws_secret_access_key':
                        aws_secret_access_key = val
                except ValueError:
                    pass
        return aws_access_key_id, aws_secret_access_key

0
投票

因为aws凭证和boto文件都使用.ini格式,您可以使用ConfigParser解析它们。这是一个解析~/.aws/credentials文件的例子(这是python 2,但应该很容易移植到python 3):

from os.path import expanduser
import ConfigParser

def read_credentials_from_config_section(section_name):
    # parsing ~/.aws/credentials but it's just as easy to parse ~/.boto
    aws_credentials_path = os.path.join(expanduser("~"), '.aws', 'credentials')
    c = ConfigParser.ConfigParser()
    c.read(aws_credentials_path)
    return c.get(section_name, 'aws_access_key_id'), c.get(section_name, 'aws_secret_access_key')

使用途径:

k, s = read_credentials_from_config_section('default')

如果要使用~/.boto文件,请修改上面的代码以读取~/.boto文件,并调整其命名约定 - 代码非常相似。

另一种读取~/.aws/credentials文件的方法(假设您安装了awscli)是向aws cli发出外壳并让它处理细节。但这要慢很多(在我的机器上运行需要大约1.5秒,这对很多用例来说都是不可接受的)。

import subprocess
print subprocess.check_output(['aws', 'configure', 'get', 'aws_access_key_id', '--profile', aws_profile_name])
print subprocess.check_output(['aws', 'configure', 'get', 'aws_secret_access_key', '--profile', aws_profile_name])
© www.soinside.com 2019 - 2024. All rights reserved.