需要使用python3和boto3为指定区域创建卷的快照



我需要在aws中创建一个区域中存在的所有卷的快照。这个脚本必须能够创建us-east-2区域内所有卷的快照

我已经使用了下面的脚本,但它只拍摄我的默认区域的快照。如何解决这个问题?

import boto3
ec2 = boto3.resource('ec2')
snapshot = ec2.Snapshot('id')
Region='us-east-2'
for vol in ec2.volumes.all():
if Region=='us-east-2':
string=vol.id
ec2.create_snapshot(VolumeId=vol.id,Description=string)
print(vol.id),
print('A snapshot has been created for the following EBS volumes',vol.id)
else:
print('No snapshot has been created for the following EBS volumes',vol.id)

这个脚本只适用于默认区域,但是当我在任何其他区域创建卷时,它不会费心为这些卷拍摄快照。有人能帮帮我吗?

您可以在创建ec2客户端时使用Config指定区域。

参考:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html

在做了更多的研究之后,我可以看到下面的脚本对我来说很好。

import boto3
ec2 = boto3.client('ec2')
region_name='us-east-2'
ec2 = boto3.resource('ec2',region_name)
count=0
for vol in ec2.volumes.all():
count+=1
string=vol.id
ec2.create_snapshot(VolumeId=vol.id,Description=string)
print('A snapshot has been created for the following EBS volumes',vol.id)
if count==0:
print('No snapshot has been created for the following region, cause volume does not exit!')