简体   繁体   中英

Adding multiple filters in boto3

Hi I have a requirement to fetch ec2 instance details with tags as follows

prod = monitor

test = monitor

The objective is to list instances with these tags only. I was able to add one filter but not sure how to use multiple filters in ec2.instances.filter(Filters

from collections import defaultdict

import boto3

# Connect to EC2
ec2 = boto3.resource('ec2')

# Get information for all running instances
running_instances = ec2.instances.filter(Filters=[{
    'Name': 'instance-state-name',
    'Values': ['running'] ,
    'Name': 'tag:prod',
    'Values': ['monitor']}])

ec2info = defaultdict()
for instance in running_instances:
    for tag in instance.tags:
        if 'Name'in tag['Key']:
            name = tag['Value']
            
                    
    # Add instance info to a dictionary         
    ec2info[instance.id] = {
        'Name': name,
        'Type': instance.instance_type,
        'State': instance.state['Name'],
        'Private IP': instance.private_ip_address,
        'Public IP': instance.public_ip_address,
        'Launch Time': instance.launch_time
        }

attributes = ['Name', 'Type', 'State', 'Private IP', 'Public IP', 'Launch Time']
for instance_id, instance in ec2info.items():
    for key in attributes:
        print("{0}: {1}".format(key, instance[key]))
    print("------")

Your syntax does not quite seem correct. You should be supplying a list of dictionaries . You should be able to duplicate tags, too:

Filters=[
    {'Name': 'instance-state-name', 'Values': ['running']},
    {'Name': 'tag:prod', 'Values': ['monitor']},
    {'Name': 'tag:test', 'Values': ['monitor']},
]

This should return instances with both of those tags .

If you are wanting instances with either of the tags, then I don't think you can filter it in a single call. Instead, use ec2.instances.all() , then loop through the returned instances using Python code and apply your logic.

Try this;

for example;

response = ce.get_cost_and_usage(
            Granularity='MONTHLY',
            TimePeriod={
                'Start': start_date,
                'End': end_date
            },
            GroupBy=[
                {
                    'Type': 'DIMENSION',
                    'Key': 'SERVICE'
                },
            ],
            Filter=
                {
                    "Dimensions": { "Key": "LINKED_ACCOUNT", "Values": [awslinkedaccount[0]] }, 
                    "Dimensions": { "Key": "RECORD_TYPE", "Values": ["Usage"] },
                },


            Metrics=[
                'BLENDED_COST',
            ],
        )


print(response)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM