繁体   English   中英

为boto3设置默认设置以外的自定义boto配置文件

[英]set custom boto configuration file other than default for boto3

我没有使用boto3设置自定义配置文件位置的任何选项。 我可以从默认位置使用凭据。

我的用例是,有不同的IAM用户,并且具有不同的凭据集,因此每个人都应该能够使用自己的凭据,而无需更改默认配置。

有任何想法吗?

这是绝对可行的。 您可以通过分配一些通过boto3.Session对象传递的关键字参数来实现此目标,例如,

import boto3
session = boto3.Session(
    aws_access_key_id="AAAA",
    aws_secret_access_key="BBBBB",
    region_name="mordor"
)

然后只需正常使用会话对象即可:

s3_object = session.resource('s3') # or whatever

因此,您所需要做的就是用所需的凭据(从您的自定义配置文件填充)填充某些python数据结构,并将其传递给该boto3.Session对象。

我相信这会有所帮助: http : //boto.cloudhackers.com/en/latest/boto_config_tut.html#credentials

您可以为不同的用户设置不同的凭据。

只需使用python模块configparser

示例将显示检查RDS实例的状态并将您的AWS凭证文件存储在它将运行的任何位置。

import configparser
import boto3

class CheckStatus():

    rds_instance_name = 'rds_instnace_name'
    aws_config_file = 'aws_config.ini'

    def __init__(self, aws_config):

        self.aws_config = aws_config
        self.client = boto3.client('rds', region_name=self.aws_config['default']['region'],
                                   aws_access_key_id=self.aws_config['default']['aws_access_key_id'],
                                   aws_secret_access_key=self.aws_config['default']['aws_secret_access_key'])

    def check_rds_status(self):
        current_status = None

        response = self.client.describe_db_instances(
            DBInstanceIdentifier=self.rds_instance_name)
        current_status = response['DBInstances'][0]['DBInstanceStatus']
        print(current_status)


def get_config():
    aws_config = configparser.ConfigParser()
    aws_config.read(CheckStatus.aws_config_file)
    return aws_config

obj = CheckStatus(get_config())

obj.check_rds_status()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM