通过boto3中的IAM角色过滤实例?

雅罗斯拉夫·布拉托夫(Yaroslav Bulatov)

有没有一种方法可以通过IAM角色过滤实例?基本上,我想要一个脚本来终止我启动的所有实例,但不涉及使用其他IAM角色启动的实例。

Madhukar Mohanraju

方法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

替换<Enter you Instance Profile ARN here>实例配置文件Arn

注意:您必须输入Instance Profile ArnNOTRole ARN

实例配置文件Arn的格式为:

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

然后,您可以将Instance-id's上面返回的列表传递terminate-instancecli命令。实例的IDS必须用空格隔开。

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

方法2:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

boto3:使用instanceprofile / IAM角色创建实例

如何使用Boto3启动具有IAM角色的EC2实例?

通过 boto3 担任 IAM 用户角色时拒绝访问

无法通过boto3或IAM角色访问通过CloudFront Origin Access Identity签名URL上传的文件?

通过boto3解析IAM策略文档的响应

如何在Boto3中按日期过滤Ec2实例的标记值

boto3:使用 IAM 角色的 S3 存储桶放置事件通知失败

python boto3将IAM角色附加/替换为ec2

如何仅使用Boto3创建AWS IAM角色附加托管策略

尝试使用Boto3创建IAM角色时,总是出现MalformedPolicyDocument错误

我应该使用boto3来仅通过IAM实例配置文件写入S3存储桶,但是如何?

Boto无法访问具有正确IAM角色的ECS容器内的存储桶(但Boto3可以)

启用 boto3 在 ECS 实例上发送 SES 而不使用 IAM 访问密钥/秘密

Boto3 EC2中的分页描述实例

boto3过滤器中的“或”条件

如何获取boto3中已过滤对象的大小

Boto3:调用 client.associate_iam_instance_profile 时 IAM 实例配置文件 ARN 无效

如何通过在Windows中配置boto3库来使用python启动所有ec2实例?

我可以在.aws / credentials中使用IAM角色替换aws密钥以使用boto3吗?

BOTO3:如何将标签“不等于”的实例过滤为某物?

带标签的Boto3 EC2实例过滤器

boto3:竞价型实例创建

如何在Boto3中获取IAM用户的内联策略文档?

如何在python boto3中获取iam用户的aws托管策略的策略文档?

使用 boto3 根据 AssumeRolePolicyDocument 中的操作列出角色名称

AWS Python Boto3 - 通过 id 获取实例运行时间

如何使用boto3通过名称获取状态RDS实例

如何通过SSH编写boto3代码访问我的实例

通过ec2进行迭代,描述实例boto3