【问题标题】:Filtering instances by IAM role in boto3?在boto3中按IAM角色过滤实例?
【发布时间】:2025-12-06 19:20:03
【问题描述】:

有没有办法按 IAM 角色过滤实例? 基本上我想要一个脚本来终止我已启动的所有实例,但不会触及使用其他 IAM 角色启动的实例。

【问题讨论】:

  • 你应该标记它们并使用它。可能不希望以这种方式使用 IAM 角色,并且如果其他任何人(或您不小心)尝试将 IAM 角色用于某些类似目的,那么当您意外终止不应终止的实例时,您就是 SOL,因为你做了一些意想不到的事情。标签就是以这种方式使用的。
  • 同意对实例配置文件进行过滤并不理想,但您可以使用 awscli 执行此操作(您可以使用 boto3 计算出等效项):aws ec2 describe-instances --query "Reservations [].Instances[].{id:InstanceId, role:IamInstanceProfile.Arn}"

标签: amazon-web-services amazon-ec2 boto3


【解决方案1】:

方法一:

如果只是一次性活动,可以考虑使用 aws-cli 本身。

使用以下 aws-cli 命令列出具有特定 IAM 角色的所有实例。

aws ec2 describe-instances --region us-east-1 --query 'Reservations[*].Instances[?IamInstanceProfile.Arn==`<Enter you Instance Profile ARN here>`].{InstanceId: InstanceId}' --output text

&lt;Enter you Instance Profile ARN here&gt; 替换为Instance Profile Arn

注意: 您必须输入 Instance Profile Arn 并且 NOT Role ARN

Instance Profile Arn 将采用以下形式:

arn:aws:iam::xxxxxxxxxxxx:instance-profile/Profile-ASDNSDLKJ

然后您可以将上面返回的Instance-id's 列表传递给terminate-instance cli 命令。 instance-ids 必须用空格分隔。

aws ec2 terminate-instances --instance-ids i-1234567890abcdef0 i-1234567890jkefpq1

方法二:

import boto3

client = boto3.client('ec2',region_name='us-east-1')
response = client.describe_instances(
    Filters=[
        {
            'Name': 'iam-instance-profile.arn',
            'Values': [
                'arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ',
            ]
        },
    ]
)
terminate_instance_list = []
for resp in response['Reservations']:
  for inst in resp['Instances']:
    #print inst['InstanceId']
    terminate_instance_list.append(inst['InstanceId'])


#print(terminate_instance_list)
if terminate_instance_list:
    response = client.terminate_instances(
        InstanceIds=terminate_instance_list
    )
    print(response)

【讨论】: