How to Use the Instance Role Credentials Manually on an EC2 Instance
A couple of days ago I found myself needing to use the AWS CLI to perform some actions using the IAM Role of the local EC2 instance (and not my own -- partly because I didn't want to use/leave my credentials on the machine).
Crawling through the AWS documentation, I pieced together the steps one should follow to perform this action:
1. Ensure you have the AWS CLI installed
This should only be necessary for older machines that don't have the CLI installed by default. It's also unncessary if you plan to use environment variables.
sudo easy_install pip
# I had to fully qualify the path to Pip because /usr/local/bin didn't resolve under sudo:
sudo /usr/local/bin/pip install awscli
2. Query AWS Metadata for the credentials
# Call the metadata route at this address. Replace "IAM Role Name" with the Role
# assigned to the EC2 instance.
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<IAM Role Name>
# In my case, it was "ecsInstanceRole" because I was working with ECS
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ecsInstanceRole
You will see output like this:
{
"Code" : "Success",
"LastUpdated" : "2018-07-04T22:59:41Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "<redacted> access key",
"SecretAccessKey" : "<redacted> secret access key",
"Token" : "<redacted> Really really long session token",
"Expiration" : "2018-07-05T05:29:03Z"
}
3. Login using the AWS CLI
aws configure
# 1. Enter AccessKeyId supplied in the previous request
# 2. Enter SecretAccessKey supplied in the previous request
# 3. Enter default AWS region
# 4. Provide default output (probably just hit enter)
Alternatively, you can set those variables in the environment:
export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
4. Set the AWS Session Token
Without this, your credentials will be invalid!
You can save the token to the AWS CLI using the aws configuration
command:
aws configuration set aws_session_token "<Token>"
Or you can set the token in the environment:
export AWS_SESSION_TOKEN=<Token>
Conclusion
If you have successfully completed those steps, your AWS EC2 instances should be able to take actions within the AWS infrastructure with the permissions of the AWS IAM Role assigned. These steps should also eliminate the need for administrators to log in locally with their own account credentials, especially if they don't need rights beyond those provided to the machine.
Stumbling my way through the great wastelands of enterprise software development.