【问题标题】:is there a way to get name of IAM role attached to an EC2 instance with boto3?有没有办法使用 boto3 获取附加到 EC2 实例的 IAM 角色的名称?
【发布时间】:2021-09-21 14:22:59
【问题描述】:
我正在尝试列出在 python3 中使用 boto3 附加其 IAM 角色的所有 EC2 实例。但我没有找到任何方法可以将 IAM 角色附加到现有 EC2 实例。 boto3 中是否有任何方法可以做到这一点?
当我描述一个实例时,它有一个键名 IamInstanceProfile。其中包含实例配置文件 ID 和 iam 实例配置文件的 arn。我没有找到 IAM 实例配置文件的名称或有关附加到它的 IAM 角色的任何其他信息。我尝试使用实例配置文件 id 来描述实例配置文件,但它似乎描述了一个实例配置文件,我们需要实例配置文件的名称(而不是 id)。
有人可以帮忙吗?我可能遗漏了什么。
谢谢
【问题讨论】:
标签:
python-3.x
amazon-web-services
amazon-ec2
boto3
【解决方案1】:
您可以调用 IAM list_instance_profiles(),然后根据 EC2 describe_instances() 结果中的 ARN 或 ID 过滤结果。此响应将包含给定实例配置文件的 Roles。
Boto3 IAM documentation
【解决方案2】:
当我们描述 EC2 实例时,我们会得到具有 Arn 和 id 的 IamInstanceProfile 键。
Arn 附加了 IamInstanceProfile 名称。
Arn': 'arn:aws:iam::1234567890:instance-profile/instanceprofileOrRolename'
此名称可用于进一步操作,例如获取角色描述或列出附加到角色的策略。
谢谢
【解决方案3】:
您可以通过从实例对http://169.254.169.254/latest/meta-data/ 进行 HTTP 调用来获取 EC2 实例的元数据。
在您的情况下,您可能希望导航到 http://169.254.169.254/latest/meta-data/iam/security-credentials 以获取附加到实例的 IAM 角色。
EC2 Instance Metadata