Python IndentationError-Lambda备份

时间:2018-12-12 10:35:48

标签: python-2.7

我通过http://pep8online.com运行时,我的AWS备份脚本抛出了缩进错误。

我遍历了代码,并用空格替换了所有标签,将所有空格都替换了标签,等等。但是错误仍然存​​在。

确切的错误在脚本的第23行,显示为“ IndentationError:unindent与任何外部缩进级别都不匹配”。

但是,如果我将上面的缩进更改为2个空格,则在第23行会收到一个不同的错误“缩进不是4的倍数”,然后在整个脚本中将所有错误标记为正在运行。

我正在使用的代码如下。

import boto3
import collections
import datetime
import time
import sys


today = datetime.date.today()
today_string = today.strftime('%Y/%m/%d')


# Set the number of days before snapshot deletion (10).
deletion_date = today - datetime.timedelta(days=10)
deletion_date_string = deletion_date.strftime('%Y/%m/%d')


ec2 = boto3.client('ec2')
regions = ec2.describe_regions().get('Regions', [])
all_regions = [region['RegionName'] for region in regions]


def lambda_handler(event, context):
    snapshot_counter = 0
    snap_size_counter = 0
    deletion_counter = 0
    deleted_size_counter = 0

  for region_name in all_regions:
      ec2 = boto3.resource('ec2', region_name=region_name)

      # We only want to look through instances with the following tag key value pair: auto_snapshot : true
      instances = ec2.instances.filter(
          Filters=[
              {'Name': 'tag:auto_snapshot', 'Values': ['true']}
                  ]
              )

      volume_ids = []
      for i in instances.all():

          for tag in i.tags:  # Get the name of the instance
              if tag['Key'] == 'Name':
                  name = tag['Value']


          vols = i.volumes.all()  # Iterate through each instances volumes
          for v in vols:
              print('{0} is attached to volume {1}, proceeding to snapshot'.format(name, v.id))
              volume_ids.extend(v.id)
              snapshot = v.create_snapshot(
                  Description = 'AutoSnapshot of {0}, on volume {1} - Created {2}'.format(name, v.id, today_string),
                  )
              snapshot.create_tags(  # Add the following tags to the new snapshot
                  Tags = [
                      {
                          'Key': 'auto_snap',
                          'Value': 'true'
                      },
                      {
                          'Key': 'volume',
                      'Value': v.id
                      },
                      {
                          'Key': 'CreatedOn',
                          'Value': today_string
                      },
                       {
                          'Key': 'Name',
                          'Value': '{} autosnap'.format(name)
                      }
                  ]
              )
              snapshot_counter += 1
              snap_size_counter += snapshot.volume_size

              # Now iterate through snapshots which were made by autosnap
              snapshots = ec2.snapshots.filter(
                  Filters=[
                      {'Name': 'tag:auto_snap', 'Values': ['true']
                      }
                  ]
              )


              for snap in snapshots:
                  can_delete = False
                  for tag in snap.tags: # Use these if statements to get each snapshot's
                                        # created on date, name and auto_snap tag
                      if tag['Key'] == 'CreatedOn':
                          created_on_string = tag['Value']
                      if tag['Key'] == 'auto_snap':
                          if tag['Value'] == 'true':
                              can_delete = True
                      if tag['Key'] == 'Name':
                          name = tag['Value']
                  created_on = datetime.datetime.strptime(created_on_string, '%Y/%m/%d').date()

                  if created_on <= deletion_date and can_delete == True:
                      deleted_size_counter += snap.volume_size
                      snap.delete()
                      deletion_counter += 1

  return 

1 个答案:

答案 0 :(得分:0)

您的代码格式有些错误,我只是在PyCharm中对其进行了格式设置,现在它不报告缩进错误等。请尝试以下操作:

import boto3
import collections
import datetime
import time
import sys


today = datetime.date.today()
today_string = today.strftime('%Y/%m/%d')


# Set the number of days before snapshot deletion (10).
deletion_date = today - datetime.timedelta(days=10)
deletion_date_string = deletion_date.strftime('%Y/%m/%d')


ec2 = boto3.client('ec2')
regions = ec2.describe_regions().get('Regions', [])
all_regions = [region['RegionName'] for region in regions]


def lambda_handler(event, context):
    snapshot_counter = 0
    snap_size_counter = 0
    deletion_counter = 0
    deleted_size_counter = 0

    for region_name in all_regions:
        ec2 = boto3.resource('ec2', region_name=region_name)

      # We only want to look through instances with the following tag key value pair: auto_snapshot : true
        instances = ec2.instances.filter(
              Filters=[
                  {'Name': 'tag:auto_snapshot', 'Values': ['true']}
                      ]
                  )

        volume_ids = []
        for i in instances.all():

            for tag in i.tags:  # Get the name of the instance
                if tag['Key'] == 'Name':
                    name = tag['Value']


            vols = i.volumes.all()  # Iterate through each instances volumes
            for v in vols:
                print('{0} is attached to volume {1}, proceeding to snapshot'.format(name, v.id))
                volume_ids.extend(v.id)
                snapshot = v.create_snapshot(
                  Description = 'AutoSnapshot of {0}, on volume {1} - Created {2}'.format(name, v.id, today_string),
                  )
                snapshot.create_tags(  # Add the following tags to the new snapshot
                  Tags = [
                      {
                          'Key': 'auto_snap',
                          'Value': 'true'
                      },
                      {
                          'Key': 'volume',
                      'Value': v.id
                      },
                      {
                          'Key': 'CreatedOn',
                          'Value': today_string
                      },
                       {
                          'Key': 'Name',
                          'Value': '{} autosnap'.format(name)
                      }
                  ]
                )
                snapshot_counter += 1
                snap_size_counter += snapshot.volume_size

              # Now iterate through snapshots which were made by autosnap
                snapshots = ec2.snapshots.filter(
                  Filters=[
                      {'Name': 'tag:auto_snap', 'Values': ['true']
                      }
                  ]
              )


                for snap in snapshots:
                    can_delete = False
                    for tag in snap.tags: # Use these if statements to get each snapshot's
                                        # created on date, name and auto_snap tag
                        if tag['Key'] == 'CreatedOn':
                            created_on_string = tag['Value']
                        if tag['Key'] == 'auto_snap':
                            if tag['Value'] == 'true':
                                can_delete = True
                        if tag['Key'] == 'Name':
                            name = tag['Value']
                            created_on = datetime.datetime.strptime(created_on_string, '%Y/%m/%d').date()

                            if created_on <= deletion_date and can_delete == True:
                                deleted_size_counter += snap.volume_size
                                snap.delete()
                                deletion_counter += 1

    return

在线上也有一个linter,如果您仅复制并粘贴代码https://pythonbuddy.com/,它会告诉您是否存在类似错误等。终端中也可以使用诸如pylint,flake8等的短绒。