2017-02-28 57 views
0

嗨, 我正在尝试从AWS账户获取所有快照详细信息和卷详细信息。我的代码工作正常,但由于某种原因,我不知道它显示的是'us-east-1'和'ap-southeast-1'区域的快照和音量。不过,我也有其他地区的资源。使用AWS lambda和python sdk获取AWS账户的所有快照和数量详细信息

import xlsxwriter 
import boto3 
import collections 
import datetime 
from time import gmtime, strftime 
import smtplib 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEBase import MIMEBase 
from email.MIMEText import MIMEText 
from email import Encoders 
import os 

#lambda function beginning 
def worker_handler(event, context): 

    date_fmt = strftime("%Y_%m_%d", gmtime()) 
    #Give your file path 
    filepath ='/tmp/CM_AWS_Resources_' + date_fmt + '.xlsx' 
    #Give your filename 
    filename ='CM_AWS_Resources_' + date_fmt + '.xlsx' 
    # xlsx_file = open(filepath,'w+') 
    workbook = xlsxwriter.Workbook(filepath) 
    worksheet1 = workbook.add_worksheet('snapshots') 
    worksheet2 = workbook.add_worksheet('volumes') 

    volumeHeader = ['volume id','snapshot id','creation date','Description','size','Region'] 
    snapshotsHeader=['volume id','state','size','Region'] 
    headVolSize=1 
    row=0 
    col=0 
    while headVolSize <= len(volumeHeader): 
     for i in volumeHeader: 
      worksheet1.write(row,col,i) 
      col+=1 
      headVolSize=headVolSize+1 

    headSnapSize=1 
    row=0 
    col=0 
    while headSnapSize <= len(snapshotsHeader): 
     for i in snapshotsHeader: 
      worksheet2.write(row,col,i) 
      col+=1 
      headSnapSize=headSnapSize+1 

    while headVolSize <= len(volumeHeader): 
     for i in volumeHeader: 
       worksheet1.write(row,col,headVolSize) 
       worksheet1.write(row,col+1,i) 
       row +=1 
       headVolSize=headVolSize+1 
       j=j+1 
    ec = boto3.client('ec2') 
    s3 = boto3.resource('s3') 
    ec2Res = boto3.resource('ec2') 
    regions = ec.describe_regions().get('Regions',[]) 
    for region in regions: 
     reg=region['RegionName'] 
     regname='REGION :' + reg 
     # print regname 
     ec2 = boto3.client('ec2',region_name=reg) 

     snapshots=ec2.describe_snapshots(OwnerIds=['***',],).get('Snapshots',[]) 
     if len(snapshots) >0 : 
      print "snapshots : " + str(len(snapshots)) + " " + reg 
      j=1 
      while j <= len(snapshots): 
       row=0 
       col=0 
       for i in snapshots: 
         # print type(i['StartTime']) 
         date1 = i['StartTime'].strftime('%Y-%m-%d') 
         # print "row : " + str(row) + " col : " + str(col) 
         # print i['VolumeId'] + str(row) + "," + str(col) + " " + i['SnapshotId'] + " " +str(row) + "," + str(col+1) + " " + str(i['StartTime']) + " " + " " +str(row) + "," + str(col+2) + " " + i['Description'] + " " +" " +str(row) + "," + str(col+3) + " " + str(i['VolumeSize']) + " " +str(row) + "," + str(col+4) + " " + reg + " " +str(row) + "," + str(col+5) 
         worksheet1.write(row,col,i['VolumeId']) 
         worksheet1.write(row,col+1,i['SnapshotId']) 
         worksheet1.write(row,col+2,date1) 
         worksheet1.write(row,col+3,i['Description']) 
         worksheet1.write(row,col+4,i['VolumeSize']) 
         worksheet1.write(row,col+5,reg) 
         row +=1 
         j=j+1 
      # else: 
      #  print "do nothing" 
     ec2volumes = ec2.describe_volumes().get('Volumes',[]) 
     if len(ec2volumes) >0 : 
      #if reg=='ap-south-1': 
      print "volumes : " + str(len(ec2volumes)) + " " + reg 
      j=1 
      while j <= len(ec2volumes): 
       row=0 
       col=0 
       for i in ec2volumes: 
         # print type(i['StartTime']) 
         # print "row : " + str(row) + " col : " + str(col) 
         # print i['VolumeId'] + str(row) + "," + str(col) + " " + i['SnapshotId'] + " " +str(row) + "," + str(col+1) + " " + str(i['StartTime']) + " " + " " +str(row) + "," + str(col+2) + " " + i['Description'] + " " +" " +str(row) + "," + str(col+3) + " " + str(i['VolumeSize']) + " " +str(row) + "," + str(col+4) + " " + reg + " " +str(row) + "," + str(col+5) 
         worksheet2.write(row,col,i['VolumeId']) 
         worksheet2.write(row,col+1,i['State']) 
         worksheet2.write(row,col+2,i['Size']) 
         worksheet2.write(row,col+3,reg) 
         row +=1 
         j=j+1 


    workbook.close() 

    ses_user = "***" 
    ses_pwd = "***" 

    def mail(fromadd,to, subject, text, attach): 
     msg = MIMEMultipart() 
     msg['From'] = fromadd 
     msg['To'] = to 
     msg['Subject'] = subject 
     msg.attach(MIMEText(text)) 
     part = MIMEBase('application', 'octet-stream') 
     part.set_payload(open(attach, 'rb').read()) 
     Encoders.encode_base64(part) 
     part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach)) 
     msg.attach(part) 
     mailServer = smtplib.SMTP("email-smtp.us-east-1.amazonaws.com", 587) 
     mailServer.ehlo() 
     mailServer.starttls() 
     mailServer.ehlo() 
     mailServer.login(ses_user, ses_pwd) 
     mailServer.sendmail(fromadd, to, msg.as_string()) 
     # Should be mailServer.quit(), but that crashes... 
     mailServer.close() 

    date_fmt = strftime("%Y_%m_%d", gmtime()) 
    #Give your file path 
    filepath ='/tmp/CM_AWS_Resources_' + date_fmt + '.xlsx' 
    #Give your filename 
    mailTO=['***'] 
    for i in mailTO: 
     mail("***",i,"Details for unimportant snapshot deletion","PFA for the AWS resource of AWS account.",filepath) 

    s3.Object('bucketname', filename).put(Body=open(filepath, 'rb')) 
