Reputation: 46
I want to attach my newly created IAM Role to all my existence 250 instances, is there any "one-shot" way, because i don't want to go and attach one-by-one for all 250 instances.
Thank You
Upvotes: 1
Views: 2051
Reputation: 1
Off the back of Daniel's solution, I created something more readable that worked for me
#!/bin/bash
#### Variables
region=eu-west-2
profile_id=<insert_profile_from_/.aws/credentials>
iam_instance_profile=<insert_IAM_instance_profile>
instances=$(aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' --profile $profile_id --region $region | awk '{print $1}' | sed 's/[]","[]//g')
assign_instances()
{
for instance in $instances; do aws ec2 associate-iam-instance-profile --instance-id $instance --iam-instance-profile Name=$iam_instance_profile --region $region --profile $profile_id; done
}
assign_instances
Upvotes: 0
Reputation: 270294
The Python equivalent would be something like:
import boto3
ec2 = boto3.client('ec2', region_name='ap-southeast-2')
instances = ec2.describe_instances()
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
response = client.associate_iam_instance_profile(
IamInstanceProfile={Name='XYZ'},
InstanceId=instance['InstanceId']
)
(I didn't test it!)
Upvotes: 0
Reputation: 16302
There's not an API to assign an instance role to more than one instance at a time, but it should be pretty easy to write a few commands that would do it at the command line. There's also SDKs for most languages if you'd prefer a programmatic approach.
To add a little color to your ask, you'll need to create an instance profile associated with your role, and then attach that instance profile to each of your instances, not the role directly.
https://aws.amazon.com/blogs/security/new-attach-an-aws-iam-role-to-an-existing-amazon-ec2-instance-by-using-the-aws-cli/ has all the commands you need to do it, so you just need to iterate over the list and do it for each instance that doesn't already have the correct profile set.
If you need some help programming it, you should come up with some code yourself, paste it here, and we can assist further.
Update: since you don't seem to be ready to jump into the code end of this, I'll get you started in my favorite ad hoc execution environment, the posix shell:
iprofile="your-instance-profile-name"
aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' \
| xargs -n 1 -P 25 $aws ec2 associate-iam-instance-profile \
YourInstanceId --iam-instance-profile Name=${iprofile} --instance-id
that should list all your instances, and then, in parallel groups of 25, assiciate $iprofile
with each instance.
Upvotes: 2