【问题标题】:Regarding EC2 volume filtering mechanism using boto3关于使用boto3的EC2卷过滤机制
【发布时间】:2021-12-02 01:01:23
【问题描述】:

我正在尝试根据标签过滤 ebs 卷,我计划删除那些标签键(名称)对于该特定卷不存在的卷。我试过这个脚本,但只有在为该卷创建标签并且它的值为空字符串时才会过滤标签键(名称)。但我的要求是获取该卷不存在标签 Key(Name) 的那些卷。仅供参考,对于我要删除的那些卷,大约有 4-5 个标签。非常感谢任何形式的指导。

#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)

【问题讨论】:

  • 为什么不简单地检索 all 卷,然后使用 Python 检查是否有 Name 标签。如果它存在,那么采取你想要的行动。

标签: python amazon-web-services boto3 volumes


【解决方案1】:

这应该可以帮助您入门。正如评论者所建议的那样,这非常简单。您必须根据需要更改逻辑。

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'))

【讨论】:

    【解决方案2】:

    感谢您的回答。我已经更新了代码,现在它似乎工作正常。更新代码:

        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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 2019-11-14
      • 2020-01-06
      • 2019-04-04
      • 2019-06-17
      • 1970-01-01
      • 2015-11-19
      • 2020-07-20
      相关资源
      最近更新 更多