get_ebs_volume_names - robjcook/sync GitHub Wiki

import boto3

def get_ebs_volume_names_ordered(volume_ids):
    """
    Retrieves the 'Name' tag for a list of EBS volume IDs, maintaining the input order.

    Args:
        volume_ids (list): A list of EBS volume IDs (strings).

    Returns:
        list: A list of tuples, where each tuple contains (volume_id, name_tag).
              The order of the tuples matches the order of the input volume_ids.
              If a volume doesn't have a 'Name' tag, its name_tag will be None.
    """
    ec2_client = boto3.client('ec2')
    # Use a dictionary to quickly look up volume names by ID
    volume_names_map = {}
    ordered_results = []

    try:
        if not volume_ids:
            return [] # Return an empty list if no IDs are provided

        response = ec2_client.describe_volumes(VolumeIds=volume_ids)

        for volume in response['Volumes']:
            volume_id = volume['VolumeId']
            name_tag = None
            for tag in volume.get('Tags', []):
                if tag['Key'] == 'Name':
                    name_tag = tag['Value']
                    break
            volume_names_map[volume_id] = name_tag

        # Now, iterate through the original volume_ids list to maintain order
        for vol_id in volume_ids:
            # Get the name from the map, default to None if not found (e.g., invalid ID)
            name = volume_names_map.get(vol_id, None)
            ordered_results.append((vol_id, name))

    except ec2_client.exceptions.ClientError as e:
        print(f"Error describing volumes: {e}")
        # Depending on your error handling strategy, you might want to return
        # an empty list or a partially populated list here.
        # For simplicity, returning an empty list on error.
        return []
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return []

    return ordered_results

if __name__ == "__main__":
    # Replace with your actual list of EBS volume IDs
    my_volume_ids = [
        'vol-0abcdef1234567890',
        'vol-0fedcba9876543210',
        'vol-0123456789abcdef',
        'vol-0987654321fedcba', # Example of a volume that might not have a 'Name' tag
        'vol-xxxxxxxxxxxxxxxxx' # Example of a non-existent or invalid ID
    ]

    ordered_volume_names = get_ebs_volume_names_ordered(my_volume_ids)

    if ordered_volume_names:
        print("EBS Volume Names (Ordered by Input List):")
        for volume_id, name in ordered_volume_names:
            if name:
                print(f"  Volume ID: {volume_id}, Name: {name}")
            else:
                print(f"  Volume ID: {volume_id}, Name: (No 'Name' tag or Invalid ID)")
    else:
        print("No volume names retrieved or an error occurred. Check for errors above.")