Yaroslav Bulatov
Yaroslav Bulatov

Reputation: 57973

Filtering instances by IAM role in boto3?

Is there a way to filter instances by IAM role? Basically I want a script that terminates all the instances that I've launched, but doesn't touch instances launched with other IAM roles.

Upvotes: 2

Views: 1493

Answers (1)

Madhukar Mohanraju
Madhukar Mohanraju

Reputation: 2863

Method 1:

If it is just a one-time activity, you can consider using aws-cli itself.

Use the below aws-cli command to list all instances with a particular IAM Role.

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

Replace <Enter you Instance Profile ARN here> with the Instance Profile Arn.

NOTE: You must enter the Instance Profile Arn and NOT the Role ARN.

Instance Profile Arn will be of the form:

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

You can then pass the list of Instance-id's returned above to the terminate-instance cli command. The instance-ids must be separated by spaces.

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

Method 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)

Upvotes: 4

Related Questions