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

Need to create a snapshot of a volume using python3 and boto3 for a specific region

我需要为 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)

该脚本仅适用于默认区域,但当我在任何其他区域创建卷时,它不会费心拍摄这些卷的快照。有人可以帮忙吗?

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

参考: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!')