2017-02-28 1 views
0

Bonjour, J'essaie d'obtenir tous les détails d'instantanés et de volumes à partir du compte AWS. Mon code fonctionne parfaitement, mais je ne sais pas, pour une raison ou une autre, qu'il montre l'instantané et le volume de la région 'us-east-1' et 'ap-southeast-1'. Cependant, j'ai des ressources disponibles dans d'autres régions également.Obtention de tous les détails d'instantané et de volume du compte AWS à l'aide d'AWS lambda et python sdk

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

avez-vous vérifié? Les rôles assignés à lambda ont le droit d'exécuter la région croisée ec2.describe _ *(). – mootmoot

Répondre

0

J'ai découvert l'erreur dans mon code. La valeur de ligne Everytime a été mise à jour à 1 dans la section "pour la région dans les régions:" et, par conséquent, je n'obtenais que deux valeurs de région. J'ai donc déclaré 2 valeurs différentes pour la ligne et la colonne de la boucle d'instantané et de la boucle de volume.Ainsi, la solution a été déclarée rowSnap = 1 rowVol = 1 séparément et cela a fonctionné correctement.

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()