Skip to content

Instantly share code, notes, and snippets.

@fliphess
Last active October 29, 2019 17:16
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 fliphess/c2f6778f7d7d4b2b141a02b9b8d387bd to your computer and use it in GitHub Desktop.
Save fliphess/c2f6778f7d7d4b2b141a02b9b8d387bd to your computer and use it in GitHub Desktop.
util to set aws credentials in your environment for a specific command
#!/usr/bin/env python3
import argparse
import configparser
import subprocess
import os
import sys
CONFIG = os.path.expanduser("~/.aws/credentials")
def parse_arguments():
parser = argparse.ArgumentParser(description="Run commands with AWS credentials in the environment")
parser.add_argument(
'--creds',
'-c',
default=CONFIG,
dest="credentials_file",
help='The ini file to retrieve AWS credentials from (default: {})'.format(CONFIG),
required=False
)
parser.add_argument(
'--profile',
'-p',
default=None,
help='Use this aws profile'
)
parser.add_argument(
'command',
nargs='+',
help="The command to execute with AWS credentials",
)
arguments = parser.parse_args()
if not os.path.isfile(arguments.credentials_file):
parser.error('Credentials file {} not found!'.format(arguments.credentials_file))
return arguments
def run_command(command, environment):
try:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, env=environment)
while True:
next_line = process.stdout.readline().decode()
is_done = process.poll()
if next_line == '' and is_done is not None:
break
elif next_line == '\n' or next_line == '':
continue
print(next_line.strip())
sys.exit(process.returncode)
except OSError as e:
sys.exit(1)
def main():
arguments = parse_arguments()
config = configparser.ConfigParser()
config.read(arguments.credentials_file)
environment = os.environ.copy()
environment['AWS_ACCESS_KEY_ID'] = config.get(arguments.profile or '', "aws_access_key_id")
environment['AWS_SECRET_ACCESS_KEY'] = config.get(arguments.profile or '', "aws_secret_access_key")
run_command(command=' '.join(arguments.command), environment=environment)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment