Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. AWS_DEFAULT_REGION=ap-northeast-1
  4. export AWS_DEFAULT_REGION
  5.  
  6. list_roles=`mktemp`
  7. list_profiles=`mktemp`
  8.  
  9. aws iam list-roles| jq -r '.Roles[]' > $list_roles
  10. aws iam list-instance-profiles | jq -r '.InstanceProfiles[]' > $list_profiles
  11.  
  12. cat <<_JSON > ec2_role_policy.json
  13. {
  14. "Version": "2012-10-17",
  15. "Statement": [
  16. {
  17. "Effect": "Allow",
  18. "Principal": {
  19. "Service": "ec2.amazonaws.com"
  20. },
  21. "Action": "sts:AssumeRole"
  22. }
  23. ]
  24. }
  25. _JSON
  26.  
  27.  
  28. aws ec2 describe-instances |\
  29. jq -r '.Reservations[] | .Instances[] | select(.IamInstanceProfile==null) | [.InstanceId, (.Tags[] | select(.Key=="Name")).Value] | @tsv' |\
  30. while read instanceid name;do
  31. sleep=0
  32. role_name=ec2_${name%%[0-9]*}
  33.  
  34. exist_role=`cat $list_roles | jq -r "select(.RoleName==\"$role_name\")"`
  35. if [ -z "$exist_role" ]; then
  36. # create role
  37. role_arn=`aws iam create-role --role-name $role_name --assume-role-policy-document file://ec2_role_policy.json | jq -r '.Role | .Arn'`
  38. sleep=10
  39. else
  40. role_arn=`echo $exist_role | jq -r '.Arn'`
  41. fi
  42.  
  43. exist_profile=`cat $list_profiles | jq -r "select(.InstanceProfileName==\"$role_name\")"`
  44. if [ -z "$exist_profile" ]; then
  45. # create profile
  46. profile_arn=`aws iam create-instance-profile --instance-profile-name $role_name --instance-profile-name $role_name | jq -r '.Role | .Arn'`
  47. sleep=10
  48. else
  49. profile_arn=`echo $exist_profile | jq -r '.Arn'`
  50. fi
  51.  
  52. exist_role_in_profile=`aws iam list-instance-profiles-for-role --role-name $role_name | jq -r '.InstanceProfiles[]'`
  53. if [ -z "$exist_role_in_profile" ]; then
  54. # add role to profile
  55. aws iam add-role-to-instance-profile --role-name $role_name --instance-profile-name $role_name
  56. sleep=10
  57. fi
  58.  
  59. # waiting until create profile
  60. aws iam wait instance-profile-exists --instance-profile-name $role_name
  61. sleep $sleep
  62.  
  63. # attach role to EC2
  64. echo "$name : $instanceid , $role_name , $role_arn , $profile_arn"
  65. if ! aws ec2 associate-iam-instance-profile --instance-id $instanceid --iam-instance-profile Name=$role_name; then
  66. exit 1
  67. fi
  68.  
  69. done
  70.  
  71. rm -f $list_roles $list_profiles $list_associations
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement