Created
June 18, 2015 08:58
-
-
Save ricfeatherstone/dc2c4e3d4592ac40b51e to your computer and use it in GitHub Desktop.
Update ~/.aws/credentials file when using IAM roles on EC2 instance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'net/http' | |
require 'json' | |
iam_info_uri = URI 'http://169.254.169.254/latest/meta-data/iam/info' | |
iam_info_response = Net::HTTP.get_response(iam_info_uri) | |
iam_info = JSON.parse(iam_info_response.body) | |
profile_name = iam_info['InstanceProfileArn'].split('/')[1] | |
creds_uri = URI 'http://169.254.169.254/latest/meta-data/iam/security-credentials/#{profile_name}' | |
creds_response = Net::HTTP.get_response(creds_uri) | |
creds = JSON.parse(creds_response.body) | |
access_key_id = creds['AccessKeyId'] | |
secret_access_key = creds['SecretAccessKey'] | |
token = creds['Token'] | |
File.open(ENV['HOME']+'/.aws/credentials', 'w'){ |file| | |
file.puts '[default]' | |
file.puts "aws_access_key_id=#{access_key_id}" | |
file.puts "aws_secret_access_key=#{secret_access_key}" | |
file.puts "aws_session_token=#{token}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment