Search code examples
python-3.xboto3aws-clisnapshot

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


I am having a need to create snapshot of all volumes present in a region in aws. This script must be able to create snapshot of all the volumes in us-east-2 region

I have used the below script but its only taking snapshot of my default region. How to fix this issue?

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)

The script works fine only for default region but when I create volumes in any other region it does not bother to take snapshot of those volumes. Can someone please help?


Solution

  • You may specify the region in creating ec2 client with Config.

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