AWS EC2 get instancesId running according to the label set

I instanceId method can get directly through the label is not found, you can only put all the instances were getting filtered. If the water faithful have a better way to welcome the message.

Run the script needs to configure the local AWS CLI

# -*- coding: utf-8 -*-
import boto3


def get_instancesId():
    # 首先获取所有的instances,然后再对标签过滤 
    instances_list = []
    instances_running_list = []
    ec2 = boto3.resource('ec2')
    for instance in ec2.instances.all():
        if instance.tags is None:
            continue
        for tag in instance.tags:
            # 这里输入你的标签的key,和标签的value
            if tag['Key'] == 'user_key' and tag['Value'] == 'user_value':
                instances_list.append(instance.id)
    
    # 这里用来过滤上上面instance是否是正在运行的
    client = boto3.client('ec2')
    resp = client.describe_instances(InstanceIds=instances_list)
    for reservation in resp['Reservations']:
        if reservation['Instances'][0]['State']['Name'] == 'running':
            instances_running_list.append(reservation['Instances'][0]['InstanceId'])
    return instances_running_list

Guess you like

Origin www.cnblogs.com/crazyzero/p/11321777.html