Skip to content

Instantly share code, notes, and snippets.

@f440
Last active November 6, 2015 03:38
Show Gist options
  • Save f440/a31232b22d5f5e0a4e6e to your computer and use it in GitHub Desktop.
Save f440/a31232b22d5f5e0a4e6e to your computer and use it in GitHub Desktop.
eval "$(aws-env XXX)" することで、 credential から XXX profile を探して AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION をセット
#!/usr/bin/env ruby
class Parser
# python's config format: https://docs.python.org/2/library/configparser.html
def self.parse(contents)
sections = {}
contents.each_line do |line|
case line
when /\s*[#;]/, /^\s*$/
# skip
when /^\s*\[(.*)\]/
sections[$1] = {}
when /^\s*(.*)(?:=|: )(.*)\s*$/
section = sections.keys.last
sections[section][$1] = $2
end
end
sections
end
def self.load_file(file)
content = File.open(file).read
parse(content)
end
end
profile_name = ARGV[0] || "default"
credential_file = File.expand_path(".aws/credentials", ENV['HOME'])
unless File.exists? credential_file
abort "Missing credential file: #{credential_file}"
end
profiles = Parser.load_file(credential_file)
profile = profiles[profile_name]
if profile.nil?
abort "Can't find: #{profile_name}"
end
config_file =
ENV.fetch('AWS_CONFIG_FILE', File.expand_path(".aws/config", ENV['HOME']))
if File.exists? config_file
configs = Parser.load_file(config_file)
config_profile = configs["profile #{profile_name}"] || configs["default"] || {}
if config_profile["region"]
default_region = config_profile["region"]
end
end
puts <<-SHELL
# [#{profile_name}]
export AWS_ACCESS_KEY_ID='#{profile["aws_access_key_id"]}'
export AWS_SECRET_ACCESS_KEY='#{profile["aws_secret_access_key"]}'
SHELL
puts <<-SHELL if default_region
export AWS_DEFAULT_REGION='#{default_region}'
SHELL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment