簡體   English   中英

如何讓 boto3 顯示 _all_ RDS 實例?

[英]How to get boto3 to display _all_ RDS instances?

嘗試使用boto3獲取所有RDS 實例- 不會返回所有 RDS 實例。

當我查看俄勒岡 (us-west-2) 的 RDS 實例時,我看到以下內容:

俄勒岡州的 RDS 實例

但是,如果我運行下面的 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:

按照邁克爾的評論,我將腳本更改為以下內容,但即使出現了另一行相關的行,但大多數 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)

您的原始代碼中有錯誤,但如果您希望此代碼擴展到大量實例(您不太可能需要它),那么您將需要使用以下內容:

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 周圍排除。

由於db_instancesdict類型,您的for循環范圍的值為 2。

代替

for i in range(len(db_instances)):

它應該是

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

這給出了迭代循環的list類型和正確的長度。

此代碼將列出帳戶中存在的所有 RDS 實例

試試這個 100% 工作代碼

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

僅供參考,在這種情況下,更 Pythonic 的循環方式是:

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

這避免了對i類型迭代器的需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM