filtering ec2 instances by associated IAM role with boto

风流意气都作罢 提交于 2019-12-12 04:02:32

问题


I have a few instances on AWS that are associated with the same IAM Role. I'm looking to write a code that returns these instances.
Based from this document: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html, I see that there is an available filter iam-instance-profile.arn. I'm just not sure how I would go about using that or if that is what I should be using.

This is an example where instances are filtered by tags.

conn = boto.ec2.connect_to_region('ap-southeast-1')
reservations = conn.get_all_instances(filters={"tag:Name": "my-instance-1"});

for reservation in reservations:
    instance = reservation.instances[0] 

I'd like to do something similar except with an IAM Role as the filter.

Another thing - the example above conn.get_all_instances(filters={"tag:Name": "my-instance-1"});returns reservations. I'd like to get the instances without having to get them through reservations. For example: conn.get_only_instances(instance_ids=['i-cc186913']) returns me the instance.
What is the best way where I could have a filter (IAM Role) and return ONLY instances (not getting them through reservations)?


回答1:


Pass your instance profile ARN for that role (which you can get from IAM dashboard or you can construct it). Example:

conn.get_only_instances(filters={"iam-instance-profile.arn": "arn:aws:iam::<your-account-number>:instance-profile/<your-role-name>"})

It will return a list of instance and you can loop through it.

>>> conn.get_only_instances(filters={"iam-instance-profile.arn":"arn:aws:iam::123456781221:instance-profile/stackoverflowRole"})
[Instance:i-8ba223ab]


来源:https://stackoverflow.com/questions/34891683/filtering-ec2-instances-by-associated-iam-role-with-boto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!