2016-11-28 132 views
0

這是我通過AWS Lambda創建快照的代碼。通過AWS創建包含描述的快照Lambda

import boto3 
import collections 
import datetime 

ec = boto3.client('ec2') 

def lambda_handler(event, context): 
    reservations = ec.describe_instances(
     Filters=[ 
      {'Name': 'tag-key', 'Values': ['Backup', 'backup']}, 
     ] 
    ).get(
     'Reservations', [] 
    ) 

    instances = sum(
     [ 
      [i for i in r['Instances']] 
      for r in reservations 
     ], []) 

    print "Found %d instances that need backing up" % len(instances) 

    to_tag = collections.defaultdict(list) 

    for instance in instances: 
     try: 
      retention_days = [ 
       int(t.get('Value')) for t in instance['Tags'] 
       if t['Key'] == 'Retention'][0] 
     except IndexError: 
      retention_days = 14 

     for volume in ec.volumes.filter(Filters=[ 
      {'Name': 'attachment.instance-id', 'Values': [instance.id]} 
     ]): 
      description = 'scheduled-%s.%s-%s' % (instance_name, volume.volume_id, datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) 

      print 'description: %s' % (description) 

     for dev in instance['BlockDeviceMappings']: 
      if dev.get('Ebs', None) is None: 
       continue 
      vol_id = dev['Ebs']['VolumeId'] 
      print "Found EBS volume %s on instance %s" % (
      vol_id, instance['InstanceId']) 

      snap = ec.create_snapshot(
       VolumeId=vol_id, 
      ) 

      to_tag[retention_days].append(snap['SnapshotId']) 

      print "Retaining snapshot %s of volume %s from instance %s for %d days" % (
       snap['SnapshotId'], 
       vol_id, 
       instance['InstanceId'], 
       retention_days, 
      ) 


    for retention_days in to_tag.keys(): 
     delete_date = datetime.date.today() +  datetime.timedelta(days=retention_days) 
     delete_fmt = delete_date.strftime('%Y-%m-%d') 
     print "Will delete %d snapshots on %s" % (len(to_tag[retention_days]), delete_fmt) 
     ec.create_tags(
      Resources=to_tag[retention_days], 
      Tags=[ 
       {'Key': 'DeleteOn', 'Value': delete_fmt}, 
      ] 
     ) 

我得到以下響應:

'EC2' object has no attribute 'volumes': AttributeError 
Traceback (most recent call last): 
    File "/var/task/lambda_function.py", line 34, in lambda_handler 
    for volume in ec.volumes.filter(Filters=[ 
AttributeError: 'EC2' object has no attribute 'volumes' 

Whgen我用EC = boto3.resource( 'EC2')代替EC = boto3.client( 'EC2' ),我得到的描述,但其他一些如describe_instances不起作用

那麼,請告訴我是什麼替代boto3.client( 'EC2')

回答

1

boto3.resource是低電平boto3.client你混合兩者的抽象。如果您使用client.describe_instances,則使用client.describe_volumes

如果要使用resource.volumes,請使用resource.instances。由於其強大的過濾和抽象,我更喜歡resource.instances。如果您使用資源並且由於某種原因想要訪問底層客戶端,則可以使用meta獲取底層客戶端。

ec2 = boto3.resource('ec2') 
client = ec2.meta.client 

避免處理預訂等,請使用resource.instances。如果你是谷歌的話,有很多例子。幾行代碼,非常可讀。

+0

謝謝你的寶貴意見。我現在要做的就是向快照添加一個描述。您能否告訴我如何在不更改代碼的情況下添加該代碼? – prudhvi