用 AWS Metadata API 获取本机的 IAM Role 的脚本

获取当前Instance的IAM Role名:

1
instance_profile=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/`  

获取Key ID和Secret:

1
2
aws_access_key_id=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/${instance_profile} | grep AccessKeyId | cut -d':' -f2 | sed 's/[^0-9A-Z]*//g'`  
aws_secret_access_key=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/${instance_profile} | grep SecretAccessKey | cut -d':' -f2 | sed 's/[^0-9A-Za-z/+=]*//g'`

设置环境变量:

1
2
export AWS_ACCESS_KEY_ID=${aws_access_key_id}
export AWS_SECRET_ACCESS_KEY=${aws_secret_access_key}