Last active
August 29, 2015 14:06
-
-
Save detunized/e27719741b3dbf26c1c7 to your computer and use it in GitHub Desktop.
Rotate AWS credentials
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 | |
# This script rotates AWS credentials. | |
# It's very quick and dirty and unsafe. | |
# It's possible that something is gonna fail along the way and you're | |
# gonna end up with broken or no credentials at all. You can always fix | |
# them from the AWS dashboard later. | |
# The script expects ~/bin/aws-credentials to be present and executable. | |
# This file is overwritten with the new credentials at the end. | |
require "time" | |
require "yaml" | |
AWS_CREDENTIALS_PATH = File.join ENV["HOME"], "bin", "aws-credentials" | |
def installed? command | |
`which "#{command}"` && $?.success? | |
end | |
def ensure_installed command, message | |
unless installed? command | |
puts message | |
exit 1 | |
end | |
end | |
def aws command | |
`. aws-credentials && aws iam #{command}` | |
end | |
ensure_installed "aws", %Q{aws is not installed\nRun "sudo pip install awscli" to install} | |
# Grab old keys | |
old_keys = YAML.load aws "list-access-keys" | |
# Create new ones | |
new_keys = YAML.load aws "create-access-key" | |
# Retire old keys | |
old_keys["AccessKeyMetadata"].each do |keys| | |
aws "update-access-key --access-key-id #{keys["AccessKeyId"]} --status Inactive" | |
aws "delete-access-key --access-key-id #{keys["AccessKeyId"]}" | |
end | |
# Save the new keys into aws-credentials | |
File.open AWS_CREDENTIALS_PATH, "w", 0700 do |io| | |
io.write <<-EOT | |
#!/bin/sh | |
export AWS_ACCESS_KEY_ID="#{new_keys["AccessKey"]["AccessKeyId"]}" | |
export AWS_SECRET_ACCESS_KEY="#{new_keys["AccessKey"]["SecretAccessKey"]}" | |
export AWS_SECRET_KEY=$AWS_SECRET_ACCESS_KEY | |
EOT | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment