Skip to content

Instantly share code, notes, and snippets.

@alexrudy
Created August 21, 2017 18:57
Show Gist options
  • Save alexrudy/82a040504dcf2fc1df6414f98e22cb51 to your computer and use it in GitHub Desktop.
Save alexrudy/82a040504dcf2fc1df6414f98e22cb51 to your computer and use it in GitHub Desktop.
Quick python command to strip and insert AWS keys into SQL files.
#!/usr/bin/env python
import click
import re
import os
import contextlib
@contextlib.contextmanager
def backup_file(file, mode='w', replace=False):
"""Open a backup file for writing"""
with open(file.name + ".bak", "w") as bak:
yield bak
if replace:
file.close()
os.remove(file.name)
os.rename(file.name+".bak", file.name)
def strip_keys(file, force=False):
"""Strip keys from an individual file."""
with backup_file(file, replace=force) as out:
for line in file:
g = re.search(r"CREDENTIALS\s+(AS\s+)?'aws_access_key_id=\S+;aws_secret_access_key=\S+'", line)
if g:
line = line.replace(g.group(0), "CREDENTIALS 'aws_access_key_id=<aws_id>;aws_secret_access_key=<aws_secret>'")
out.write(line)
@click.group()
def main():
"""Main command for stripping or insterting keys."""
pass
def insert_keys(file, force=False):
"""docstring for insert_keys"""
with backup_file(file, replace=force) as out:
for line in file:
g = re.search(r"CREDENTIALS\s+(AS\s+)?'aws_access_key_id=\S+;aws_secret_access_key=\S+'", line)
if g:
line = line.replace("<aws_id>", os.environ['AWSID'])
line = line.replace("<aws_secret>", os.environ['AWSKEY'])
out.write(line)
@main.command()
@click.argument("files", type=click.File('r'), nargs=-1)
@click.option("-f", "--force", is_flag=True, help="Force in place opeartion")
def insert(files, force):
"""Insert AWS keys into some SQL"""
for file in files:
insert_keys(file, force)
@main.command()
@click.argument("files", type=click.File('r'), nargs=-1)
@click.option("-f", "--force", is_flag=True, help="Force in place opeartion")
def strip(files, force):
"""Strip AWS Keys from CREDENTIALS commands"""
for file in files:
strip_keys(file, force)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment