filtering ec2 instances by associated IAM role wit

2019-08-24 15:23发布

问题:

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]