Home > Back-end >  Need to create a snapshot of a volume using python3 and boto3 for a specific region
Need to create a snapshot of a volume using python3 and boto3 for a specific region

Time:05-17

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?

CodePudding user response:

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

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

CodePudding user response:

After doing more research I could see that the below script worked fine for me.

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!')
  • Related