Skip to content

Instantly share code, notes, and snippets.

@ricfeatherstone
Created June 18, 2015 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricfeatherstone/dc2c4e3d4592ac40b51e to your computer and use it in GitHub Desktop.
Save ricfeatherstone/dc2c4e3d4592ac40b51e to your computer and use it in GitHub Desktop.
Update ~/.aws/credentials file when using IAM roles on EC2 instance.
#!/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