我需要在 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")
正如约翰在评论中所建议的那样,您使用过滤器使它过于复杂。
你想要这样的东西:
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)
要点:
此代码循环停止所有子组织中的所有实例。
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])