简体   繁体   中英

Python boto3 filtering RDS tag

I have created a python script to get my AWS RDS instances Endpoint.

#!/usr/bin/env python
import boto3`
rds = boto3.client('rds')
try:
# get all of the db instances
    dbs = rds.describe_db_instances()
for db in dbs['DBInstances']:
print ("%s@%s:%s %s") % (
        db['MasterUsername'],
        db['Endpoint']['Address'],
        db['Endpoint']['Port'],
        db['DBInstanceStatus'])
except Exception as error:
print error

It connects to RDS and I see data in dbs variable.

{u'DBInstances': [{u'PubliclyAccessible': False, u'MasterUsername':     'dbadmin', u'MonitoringInterval': 0, u'LicenseModel': 'general-public-license', ...

Unfortunately, I got en error:

File "rds2.py", line 7
for db in dbs['DBInstances']:
  ^
SyntaxError: invalid syntax`

Could you tell me whats wrong? My goal is to get Endpoint of RDS with TAG (Name = APP1).

Thanks.

Like helloV pointed out, your indentation is incorrect. If you want to find the DB by tag lookup, you might want to use this:

#!/usr/bin/env python
import boto3

rds = boto3.client('rds')
dbs = rds.describe_db_instances()


def get_tags_for_db(db):
    instance_arn = db['DBInstanceArn']
    instance_tags = rds.list_tags_for_resource(ResourceName=instance_arn)
    return instance_tags['TagList']


target_db = None

for db in dbs['DBInstances']:
    print ("%s@%s:%s %s") % (
        db['MasterUsername'],
        db['Endpoint']['Address'],
        db['Endpoint']['Port'],
        db['DBInstanceStatus'])

    db_tags = get_tags_for_db(db)
    tag = next(iter(filter(lambda tag: tag['Key'] == 'Name' and tag['Value'] == 'APP1', db_tags)), None)
    if tag:
        target_db = db
        break

print(target_db)

The DB Instance you're looking for will be stored as target_db . For more information about listing tags for a DB instance, see this .

It is a problem with your Python indentation.

import boto3
rds = boto3.client('rds')
try:
# get all of the db instances
    dbs = rds.describe_db_instances()
    for db in dbs['DBInstances']:
        print ("%s@%s:%s %s") % (
            db['MasterUsername'],
            db['Endpoint']['Address'],
            db['Endpoint']['Port'],
            db['DBInstanceStatus'])
except Exception as error:
    print error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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