Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- AWS_DEFAULT_REGION=ap-northeast-1
- export AWS_DEFAULT_REGION
- list_roles=`mktemp`
- list_profiles=`mktemp`
- aws iam list-roles| jq -r '.Roles[]' > $list_roles
- aws iam list-instance-profiles | jq -r '.InstanceProfiles[]' > $list_profiles
- cat <<_JSON > ec2_role_policy.json
- {
- "Version": "2012-10-17",
- "Statement": [
- {
- "Effect": "Allow",
- "Principal": {
- "Service": "ec2.amazonaws.com"
- },
- "Action": "sts:AssumeRole"
- }
- ]
- }
- _JSON
- aws ec2 describe-instances |\
- jq -r '.Reservations[] | .Instances[] | select(.IamInstanceProfile==null) | [.InstanceId, (.Tags[] | select(.Key=="Name")).Value] | @tsv' |\
- while read instanceid name;do
- sleep=0
- role_name=ec2_${name%%[0-9]*}
- exist_role=`cat $list_roles | jq -r "select(.RoleName==\"$role_name\")"`
- if [ -z "$exist_role" ]; then
- # create role
- role_arn=`aws iam create-role --role-name $role_name --assume-role-policy-document file://ec2_role_policy.json | jq -r '.Role | .Arn'`
- sleep=10
- else
- role_arn=`echo $exist_role | jq -r '.Arn'`
- fi
- exist_profile=`cat $list_profiles | jq -r "select(.InstanceProfileName==\"$role_name\")"`
- if [ -z "$exist_profile" ]; then
- # create profile
- profile_arn=`aws iam create-instance-profile --instance-profile-name $role_name --instance-profile-name $role_name | jq -r '.Role | .Arn'`
- sleep=10
- else
- profile_arn=`echo $exist_profile | jq -r '.Arn'`
- fi
- exist_role_in_profile=`aws iam list-instance-profiles-for-role --role-name $role_name | jq -r '.InstanceProfiles[]'`
- if [ -z "$exist_role_in_profile" ]; then
- # add role to profile
- aws iam add-role-to-instance-profile --role-name $role_name --instance-profile-name $role_name
- sleep=10
- fi
- # waiting until create profile
- aws iam wait instance-profile-exists --instance-profile-name $role_name
- sleep $sleep
- # attach role to EC2
- echo "$name : $instanceid , $role_name , $role_arn , $profile_arn"
- if ! aws ec2 associate-iam-instance-profile --instance-id $instanceid --iam-instance-profile Name=$role_name; then
- exit 1
- fi
- done
- rm -f $list_roles $list_profiles $list_associations
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement