Skip to content

Instantly share code, notes, and snippets.

@dooferlad
Last active April 6, 2023 13:16
Show Gist options
  • Save dooferlad/8815c5d70f49eddff0b974b43ffee59a to your computer and use it in GitHub Desktop.
Save dooferlad/8815c5d70f49eddff0b974b43ffee59a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from subprocess import run
import os
import sys
import configparser
import yaml
def main(args, commands):
args[0] = "/usr/local/bin/sops"
config = configparser.ConfigParser()
config.read(os.path.expanduser("~/.aws/config"))
profile_ids = {}
for section in config.sections():
if "role_arn" in config[section] and section.startswith("profile "):
profile_id = config[section]["role_arn"].split(":")[4]
assert config[section]["role_arn"].split(":")[:3] == ["arn", "aws", "iam"]
profile_ids[profile_id] = section[len("profile "):]
profile = None
new_args = []
for arg in args:
if not (arg.startswith("-") or arg in commands):
arg = os.path.abspath(arg)
filename = os.path.basename(arg)
filedir = os.path.dirname(arg)
new_args.append(arg)
search_dir = filedir
while True:
if os.path.exists(os.path.join(search_dir, ".sops.yaml")):
with open(os.path.join(search_dir, ".sops.yaml")) as f:
sops_config = yaml.safe_load(f)
bits = sops_config["creation_rules"][0]["kms"].split(":")
assert bits[:3] == ['arn', 'aws', 'kms']
aws_profile_id = bits[4]
profile = profile_ids[aws_profile_id]
os.environ["AWS_PROFILE"] = profile
break
search_dir = os.path.dirname(search_dir)
if len(search_dir) == 0:
raise ValueError("Unable to find .sops.yaml")
if ".yaml" in filename:
args = [args[0], "--output-type=yaml", "--input-type=yaml"] + args[1:]
v = run(args, env=os.environ)
exit(v.returncode)
if __name__ == '__main__':
c = """
COMMANDS:
exec-env execute a command with decrypted values inserted into the environment
exec-file execute a command with the decrypted contents as a temporary file
publish Publish sops file or directory to a configured destination
keyservice start a SOPS key service server
groups modify the groups on a SOPS file
updatekeys update the keys of a SOPS file using the config file
help, h Shows a list of commands or help for one command
"""
commands = []
for line in c.splitlines():
bits = line.split()
if len(bits) > 1:
commands.append(bits[0].strip(","))
main(sys.argv, commands)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment