侧边栏壁纸
博主头像
枕头下放双臭袜子博主等级

今我何功德,曾不事农桑

  • 累计撰写 166 篇文章
  • 累计创建 32 个标签
  • 累计收到 0 条评论
AWS

aws lambda脚本获取rds相关信息

枕头下放双臭袜子
2020-12-02 / 0 评论 / 0 点赞 / 693 阅读 / 0 字 / 正在检测是否收录...
1、lambda脚本

脚本先获取到了RDS的DBInstanceIdentifier,然后根据DBInstanceIdentifier作为参数去获取rds snapshot的相关信息,根据时间筛选出三个月前的写入到CSV文件并上传到特定路径的S3位置下。标签值需要判断Key的值才能获取到相应的Value

① lambda脚本
import boto3
import csv
import io
import datetime
from datetime import datetime as dt

def get_date():
    before_days = 90
    past_date = (datetime.datetime.today() - datetime.timedelta(days=int(before_days))).strftime("%Y-%m-%d")
    return past_date

def getdbinstance():
    client = boto3.client('rds')
    dbInstanceIdentifier_list = []
    response = client.describe_db_instances()
    for n in range(len(response['DBInstances'])):
        dbInstanceIdentifier = response['DBInstances'][n]['DBInstanceIdentifier']
        dbInstanceIdentifier_list.append(dbInstanceIdentifier)
        n = n + 1
    return dbInstanceIdentifier_list


def getdbsnaptshot():
    s3 = boto3.client('s3')
    csvio = io.StringIO()
    writer = csv.writer(csvio)
    writer.writerow([
        'snaptshot_arn',
        'DBInstanceIdentifier',
        'DBSnapshotIdentifier',
        'SnapshotCreateTime',
        'InstanceCreateTime',
        'appenv',
        'bgrp',
        'cmdbid',
        'name',
        'retention',
        'RI',
        'sched',
        'vendor'
    ])
    client = boto3.client('rds')
    dbInstanceIdentifier_list = getdbinstance()
    past_date = dt.strptime(get_date(), "%Y-%m-%d")
    for dbInstanceIdentifier in dbInstanceIdentifier_list:
        response = client.describe_db_snapshots(
            DBInstanceIdentifier=dbInstanceIdentifier,
            SnapshotType='manual',
            Filters=[
                {
                    'Name': 'db-instance-id',
                    'Values': [
                        dbInstanceIdentifier
                    ]
                }
            ]
        )
        # print(response)
        # if判断该字段不为空,否则会出现KeyValue Error的错误
        if response['DBSnapshots']:
            CreationTime = dt.strptime(str(response['DBSnapshots'][0]['SnapshotCreateTime']).split(' ')[0], "%Y-%m-%d")
            if CreationTime < past_date:
                snaptshot_arn = response['DBSnapshots'][0]['DBSnapshotArn']
                DBInstanceIdentifier = response['DBSnapshots'][0]['DBInstanceIdentifier']
                DBSnapshotIdentifier = response['DBSnapshots'][0]['DBSnapshotIdentifier']
                SnapshotCreateTime = response['DBSnapshots'][0]['SnapshotCreateTime']
                InstanceCreateTime = response['DBSnapshots'][0]['InstanceCreateTime']
                appenv = ''
                bgrp = ''
                cmdbid = ''
                name = ''
                retention = ''
                RI = ''
                sched = ''
                vendor = ''
                # tag获取需要判断,且查看返回类型
                for tagList in response['DBSnapshots'][0]['TagList']:
                    if tagList['Key'] == 'appenv':
                        appenv = tagList['Value']
                    elif tagList['Key'] == 'bgrp':
                        bgrp = tagList['Value']
                    elif tagList['Key'] == 'cmdbid':
                        cmdbid = tagList['Value']
                    elif tagList['Key'] == 'name':
                        name = tagList['Value']
                    elif tagList['Key'] == 'retention':
                        retention = tagList['Value']
                    elif tagList['Key'] == 'RI':
                        RI = tagList['Value']
                    elif tagList['Key'] == 'sched':
                        sched = tagList['Value']
                    elif tagList['Key'] == 'vendor':
                        vendor = tagList['Value']
                writer.writerow([
                    snaptshot_arn,
                    DBInstanceIdentifier,
                    DBSnapshotIdentifier,
                    SnapshotCreateTime,
                    InstanceCreateTime,
                    appenv,
                    bgrp,
                    cmdbid,
                    name,
                    retention,
                    RI,
                    sched,
                    vendor
                ])
    s3_key = 'lambda/List_snapshot-RDS/' + str(datetime.datetime.today()).split('-')[0] + '-' + \
         str(datetime.datetime.today()).split('-')[1] + '-' + 'fcchina_rdssnapshotlist.csv'
    s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='fcchinajms',
                  Key=s3_key)


def lambda_handler(event, context):
    # print(getdbinstance())
    getdbsnaptshot()

② 角色权限
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "rds:DescribeDBSnapshots",
                "rds:DescribeDBInstances",
                "logs:GetLogEvents",
                "logs:CreateLogGroup",
                "logs:PutLogEvents",
                "rds:DescribeDBSnapshotAttributes",
                "s3:PutObject"
            ],
            "Resource": "*"
        }
    ]
}
0

评论