当我将python 2.7版本更新为python 3.8时,我的AMI脚本无法正常工作,在lambda部分下的aws控制台上测试代码后,显示2.7版本和3.8版本之间的版本不匹配。有人可以帮助我解决这个问题吗?
谢谢
import boto3
import collections
import datetime
import time
import sys
ec2 = boto3.client('ec2')
sts = boto3.client('sts')
drec2 = boto3.client('ec2', region_name='eu-west-1')
dr = boto3.resource('ec2')
awsaccountid = sts.get_caller_identity().get('Account')
images = dr.images.filter(Owners=[awsaccountid])
date = datetime.datetime.now()
date_fmt = date.strftime('%Y-%m-%d')
time_fmt = date.strftime('%Y-%m-%d--%H-%M-%S')
def lambda_handler(event, context):
def get_instance_name(itags):
instancename = ''
if itags is None:
instancename = ''
else:
for tags in itags:
if tags["Key"] == 'Name':
instancename = tags["Value"]
return instancename
# Check for the availability of the image
def is_image_available(image_id):
try:
available = 0
while available == 0:
print("Not created yet.. Gonna sleep for 10 seconds")
time.sleep(10)
image = ec2.describe_images(ImageIds=[image_id])
if image['Images'][0]['State'] == 'available':
available = 1
if available == 1:
print("Image is now available for use.")
return True
except Exception,e:
print e
reservations = ec2.describe_instances(
Filters=[
{'Name': 'tag:Backup', 'Values': ['yes', 'Yes']},
]
).get(
'Reservations', []
)
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
for instance in instances:
try:
retention_days = 2
except IndexError:
retention_days = 7
finally:
for image in images:
#today_time = datetime.datetime.now().strftime('%m-%d-%Y')
#today_fmt = today_time.strftime('%m-%d-%Y')
#today_date = time.strptime(today_time, '%m-%d-%Y')
aminame = get_instance_name(instance['Tags']) + "-" + instance['InstanceId'] + "-On-" + date_fmt
if image.name == aminame:
if is_image_available(image.id):
dramiid = drec2.copy_image(SourceRegion='us-east-1', SourceImageId=image.id,
Name="DR-" + get_instance_name(instance['Tags']) + "-" +
`enter code here` instance[
'InstanceId'] + "-On-" + date_fmt,
Description="Lambda created AMI of instance " + instance[
'InstanceId'] + " On " + time_fmt)
print("Retaining DR AMI %s of instance %s for %d days" % (
dramiid['ImageId'],
instance['InstanceId'],
retention_days,
))
# to_tag[retention_days].append(dramiid['ImageId'])
# for retention_days in to_tag.keys():
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%m-%d-%Y')
print("Will delete the DR AMI in %d days on %s" % (retention_days, delete_fmt))
# break
drec2.create_tags(
Resources=[dramiid['ImageId']],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
]
)
出现以下错误:
Function Logs:
START
RequestId: 1f9263c7-9736-4b31-934d-719d38f8fdba
Version: $LATEST
[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 52)
Traceback (most recent call last): File "/var/task/lambda_function.py"
Line 52 except Exception,e:END
RequestId: 1f9263c7-9736-4b31-934d-719d38f8fdba
有人知道如何解决这个问题吗?
答案 0 :(得分:0)
在python3中运行脚本时,应该进行一些语法更改。
例如
in python 3 , you say `print('value')` with brackets.
in python 2, you say `print "hello"`
in python 3, you say `except Exception as e`
in python 2, you can say `except Exception, e`
此处:
import boto3
import collections
import datetime
import time
import sys
ec2 = boto3.client('ec2')
sts = boto3.client('sts')
drec2 = boto3.client('ec2', region_name='eu-west-1')
dr = boto3.resource('ec2')
awsaccountid = sts.get_caller_identity().get('Account')
images = dr.images.filter(Owners=[awsaccountid])
date = datetime.datetime.now()
date_fmt = date.strftime('%Y-%m-%d')
time_fmt = date.strftime('%Y-%m-%d--%H-%M-%S')
def lambda_handler(event, context):
def get_instance_name(itags):
instancename = ''
if itags is None:
instancename = ''
else:
for tags in itags:
if tags["Key"] == 'Name':
instancename = tags["Value"]
return instancename
# Check for the availability of the image
def is_image_available(image_id):
try:
available = 0
while available == 0:
print("Not created yet.. Gonna sleep for 10 seconds")
time.sleep(10)
image = ec2.describe_images(ImageIds=[image_id])
if image['Images'][0]['State'] == 'available':
available = 1
if available == 1:
print("Image is now available for use.")
return True
except Exception as e:
print(e)
reservations = ec2.describe_instances(
Filters=[
{'Name': 'tag:Backup', 'Values': ['yes', 'Yes']},
]
).get(
'Reservations', []
)
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
for instance in instances:
try:
retention_days = 2
except IndexError:
retention_days = 7
finally:
for image in images:
#today_time = datetime.datetime.now().strftime('%m-%d-%Y')
#today_fmt = today_time.strftime('%m-%d-%Y')
#today_date = time.strptime(today_time, '%m-%d-%Y')
aminame = get_instance_name(instance['Tags']) + "-" + instance['InstanceId'] + "-On-" + date_fmt
if image.name == aminame:
if is_image_available(image.id):
dramiid = drec2.copy_image(SourceRegion='us-east-1', SourceImageId=image.id,
Name="DR-" + get_instance_name(instance['Tags']) + "-" +
'enter code here' + instance[
'InstanceId'] + "-On-" + date_fmt,
Description="Lambda created AMI of instance " + instance[
'InstanceId'] + " On " + time_fmt)
print("Retaining DR AMI %s of instance %s for %d days" % (
dramiid['ImageId'],
instance['InstanceId'],
retention_days,
))
# to_tag[retention_days].append(dramiid['ImageId'])
# for retention_days in to_tag.keys():
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%m-%d-%Y')
print("Will delete the DR AMI in %d days on %s" % (retention_days, delete_fmt))
# break
drec2.create_tags(
Resources=[dramiid['ImageId']],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
]
)