如何使boto3显示_all_ RDS实例?

时间:2019-04-26 20:01:12

标签: amazon-web-services amazon-rds boto3

尝试使用boto3获取所有 RDS实例-不会返回所有RDS实例。

当我查看俄勒冈州(us-west-2)的RDS实例时,会看到以下内容:

RDS instances in Oregon

但是,如果我运行下面的Python3脚本,我只会得到一个结果:

$ python3 ./stackoverflow.py 

RDS instances in Oregon
------------------------------
aurora-5-7-yasmin.cazdggrmkpt1.us-west-2.rds.amazonaws.com qa test db.t2.small aurora-5-7-yasmin
$ 

您能建议一种使boto3显示所有 RDS实例的方法吗?


$ cat ./stackoverflow.py 
import collections
import boto3
import datetime
import pygsheets

REGIONS = ('us-west-2',)
REGIONS_H = ('Oregon',)

currentDT = str(datetime.datetime.now())


def create_spreadsheet(outh_file, spreadsheet_name = "AWS usage"):
    client = pygsheets.authorize(outh_file=outh_file, outh_nonlocal=True)
    client.list_ssheets(parent_id=None)
    spread_sheet = client.create(spreadsheet_name)
    return spread_sheet


def rds_worksheet_creation(spread_sheet):
    for i in range(len(REGIONS)):
        region = REGIONS[i]
        region_h = REGIONS_H[i]
        print()
        print("{} instances in {}".format("RDS", region_h))
        print("------------------------------")

        client = boto3.client('rds', region_name=region)
        db_instances = client.describe_db_instances()
        for i in range(len(db_instances)):
            j = i - 1
            try:
                DBName = db_instances['DBInstances'][j]['DBName']
                MasterUsername = db_instances['DBInstances'][0]['MasterUsername']
                DBInstanceClass = db_instances['DBInstances'][0]['DBInstanceClass']
                DBInstanceIdentifier = db_instances['DBInstances'][0]['DBInstanceIdentifier']
                Endpoint = db_instances['DBInstances'][0]['Endpoint']
                Address = db_instances['DBInstances'][0]['Endpoint']['Address']
                print("{} {} {} {} {}".format(Address, MasterUsername, DBName, DBInstanceClass,
                DBInstanceIdentifier))
            except KeyError:
                continue


if __name__ == "__main__":
    spread_sheet = create_spreadsheet(spreadsheet_name = "AWS usage", outh_file = '../client_secret.json')
    spread_sheet.link(syncToCloud=False)
    rds_worksheet_creation(spread_sheet)

$ cat ../client_secret.json 
{"installed":{"client_id":"362799999999-uml0m2XX4v999999mr2s03XX9g8l9odi.apps.googleusercontent.com","project_id":"amiable-shuttle-198516","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"XXXXxQH434Qg-xxxx99_n0vW","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
$ 

编辑1:

在Michael的评论之后,我将脚本更改为以下内容,但是即使出现了另一条相关的代码行,大多数RDS实例仍未返回:

$ python3 ./stackoverflow.py 

RDS instances in Oregon
------------------------------
aurora-5-7-yasmin.cazdggrmkpt1.us-west-2.rds.amazonaws.com qa +++ DBName gave KeyError +++ db.t2.small aurora-5-7-yasmin
aurora-5-7-yasmin.cazdggrmkpt1.us-west-2.rds.amazonaws.com qa test db.t2.small aurora-5-7-yasmin
$ 

$ cat ./stackoverflow.py 
import collections
import boto3
import datetime
import pygsheets

REGIONS = ('us-west-2',)
REGIONS_H = ('Oregon',)

currentDT = str(datetime.datetime.now())


def create_spreadsheet(outh_file, spreadsheet_name = "AWS usage"):
    client = pygsheets.authorize(outh_file=outh_file, outh_nonlocal=True)
    client.list_ssheets(parent_id=None)
    spread_sheet = client.create(spreadsheet_name)
    return spread_sheet


def rds_worksheet_creation(spread_sheet):
    for i in range(len(REGIONS)):
        region = REGIONS[i]
        region_h = REGIONS_H[i]
        print()
        print("{} instances in {}".format("RDS", region_h))
        print("------------------------------")

        client = boto3.client('rds', region_name=region)
        db_instances = client.describe_db_instances()
        for i in range(len(db_instances)):
            j = i - 1
            try:
                DBName = db_instances['DBInstances'][j]['DBName']
            except KeyError:
                DBName = "+++ DBName gave KeyError +++"
            MasterUsername = db_instances['DBInstances'][0]['MasterUsername']
            DBInstanceClass = db_instances['DBInstances'][0]['DBInstanceClass']
            DBInstanceIdentifier = db_instances['DBInstances'][0]['DBInstanceIdentifier']
            Endpoint = db_instances['DBInstances'][0]['Endpoint']
            Address = db_instances['DBInstances'][0]['Endpoint']['Address']
            print("{} {} {} {} {}".format(Address, MasterUsername, DBName, DBInstanceClass,
            DBInstanceIdentifier))


if __name__ == "__main__":
    spread_sheet = create_spreadsheet(spreadsheet_name = "AWS usage", outh_file = '../client_secret.json')
    spread_sheet.link(syncToCloud=False)
    rds_worksheet_creation(spread_sheet)

4 个答案:

答案 0 :(得分:3)

由于fordb_instances类型,因此您的dict循环范围的值为2。

代替

for i in range(len(db_instances)):

应该是

for i in range(len(db_instances['DBInstances'])):

其中给出list类型和正确的长度以迭代循环。

答案 1 :(得分:2)

仅供参考,在这种情况下,更Pythonic的循环方式是:

for instance in db_instances['DBInstances']:
    MasterUsername = instance['MasterUsername']
    DBInstanceClass = instance['DBInstanceClass']
    etc.

这避免了使用i型迭代器。

答案 2 :(得分:2)

您的原始代码有错误,但是如果您希望此代码可扩展到大量实例(不太可能需要此实例),则需要使用以下代码:

import boto3
available_regions = boto3.Session().get_available_regions('rds')

for region in available_regions:
    rds = boto3.client('rds', region_name=region)
    paginator = rds.get_paginator('describe_db_instances').paginate()
    for page in paginator:
        for dbinstance in page['DBInstances']:
            print("{DBInstanceClass}".format(**dbinstance))

如果您知道每个区域的实例少于100个,则可以摆脱分页器,而只需使用第一个循环:

for region in available_regions:
    rds = boto3.client('rds', region_name=region)
    for dbinstance in rds.describe_db_instances():
        print("{DBInstanceClass}".format(**dbinstance))

此外,您可以提供一个简单的

dbinstance.get('DBName', 'No Name Set')

而不是在KeyError周围除外。

答案 3 :(得分:0)

此代码将列出该帐户中存在的所有RDS实例

尝试使用此100%工作代码

#!/usr/bin/env python
import boto3
client = boto3.client('rds')
response = client.describe_db_instances()
x=',';
for r in response['DBInstances']:
   db_name = r['DBName']
   db_instance_name = r['DBInstanceIdentifier']
   db_type = r['DBInstanceClass']
   db_storage = r['AllocatedStorage']
   db_engine = r['Engine']
   print db_instance_name,x,db_type,x,db_storage,x,db_engine