+0

您是否检查分配给lambda的角色被赋予执行跨区域ec2.describe _ *()的权限。 – mootmoot

回答

0

我发现了我的代码中的错误。在“区域:”区域中,每次行值都更新为1,因此我只获取两个区域值。因此,我为快照循环和音量循环的行和列声明了2个不同的值。因此,我声明的解决方案是rowSnap = 1 rowVol = 1,并且它正常工作。

rowSnap=1 
rowVol=1 
regions = ec.describe_regions().get('Regions',[]) 
for region in regions: 
    reg=region['RegionName'] 
    regname='REGION :' + reg 
    # print regname 
    ec2 = boto3.client('ec2',region_name=reg) 
    snapshots=ec2.describe_snapshots(OwnerIds=['**',],).get('Snapshots',[]) 
    if len(snapshots) >0 : 
     print "snapshots : " + str(len(snapshots)) + " " + reg 
     j=1 
     col=0 
     while j <= len(snapshots): 
      for i in snapshots: 
        date1 = i['StartTime'].strftime('%Y-%m-%d') 
        worksheet1.write(rowSnap,col,i['VolumeId']) 
        worksheet1.write(rowSnap,col+1,i['SnapshotId']) 
        worksheet1.write(rowSnap,col+2,date1) 
        worksheet1.write(rowSnap,col+3,i['Description']) 
        worksheet1.write(rowSnap,col+4,i['VolumeSize']) 
        worksheet1.write(rowSnap,col+5,reg) 
        rowSnap +=1 
        j=j+1 
    ec2volumes = ec2.describe_volumes().get('Volumes',[]) 
    if len(ec2volumes) >0 : 
     #if reg=='ap-south-1': 
     print "volumes : " + str(len(ec2volumes)) + " " + reg 
     j=1 
     col=0 
     while j <= len(ec2volumes): 
      # row=0 
      # col=0 
      for i in ec2volumes: 
        worksheet2.write(rowVol,col,i['VolumeId']) 
        worksheet2.write(rowVol,col+1,i['State']) 
        worksheet2.write(rowVol,col+2,i['Size']) 
        worksheet2.write(rowVol,col+3,reg) 
        rowVol +=1 
        j=j+1 


workbook.close() 
相关问题