停止所有不包含 AWS 中具有特定值的标签的 ec2 实例

问题描述 投票:0回答:2

我需要在 python 中为 AWS lambda 函数编写一个脚本,以停止所有没有特定标签或该标签的特定值的 ec2 实例。

我将 boto3 与 python 一起使用来获取所有实例,并使用过滤器来过滤具有该特定标签或其标签值的所有实例,但无法获取在没有该特定标签或其值的情况下运行的实例。

import boto3
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    filters = [{
         'Name': 'tag:state:scheduleName',
         'Values': ['24x7']
       }]

    #get all instances   
    AllInstances=[instance.id for instance in ec2.instances.all()]
    # get instances with that tag and value
    instances = ec2.instances.filter(Filters=filters)

    RunningInstancesWithTag = [instance.id for instance in instances]

    RunningInstancesWithoutTag= [x for x in AllInstances if x not in  RunningInstancesWithTag]

    if len(RunningInstancesWithoutTag) > 0:
            print("found instances with out tag")
            ec2.instances.filter(InstanceIds = RunningInstancesWithoutTag).stop() #for stopping an ec2 instance
            print("instance stopped")
    else:
        print("let it be run as tag value is 24*7")
aws-lambda boto3
2个回答
1
投票

正如约翰在评论中所建议的那样,您使用过滤器使它过于复杂。

你想要这样的东西:

import boto3

ec2 = boto3.resource('ec2')

def lambda_handler(event, context):

    running_with = []
    running_without = []

    for instance in ec2.instances.all():

        if instance.state['Name'] != 'running':
            continue

        has_tag = False
        for tag in instance.tags:
            if tag['Key'] == 'scheduleName' and tag['Value'] == '24x7':
                has_tag = True
                break

        if has_tag:
            running_with.append(instance.id)
        else:
            running_without.append(instance.id)

    print("With: %s" % running_with)
    print("Without: %s" % running_without)

要点:

  • 不要使用过滤器,只需调用 ec2.instances.all() 即可。
  • 遍历实例,然后遍历标签并计数有无。

0
投票

此代码循环停止所有子组织中的所有实例。

import boto3

# Set the AWS Organizations client
org_client = boto3.client('organizations')

# Get all accounts in the organization
accounts = org_client.list_accounts()

# Loop through each account and stop all EC2 instances
for account in accounts['Accounts']:
    print(f"Stopping instances in account: {account['Name']} ({account['Id']})")
    
    # Get all running instances and stop them
    reservations = boto3.client('ec2').describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
    for reservation in reservations['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            print(f"Stopping instance: {instance_id}")
            boto3.client('ec2').stop_instances(InstanceIds=[instance_id])
© www.soinside.com 2019 - 2024. All rights reserved.