Skip to content

Instantly share code, notes, and snippets.

@sameergautam
Created July 19, 2019 06:03
Show Gist options
  • Save sameergautam/fdf6ce9505a3d79c5b06e434bb8e4aee to your computer and use it in GitHub Desktop.
Save sameergautam/fdf6ce9505a3d79c5b06e434bb8e4aee to your computer and use it in GitHub Desktop.
Update the IAM instance profile of the instances. The initial IAM instance profile attached to the instance must have necessary permissions to carry out the modification task
#!/bin/bash
ROLE_TO_ATTACH=$(aws iam list-roles --query Roles[*].RoleName --output json | grep -i `echo $PROJECT` | cut -d \" -f2)
AWS_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
AWS_IAM_PROFILE_ASSOCIATION=$(aws ec2 describe-iam-instance-profile-associations \
--region=$(echo $AWS_REGION) \
--filters "Name=instance-id,Values=$(echo $INSTANCE_ID)" \
--output text | egrep -o 'iip\-assoc\-[[:alnum:]]+')
aws ec2 replace-iam-instance-profile-association \
--association-id $AWS_IAM_PROFILE_ASSOCIATION \
--iam-instance-profile Name=$(echo $ROLE_TO_ATTACH) \
--region=$(echo $AWS_REGION)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment