Home > Back-end >  Regarding EC2 volume filtering mechanism using boto3
Regarding EC2 volume filtering mechanism using boto3

Time:10-14

I am trying to filter ebs volumes based on tags, i am planning to delete those volumes whose tag key (Name) does not exist for that particular volume. I tried this script, but this filters the tag Key (Name) only if tag is created for that volume and its value is an empty string. But my requirement is to fetch those volumes where tag Key(Name) is not present for this volume. FYI, there are around 4-5 tags present for those volumes i am trying to delete. Any kind of guidance is highly appreciated.

#Filtering volumes based on tag and status, and deletion
for region in region_list: #list of regions
    to_terminate=[]
    ec2_volume = boto3.resource('ec2',region_name=region)
    #volumes = ec2_volume.volumes.all()
    print(region)
    for volume in ec2_volume.volumes.filter(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                '',
            ]
        },
        {
            'Name': 'status',
            'Values': [
                'available',
            ]
        }
        
    ]
    ):
    
        
        print('Evaluating volume {0}'.format(volume.id))
        print('The number of attachments for this volume is {0}'.format(len(volume.attachments)))
        
        to_terminate.append(volume)
    print(to_terminate)

CodePudding user response:

This should get you started. It's pretty straightforward as the commenter suggested. You'll have to change the logic around as needed.

ec2c = boto3.client('ec2')
response = ec2c.describe_instances()
response['Reservations'][0]['Instances']
for inst in response['Reservations'][0]['Instances']:
    if not inst.get('Tags'):
        print('Instance: {} has no tags'.format(inst['InstanceId']))
    else:
        print('Instance: {} has tags'.format(inst['InstanceId']))
        print(inst.get('Tags'))

CodePudding user response:

Thank you for your answers. I have updated the code and now it seems to be working fine. Updated code:

    available_volumes=[]
    for volume in ec2_volume.volumes.filter(
    Filters=[
        {
            'Name': 'status',
            'Values': [
                'available',
            ]
        }
        
    ]
    ):
        
        available_volumes.append(volume)
    
    tagged_volumes = []
    for volume in ec2_volume.volumes.filter(Filters = [{'Name': 'tag:Name', 'Values':['*']}]):
        tagged_volumes.append(volume)
    #print(tagged_volumes)
    
    untagged_volumes = [available_volumes for available_volumes in available_volumes if available_volumes not in tagged_volumes]
    #untagged_instances = [all_instance for all_instance in all_instances if all_instance not in tagged_instances]
    #print(untagged_volumes)
    
    for volume in untagged_volumes:
        print('Deleting volume {0}'.format(volume.id))
        volume.delete()
  • Related