Created
January 16, 2018 15:14
-
-
Save acatton/2fc6aeb4ea4c6dc555669cbcd61b6163 to your computer and use it in GitHub Desktop.
aws-docker
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 python3 | |
# $ docker run --rm -it $(docker-aws) alpine | |
# / # env | grep -i aws | |
# AWS_DEFAULT_REGION=eu-central-1 | |
# AWS_SESSION_TOKEN=... | |
# AWS_ACCESS_KEY_ID=... | |
# AWS_SECRET_ACCESS_KEY=... | |
# | |
# When you don't want to mount `~/.aws:/root/.aws` because SELinux prevents you to do so. | |
# Or because your container doesn't run as root, and its user doesn't have a home directory. | |
# This script just needs python 3, no depency. | |
import argparse | |
import configparser | |
import os | |
import shlex | |
DEFAULT_CREDENTIALS = os.path.expanduser('~/.aws/credentials') | |
DEFAULT_CONFIG = os.path.expanduser('~/.aws/config') | |
REMAPPING = {'region': 'AWS_DEFAULT_REGION', 'aws_access_key_id': 'AWS_ACCESS_KEY_ID', | |
'aws_secret_access_key': 'AWS_SECRET_ACCESS_KEY', | |
'aws_session_token': 'AWS_SESSION_TOKEN'} | |
def get_parser(): | |
parser = argparse.ArgumentParser(description="Generate docker command line to use AWS") | |
parser.add_argument( | |
'--credentials', metavar='FNAME', | |
default=os.environ.get('AWS_CONFIG_FILE', DEFAULT_CONFIG)) | |
parser.add_argument( | |
'--config', metavar='FNAME', | |
default=os.environ.get('AWS_SHARED_CREDENTIALS_FILE', DEFAULT_CREDENTIALS)) | |
parser.add_argument( | |
'--profile', metavar='PROFILE', default=os.environ.get('AWS_PROFILE', 'default')) | |
return parser | |
def generate_commandline(variables): | |
"""Generate the command line form the variables: | |
>>> generate_commandline([('foo bar', 'baz'), ('qux', 'Hello world')]) | |
"-e 'foo bar'=baz -e qux='Hello world'" | |
""" | |
acc = [] | |
for key, val in variables: | |
acc.append('-e ') | |
acc.append(shlex.quote(key)) | |
acc.append('=') | |
acc.append(shlex.quote(val)) | |
acc.append(' ') | |
return ''.join(acc).rstrip() | |
def run(): | |
args = get_parser().parse_args() | |
config = configparser.ConfigParser() | |
config.read(args.config) | |
config.read(args.credentials) | |
profile = config[args.profile] | |
variables = {REMAPPING[k]: v for k, v in profile.items() if k in REMAPPING} | |
print(generate_commandline(variables.items())) | |
if __name__ == '__main__': | |
run() | |
# This work is free. You can redistribute it and/or modify it under the | |
# terms of the Do What The Fuck You Want To Public License, Version 2, | |
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment